<?php
/**
 * Plugin Name: Kurs Booking
 * Description: Schlankes Buchungssystem fuer Reitkurse
 * Version: 1.1.0
 * Author: Webwerkstatt
 * Author URI: https://web-werkstatt.at
 * Text Domain: kurs-booking
 * Domain Path: /languages
 * Requires at least: 6.0
 * Requires PHP: 8.0
 *
 * @package KursBooking
 */

declare(strict_types=1);

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Plugin constants.
define( 'KURS_BOOKING_VERSION', '1.3.1' );
define( 'KURS_BOOKING_PATH', plugin_dir_path( __FILE__ ) );
define( 'KURS_BOOKING_URL', plugin_dir_url( __FILE__ ) );
define( 'KURS_BOOKING_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Autoloader for plugin classes
 *
 * @param string $class The class name to load.
 */
spl_autoload_register(
	function ( string $class ): void {
		// Only handle our classes.
		if ( strpos( $class, 'Kurs_Booking_' ) !== 0 ) {
			return;
		}

		// Convert class name to file name.
		// Kurs_Booking_Kurs -> class-kurs.php.
		$class_name = substr( $class, 13 ); // Remove 'Kurs_Booking_' prefix.
		$file_name  = 'class-' . strtolower( str_replace( '_', '-', $class_name ) ) . '.php';
		$file_path  = KURS_BOOKING_PATH . 'includes/' . $file_name;

		if ( file_exists( $file_path ) ) {
			require_once $file_path;
		}
	}
);

/**
 * Initialize the plugin
 */
function kurs_booking_init(): void {
	// Load text domain.
	load_plugin_textdomain(
		'kurs-booking',
		false,
		dirname( KURS_BOOKING_BASENAME ) . '/languages'
	);

	// Initialize capabilities (must be early for permission checks).
	Kurs_Booking_Capabilities::init();

	// Initialize REST API for Customer Portal.
	Kurs_Booking_REST_API::init();

	// Initialize core classes.
	Kurs_Booking_Kurs::init();
	Kurs_Booking_Buchung::init();

	// Sprint 8.1: Initialize Dienstleistungen (Produktarten) management.
	Kurs_Booking_Dienstleistungen::init();

	// Video module (conditional).
	if ( Kurs_Booking_Settings::is_module_active( 'videos' ) ) {
		Kurs_Booking_Video::init();
		Kurs_Booking_Video_Bundle::init();
		Kurs_Booking_Video_Upload::init();
		Kurs_Booking_Video_Service::init_webhook();
	}

	// Initialize AJAX handlers (both admin and frontend).
	Kurs_Booking_Ajax::init();

	// Initialize Email system.
	Kurs_Booking_Email::init();

	// sevDesk module (conditional).
	if ( Kurs_Booking_Settings::is_module_active( 'sevdesk' ) ) {
		Kurs_Booking_SevDesk::init();
	}

	// Sprint 4.11: Initialize Custom Fields module (admin metaboxes + booking validation).
	Kurs_Booking_Custom_Fields::init();

	// DSGVO/GDPR Privacy Export and Eraser hooks.
	Kurs_Booking_Privacy::init();

	// Admin only.
	if ( is_admin() ) {
		Kurs_Booking_Admin::init();
		Kurs_Booking_Settings::init();
		Kurs_Booking_Post_Navigation::init();
		Kurs_Booking_Field_Tree::init();

		// Video admin (conditional).
		if ( Kurs_Booking_Settings::is_module_active( 'videos' ) ) {
			Kurs_Booking_Video_Admin::init();
		}
	}

	// Frontend only.
	if ( ! is_admin() || wp_doing_ajax() ) {
		Kurs_Booking_Frontend::init();
	}
}
add_action( 'plugins_loaded', 'kurs_booking_init' );

/**
 * Register Kadence migration meta fields for REST API access.
 *
 * WordPress treats meta keys starting with underscore as "protected".
 * Protected meta cannot be edited via REST API unless explicitly registered
 * with show_in_rest and auth_callback.
 *
 * This fixes the error: "You are not authorized to edit the custom field _kadence_migrated_at"
 *
 * @since 1.3.2
 */
function kurs_booking_register_migration_meta(): void {
	$meta_fields = array(
		'_kadence_migrated_at'       => 'string',
		'_kadence_migration_status'  => 'string',
		'_kadence_requires_review'   => 'string',
		// Also register non-prefixed versions used by migration tool.
		'kadence_migrated_at'        => 'string',
		'kadence_migration_status'   => 'string',
		'kadence_requires_review'    => 'string',
	);

	$post_types = array( 'post', 'page' );

	foreach ( $post_types as $post_type ) {
		foreach ( $meta_fields as $meta_key => $type ) {
			register_post_meta(
				$post_type,
				$meta_key,
				array(
					'single'            => true,
					'type'              => $type,
					'show_in_rest'      => true,
					'auth_callback'     => function () {
						return current_user_can( 'edit_posts' );
					},
					'sanitize_callback' => 'sanitize_text_field',
				)
			);
		}
	}
}
add_action( 'init', 'kurs_booking_register_migration_meta' );

/**
 * Plugin activation hook
 */
function kurs_booking_activate(): void {
	// Initialize post types to register rewrite rules.
	Kurs_Booking_Kurs::register_post_type();
	Kurs_Booking_Kurs::register_taxonomy();
	Kurs_Booking_Buchung::register_post_type();
	Kurs_Booking_Video::register_post_type();

	// Flush rewrite rules.
	flush_rewrite_rules();

	// Set default options.
	$defaults = array(
		'kurs_booking_version' => KURS_BOOKING_VERSION,
	);

	foreach ( $defaults as $key => $value ) {
		if ( get_option( $key ) === false ) {
			add_option( $key, $value );
		}
	}

	// Initialize default booking fields (Name, Email, Phone).
	Kurs_Booking_Settings::init_default_booking_fields();

	// Sprint 8.1: Install default Dienstleistungen (Produktarten).
	Kurs_Booking_Dienstleistungen::install_defaults();
}
register_activation_hook( __FILE__, 'kurs_booking_activate' );

/**
 * Plugin deactivation hook
 */
function kurs_booking_deactivate(): void {
	flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'kurs_booking_deactivate' );

/**
 * Enqueue admin styles and scripts
 *
 * @param string $hook_suffix The current admin page hook suffix.
 */
function kurs_booking_admin_enqueue( string $hook_suffix ): void {
	$screen = get_current_screen();

	if ( ! $screen ) {
		return;
	}

	// Check if we're on a kurs-booking related screen.
	$is_kurs_screen = (
		// Post type screens (edit, new, list).
		in_array( $screen->post_type, array( 'kurs', 'kurs-buchung', 'kurs-video' ), true ) ||
		// Settings page.
		'kurs_page_kurs-booking-settings' === $screen->id ||
		// Edit screens have format: post_type (e.g., 'kurs' for edit.php?post_type=kurs).
		in_array( $screen->id, array( 'kurs', 'kurs-buchung', 'kurs-video', 'edit-kurs', 'edit-kurs-buchung', 'edit-kurs-video' ), true )
	);

	if ( ! $is_kurs_screen ) {
		return;
	}

	// Enqueue WordPress's jQuery UI Sortable for drag & drop.
	wp_enqueue_script( 'jquery-ui-sortable' );

	// Admin CSS.
	wp_enqueue_style(
		'kurs-booking-admin',
		KURS_BOOKING_URL . 'assets/css/admin.css',
		array(),
		KURS_BOOKING_VERSION
	);

	// Admin JavaScript.
	wp_enqueue_script(
		'kurs-booking-admin',
		KURS_BOOKING_URL . 'assets/js/admin.js',
		array( 'jquery', 'jquery-ui-sortable' ),
		KURS_BOOKING_VERSION,
		array(
			'strategy'  => 'defer',
			'in_footer' => true,
		)
	);

	// Localize script with i18n and settings.
	wp_localize_script(
		'kurs-booking-admin',
		'kursBookingAdmin',
		array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'kurs_booking_admin' ),
			'i18n'    => array(
				'confirm_delete'           => __( 'Sind Sie sicher?', 'kurs-booking' ),
				'add_variant'              => __( 'Variante hinzufuegen', 'kurs-booking' ),
				'remove'                   => __( 'Entfernen', 'kurs-booking' ),
				'min_variant'              => __( 'Mindestens eine Variante erforderlich.', 'kurs-booking' ),
				'ticket'                   => __( 'Ticket', 'kurs-booking' ),
				'new_ticket'               => __( 'Neues Ticket', 'kurs-booking' ),
				'sevdesk_testing'          => __( 'Teste Verbindung...', 'kurs-booking' ),
				'sevdesk_creating_invoice' => __( 'Erstelle Rechnung...', 'kurs-booking' ),
				'sevdesk_confirm_invoice'  => __( 'Soll eine sevDesk-Rechnung für diese Buchung erstellt werden?', 'kurs-booking' ),
				'sevdesk_connection_error' => __( 'Verbindungsfehler', 'kurs-booking' ),
			),
		)
	);

	// Enqueue media library for logo upload on settings page.
	if ( 'kurs_page_kurs-booking-settings' === $screen->id ) {
		wp_enqueue_media();
	}
}
add_action( 'admin_enqueue_scripts', 'kurs_booking_admin_enqueue' );

/**
 * Load shortcodes
 */
require_once KURS_BOOKING_PATH . 'includes/shortcodes/video-player.php';

/**
 * Load video access template
 */
require_once KURS_BOOKING_PATH . 'templates/video-access.php';

/**
 * REST API Health Check endpoint
 */
function kurs_booking_register_rest_routes(): void {
	register_rest_route(
		'kurs-booking/v1',
		'/health',
		array(
			'methods'             => 'GET',
			'callback'            => function () {
				return array(
					'status'  => 'ok',
					'version' => KURS_BOOKING_VERSION,
				);
			},
			'permission_callback' => '__return_true',
		)
	);
}
add_action( 'rest_api_init', 'kurs_booking_register_rest_routes' );
