<?php
/**
 * Plugin Name: Rentals & Bookings — Solo & Marketplace
 * Plugin URI: https://wahra.tn/plugins/
 * Description: Complete rental and booking management for WooCommerce. Works standalone (solo vendor) or with Dokan Marketplace. Mobile-first wizard, advanced pricing, multi-step payments.
 * Version: 2.3.0
 * Author: Wahra Team
 * Author URI: https://wahra.tn
 * Text Domain: wahra-rentals-bookings
 * Domain Path: /languages
 * Requires at least: 6.6
 * Requires PHP: 8.1
 * WC requires at least: 8.0
 * WC tested up to: 10.4.3
 * Requires Plugins: woocommerce
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

// Plugin constants
define('WAHRB_VERSION', '2.3.0');
define('WAHRB_PLUGIN_FILE', __FILE__);
define('WAHRB_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WAHRB_PLUGIN_URL', plugin_dir_url(__FILE__));
define('WAHRB_PLUGIN_BASENAME', plugin_basename(__FILE__));
define('WAHRB_TEXT_DOMAIN', 'wahra-rentals-bookings');

/**
 * Main plugin class
 */
final class Wahra_Rentals_Bookings {

    /**
     * Plugin version
     *
     * @var string
     */
    public string $version = '2.3.0';

    /**
     * Minimum PHP version required
     *
     * @var string
     */
    public string $min_php = '8.1';

    /**
     * Minimum WordPress version required
     *
     * @var string
     */
    public string $min_wp = '6.6';

    /**
     * Minimum WooCommerce version required
     *
     * @var string
     */
    public string $min_wc = '8.0';

    /**
     * Single instance
     *
     * @var Wahra_Rentals_Bookings|null
     */
    private static ?Wahra_Rentals_Bookings $instance = null;

    /**
     * Get single instance
     *
     * @return Wahra_Rentals_Bookings
     */
    public static function instance(): Wahra_Rentals_Bookings {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        $this->define_constants();
        $this->init_hooks();
    }

    /**
     * Define additional constants
     */
    private function define_constants(): void {
        if (!defined('WAHRB_DB_VERSION')) {
            define('WAHRB_DB_VERSION', '1.2.0'); // Phase 2: form_templates, coupons, coupon_usage tables
        }
    }

    /**
     * Initialize hooks
     */
    private function init_hooks(): void {
        // Activation and deactivation hooks
        register_activation_hook(WAHRB_PLUGIN_FILE, [$this, 'activate']);
        register_deactivation_hook(WAHRB_PLUGIN_FILE, [$this, 'deactivate']);

        // Load plugin after all plugins are loaded
        add_action('plugins_loaded', [$this, 'init_plugin'], 10);
    }

    /**
     * Activate plugin
     */
    public function activate(): void {
        require_once WAHRB_PLUGIN_DIR . 'includes/class-wahrb-activator.php';
        WAHRB_Activator::activate();
    }

    /**
     * Deactivate plugin
     */
    public function deactivate(): void {
        require_once WAHRB_PLUGIN_DIR . 'includes/class-wahrb-deactivator.php';
        WAHRB_Deactivator::deactivate();
    }

    /**
     * Initialize plugin
     */
    public function init_plugin(): void {
        // Check requirements
        if (!$this->check_requirements()) {
            return;
        }

        // Load dependencies
        $this->load_dependencies();

        // Initialize components
        $this->init_components();
    }

    /**
     * Check plugin requirements
     *
     * @return bool
     */
    private function check_requirements(): bool {
        $errors = [];

        // Check PHP version
        if (version_compare(PHP_VERSION, $this->min_php, '<')) {
            $errors[] = sprintf(
                /* translators: 1: Current PHP version, 2: Required PHP version */
                __('Rentals & Bookings — Solo & Marketplace requires PHP %2$s or higher. You are running PHP %1$s.', 'wahra-rentals-bookings'),
                PHP_VERSION,
                $this->min_php
            );
        }

        // Check WordPress version
        if (version_compare(get_bloginfo('version'), $this->min_wp, '<')) {
            $errors[] = sprintf(
                /* translators: 1: Current WordPress version, 2: Required WordPress version */
                __('Rentals & Bookings — Solo & Marketplace requires WordPress %2$s or higher. You are running WordPress %1$s.', 'wahra-rentals-bookings'),
                get_bloginfo('version'),
                $this->min_wp
            );
        }

        // Check WooCommerce
        if (!class_exists('WooCommerce')) {
            $errors[] = __('Rentals & Bookings — Solo & Marketplace requires WooCommerce to be installed and activated.', 'wahra-rentals-bookings');
        } elseif (defined('WC_VERSION') && version_compare(WC_VERSION, $this->min_wc, '<')) {
            $errors[] = sprintf(
                /* translators: 1: Current WooCommerce version, 2: Required WooCommerce version */
                __('Rentals & Bookings — Solo & Marketplace requires WooCommerce %2$s or higher. You are running WooCommerce %1$s.', 'wahra-rentals-bookings'),
                WC_VERSION,
                $this->min_wc
            );
        }

        // Dokan is optional — if present, multi-vendor mode is used.
        // If absent, the plugin runs in solo vendor mode (site owner = sole vendor).

        // Display errors if any
        if (!empty($errors)) {
            add_action('admin_notices', function() use ($errors) {
                foreach ($errors as $error) {
                    printf('<div class="notice notice-error"><p>%s</p></div>', esc_html($error));
                }
            });
            return false;
        }

        return true;
    }

    /**
     * Load plugin dependencies
     */
    private function load_dependencies(): void {
        // Core classes
        require_once WAHRB_PLUGIN_DIR . 'includes/class-wahrb-loader.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/class-wahrb-platform-categories.php';

        // Database
        require_once WAHRB_PLUGIN_DIR . 'includes/Database/class-wahrb-database.php';

        // Bookings
        require_once WAHRB_PLUGIN_DIR . 'includes/Bookings/class-wahrb-booking.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Bookings/class-wahrb-availability.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Bookings/class-wahrb-daily-availability.php'; // NEW: Daily Index
        require_once WAHRB_PLUGIN_DIR . 'includes/Bookings/class-wahrb-hold.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Bookings/class-wahrb-booking-notes.php';

        // Pricing
        require_once WAHRB_PLUGIN_DIR . 'includes/Pricing/class-wahrb-pricing-engine.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Pricing/class-wahrb-price-rule.php';

        // Form Builder
        require_once WAHRB_PLUGIN_DIR . 'includes/FormBuilder/class-wahrb-form-builder.php';

        // Coupons
        require_once WAHRB_PLUGIN_DIR . 'includes/Coupons/class-wahrb-coupon-manager.php';

        // Payment
        require_once WAHRB_PLUGIN_DIR . 'includes/Payment/class-wahrb-payment-manager.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Payment/class-wahrb-deposit-handler.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Payment/class-wahrb-balance-handler.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Payment/class-wahrb-security-deposit.php';

        // API
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-rest-controller.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-availability-controller.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-bookings-controller.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-wizard-controller.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-payment-controller.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-form-builder-controller.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Api/class-wahrb-coupon-controller.php';

        // Emails
        require_once WAHRB_PLUGIN_DIR . 'includes/Emails/class-wahrb-emailer.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Emails/class-wahrb-cron.php';

        // Dokan integration (loaded only if Dokan is active)
        if (wahrb_is_dokan_active()) {
            require_once WAHRB_PLUGIN_DIR . 'includes/Dokan/class-wahrb-dokan-integration.php';
        }

        // Solo vendor integration (loaded only if Dokan is NOT active)
        if (!wahrb_is_dokan_active()) {
            require_once WAHRB_PLUGIN_DIR . 'includes/Solo/class-wahrb-solo-integration.php';
        }

        // Color customization
        require_once WAHRB_PLUGIN_DIR . 'includes/class-wahrb-color-settings.php';

        // Vendor permissions
        require_once WAHRB_PLUGIN_DIR . 'includes/class-wahrb-vendor-permissions.php';

        // Admin UX (self-registering, since 2.0.6)
        require_once WAHRB_PLUGIN_DIR . 'includes/Admin/class-wahrb-support-widget.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Admin/class-wahrb-review-prompt.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Admin/class-wahrb-compatibility.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Admin/class-wahrb-freshness-reminder.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Admin/class-wahrb-setup-wizard.php';
        require_once WAHRB_PLUGIN_DIR . 'includes/Admin/class-wahrb-csv-exporter.php';
    }

    /**
     * Initialize plugin components
     */
    private function init_components(): void {
        // Initialize loader
        $loader = new WAHRB_Loader();

        // Auto-upgrade database tables when plugin version changes
        // This handles cases where plugin files are updated without deactivation/reactivation
        add_action('admin_init', [$this, 'maybe_upgrade_database']);

        // Initialize vendor integration (Dokan multi-vendor OR solo mode)
        if (wahrb_is_dokan_active()) {
            new WAHRB_Dokan_Integration();
        } else {
            new WAHRB_Solo_Integration();
        }

        // Initialize Emails and Cron
        WAHRB_Emailer::instance();
        WAHRB_Cron::instance();

        // Initialize CSV Exporter (hooks into AJAX)
        WAHRB_CSV_Exporter::instance();

        // Initialize REST API
        add_action('rest_api_init', [$this, 'register_rest_routes']);

        // Enqueue scripts
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);

        // HPOS compatibility
        add_action('before_woocommerce_init', [$this, 'declare_hpos_compatibility']);

        // Schedule cron events
        $this->schedule_events();

        // Admin UX components (self-registering, since 2.0.6)
        if ( is_admin() ) {
            new WAHRB_Support_Widget();
            new WAHRB_Review_Prompt();
            new WAHRB_Compatibility();
            new WAHRB_Freshness_Reminder();
            new WAHRB_Setup_Wizard();
        }
    }

    /**
     * Check and upgrade database tables if needed
     *
     * Runs on admin_init to handle cases where plugin files are updated
     * (e.g., via FTP) without deactivating/reactivating the plugin.
     * Uses version comparison to avoid unnecessary dbDelta calls.
     */
    public function maybe_upgrade_database(): void {
        $db = WAHRB_Database::instance();
        $db->maybe_upgrade();
    }

    /**
     * Register REST API routes
     */
    public function register_rest_routes(): void {
        $availability_controller = new WAHRB_Availability_Controller();
        $availability_controller->register_routes();

        $bookings_controller = new WAHRB_Bookings_Controller();
        $bookings_controller->register_routes();

        $wizard_controller = new WAHRB_Wizard_Controller();
        $wizard_controller->register_routes();

        $payment_controller = new WAHRB_Payment_Controller();
        $payment_controller->register_routes();

        $form_builder_controller = new WAHRB_Form_Builder_Controller();
        $form_builder_controller->register_routes();

        $coupon_controller = new WAHRB_Coupon_Controller();
        $coupon_controller->register_routes();
    }

    /**
     * Enqueue frontend assets
     */
    public function enqueue_frontend_assets(): void {
        // Only load on relevant pages
        if (!$this->should_load_assets()) {
            return;
        }

        // React wizard app (built by Vite)
        $wizard_asset_file = WAHRB_PLUGIN_DIR . 'assets/js/wizard.asset.php';
        if (file_exists($wizard_asset_file)) {
            $wizard_asset = require $wizard_asset_file;
            wp_enqueue_script(
                'wahrb-wizard-app',
                WAHRB_PLUGIN_URL . 'assets/js/wizard.js',
                $wizard_asset['dependencies'] ?? [],
                $wizard_asset['version'] ?? WAHRB_VERSION,
                true
            );

            wp_enqueue_style(
                'wahrb-wizard-styles',
                WAHRB_PLUGIN_URL . 'assets/css/wizard.css',
                [],
                WAHRB_VERSION
            );
        }

        // Frontend booking calendar
        wp_enqueue_style(
            'wahrb-frontend-styles',
            WAHRB_PLUGIN_URL . 'assets/css/wahrb-frontend.css',
            [],
            WAHRB_VERSION
        );
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets(): void {
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }

        // Admin settings page
        if (strpos($screen->id, 'wahrb-settings') !== false) {
            wp_enqueue_style(
                'wahrb-admin-styles',
                WAHRB_PLUGIN_URL . 'assets/css/wahrb-admin.css',
                [],
                WAHRB_VERSION
            );

            // Form builder assets (SortableJS + builder CSS/JS)
            wp_enqueue_script(
                'sortablejs',
                WAHRB_PLUGIN_URL . 'assets/vendor/sortablejs/Sortable.min.js',
                [],
                '1.15.6',
                true
            );

            wp_enqueue_style(
                'wahrb-form-builder-css',
                WAHRB_PLUGIN_URL . 'assets/css/wahrb-form-builder.css',
                [],
                WAHRB_VERSION
            );

            wp_enqueue_script(
                'wahrb-form-builder-js',
                WAHRB_PLUGIN_URL . 'assets/js/wahrb-form-builder.js',
                ['sortablejs'],
                WAHRB_VERSION,
                true
            );

            // Coupon admin assets
            wp_enqueue_style(
                'wahrb-coupon-admin-css',
                WAHRB_PLUGIN_URL . 'assets/css/wahrb-coupon-admin.css',
                [],
                WAHRB_VERSION
            );

            wp_enqueue_script(
                'wahrb-coupon-admin-js',
                WAHRB_PLUGIN_URL . 'assets/js/wahrb-coupon-admin.js',
                [],
                WAHRB_VERSION,
                true
            );
        }
    }

    /**
     * Check if assets should be loaded
     *
     * @return bool
     */
    private function should_load_assets(): bool {
        // Load on Dokan dashboard pages (multi-vendor mode)
        if (function_exists('dokan_is_seller_dashboard') && dokan_is_seller_dashboard()) {
            return true;
        }

        // Solo mode: load on our admin pages
        if (!wahrb_is_dokan_active() && is_admin()) {
            $screen = get_current_screen();
            if ($screen && strpos($screen->id, 'wahrb-') !== false) {
                return true;
            }
        }

        // Load on product pages with rental enabled
        if (is_product()) {
            $product_id = get_queried_object_id();
            if ($product_id && get_post_meta($product_id, '_wahrb_rental_enabled', true) === 'yes') {
                return true;
            }
        }

        // Load on cart/checkout
        if (is_cart() || is_checkout()) {
            return true;
        }

        return false;
    }

    /**
     * Declare HPOS compatibility
     */
    public function declare_hpos_compatibility(): void {
        if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
                'custom_order_tables',
                WAHRB_PLUGIN_FILE,
                true
            );
        }
    }

    /**
     * Schedule cron events
     */
    private function schedule_events(): void {
        // Register 5-minute interval BEFORE scheduling events that use it
        add_filter('cron_schedules', function($schedules) {
            $schedules['five_minutes'] = [
                'interval' => 300,
                'display' => __('Every 5 Minutes', 'wahra-rentals-bookings'),
            ];
            return $schedules;
        });

        // Cleanup expired holds every 5 minutes
        if (!wp_next_scheduled('wahrb_cleanup_expired_holds')) {
            wp_schedule_event(time(), 'five_minutes', 'wahrb_cleanup_expired_holds');
        }

        // Process pending balance orders daily
        if (!wp_next_scheduled('wahrb_process_balance_orders')) {
            wp_schedule_event(time(), 'daily', 'wahrb_process_balance_orders');
        }

        // Hook cron actions
        add_action('wahrb_cleanup_expired_holds', [WAHRB_Hold::class, 'cleanup_expired']);
        add_action('wahrb_process_balance_orders', [WAHRB_Balance_Handler::class, 'process_pending_orders']);
    }

    /**
     * Get database instance
     *
     * @return WAHRB_Database
     */
    public function database(): WAHRB_Database {
        return WAHRB_Database::instance();
    }

    /**
     * Get pricing engine instance
     *
     * @return WAHRB_Pricing_Engine
     */
    public function pricing(): WAHRB_Pricing_Engine {
        return WAHRB_Pricing_Engine::instance();
    }

    /**
     * Get payment manager instance
     *
     * @return WAHRB_Payment_Manager
     */
    public function payments(): WAHRB_Payment_Manager {
        return WAHRB_Payment_Manager::instance();
    }

    /**
     * Prevent cloning
     */
    private function __clone() {}

    /**
     * Prevent unserialization
     */
    public function __wakeup() {
        throw new \Exception('Cannot unserialize singleton');
    }
}

/**
 * Check if Dokan is active
 *
 * Used to determine whether to run in multi-vendor (Dokan) mode
 * or solo vendor (WooCommerce-only) mode.
 *
 * @return bool True if Dokan is active
 */
function wahrb_is_dokan_active(): bool {
    return class_exists('WeDevs_Dokan') || function_exists('dokan');
}

/**
 * Get the operating mode of the plugin
 *
 * @return string 'dokan' or 'solo'
 */
function wahrb_get_mode(): string {
    return wahrb_is_dokan_active() ? 'dokan' : 'solo';
}

/**
 * Get a vendor-facing dashboard URL for the current mode.
 *
 * In Dokan mode this returns frontend Dokan dashboard URLs.
 * In solo mode this returns WP admin rentals URLs.
 *
 * @param string $page Page slug (e.g., 'bookings', 'wizard', 'calendar', 'settings').
 * @param array<string,mixed> $args Optional query args.
 * @return string URL
 */
function wahrb_get_vendor_dashboard_url(string $page = 'bookings', array $args = []): string {
    if (wahrb_is_dokan_active() && function_exists('dokan_get_navigation_url')) {
        $dokan_slugs = [
            'bookings' => 'wahra-rentals-bookings',
            'booking-detail' => 'wahrb-booking-detail',
            'wizard' => 'booking-wizard',
            'calendar' => 'wahrb-calendar',
            'analytics' => 'wahrb-analytics',
            'settings' => 'wahrb-settings',
        ];
        $slug = $dokan_slugs[$page] ?? 'wahra-rentals-bookings';
        $url = dokan_get_navigation_url($slug);
        return !empty($args) ? add_query_arg($args, $url) : $url;
    }

    // Solo mode: WP Admin pages
    $admin_slugs = [
        'bookings' => 'wahrb-bookings',
        'booking-detail' => 'wahrb-booking-detail',
        'wizard' => 'wahrb-wizard',
        'calendar' => 'wahrb-calendar',
        'analytics' => 'wahrb-analytics',
        'settings' => 'wahrb-vendor-settings',
    ];
    $slug = $admin_slugs[$page] ?? 'wahrb-bookings';
    $url = admin_url('admin.php?page=' . $slug);
    return !empty($args) ? add_query_arg($args, $url) : $url;
}

/**
 * Get an admin/platform-facing dashboard URL.
 *
 * In Dokan mode this points to plugin admin pages (bookings-wahra*).
 * In solo mode this points to solo admin pages (wahrb-*).
 *
 * @param string $page Page slug (e.g., 'bookings', 'settings', 'analytics', 'wizard').
 * @param array<string,mixed> $args Optional query args.
 * @return string URL
 */
function wahrb_get_admin_dashboard_url(string $page = 'bookings', array $args = []): string {
    if (wahrb_is_dokan_active()) {
        $admin_slugs = [
            'bookings' => 'bookings-wahra',
            'booking-detail' => 'bookings-wahra-detail',
            'settings' => 'bookings-wahra-settings',
            'analytics' => 'bookings-wahra-analytics',
            'wizard' => 'bookings-wahra',
            'calendar' => 'bookings-wahra',
        ];
        $slug = $admin_slugs[$page] ?? 'bookings-wahra';
    } else {
        $admin_slugs = [
            'bookings' => 'wahrb-bookings',
            'booking-detail' => 'wahrb-booking-detail',
            'wizard' => 'wahrb-wizard',
            'calendar' => 'wahrb-calendar',
            'analytics' => 'wahrb-analytics',
            'settings' => 'wahrb-settings',
            'dashboard' => 'wahrb-dashboard',
        ];
        $slug = $admin_slugs[$page] ?? 'wahrb-dashboard';
    }

    $url = admin_url('admin.php?page=' . $slug);
    return !empty($args) ? add_query_arg($args, $url) : $url;
}

/**
 * Get the dashboard URL (legacy helper).
 *
 * @param string $page Page slug.
 * @param array<string,mixed> $args Optional query args.
 * @return string URL
 */
function wahrb_get_dashboard_url(string $page = 'bookings', array $args = []): string {
    return wahrb_get_vendor_dashboard_url($page, $args);
}

/**
 * Get plugin instance
 *
 * @return Wahra_Rentals_Bookings
 */
function wahrb_instance(): Wahra_Rentals_Bookings {
    return Wahra_Rentals_Bookings::instance();
}

// Initialize plugin
wahrb_instance();
