<?php
/**
 * Plugin activator
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

/**
 * Activator class
 */
class WAHRB_Activator {

    /**
     * Activate plugin
     */
    public static function activate(): void {
        // Start output buffering to prevent any unexpected output
        ob_start();
        
        try {
            // Check requirements
            self::check_requirements();

            // Create database tables
            self::create_tables();

            // Create virtual products for deposits
            self::create_virtual_products();

            // Set default options
            self::set_default_options();

            // Add capabilities
            self::add_capabilities();

            // Flush rewrite rules immediately and schedule for next load
            flush_rewrite_rules();
            update_option('wahrb_flush_rewrite_rules', true);

            // Log activation (only after tables are created)
            self::log_activation();
        } catch (Exception $e) {
            // Silently fail, log will be empty
        }
        
        // Clean output buffer
        ob_end_clean();
    }

    /**
     * Check plugin requirements
     */
    private static function check_requirements(): void {
        // PHP version
        if (version_compare(PHP_VERSION, '8.1', '<')) {
            deactivate_plugins(WAHRB_PLUGIN_BASENAME);
            wp_die(
                esc_html__('Rentals & Bookings for WooCommerce & Dokan requires PHP 8.1 or higher.', 'wahra-rentals-bookings'),
                esc_html__('Plugin Activation Error', 'wahra-rentals-bookings'),
                ['back_link' => true]
            );
        }

        // WordPress version
        if (version_compare(get_bloginfo('version'), '6.5', '<')) {
            deactivate_plugins(WAHRB_PLUGIN_BASENAME);
            wp_die(
                esc_html__('Rentals & Bookings for WooCommerce & Dokan requires WordPress 6.5 or higher.', 'wahra-rentals-bookings'),
                esc_html__('Plugin Activation Error', 'wahra-rentals-bookings'),
                ['back_link' => true]
            );
        }

        // WooCommerce
        if (!class_exists('WooCommerce')) {
            deactivate_plugins(WAHRB_PLUGIN_BASENAME);
            wp_die(
                esc_html__('Rentals & Bookings for WooCommerce & Dokan requires WooCommerce to be installed and activated.', 'wahra-rentals-bookings'),
                esc_html__('Plugin Activation Error', 'wahra-rentals-bookings'),
                ['back_link' => true]
            );
        }

        // Dokan is optional — plugin works in solo vendor mode without it.
        // If Dokan is active, multi-vendor mode is automatically enabled.
    }

    /**
     * Create database tables
     */
    private static function create_tables(): void {
        require_once WAHRB_PLUGIN_DIR . 'includes/Database/class-wahrb-database.php';
        $db = WAHRB_Database::instance();
        $db->create_tables();
    }

    /**
     * Create virtual products for deposits and balance
     */
    private static function create_virtual_products(): void {
        // Check if deposit product already exists
        $deposit_product_id = get_option('wahrb_deposit_product_id');
        if (!$deposit_product_id || !wc_get_product($deposit_product_id)) {
            $deposit_product = new WC_Product_Simple();
            $deposit_product->set_name(__('Booking deposit', 'wahra-rentals-bookings'));
            $deposit_product->set_slug('wahrb-deposit-product');
            $deposit_product->set_status('private');
            $deposit_product->set_catalog_visibility('hidden');
            $deposit_product->set_virtual(true);
            $deposit_product->set_sold_individually(true);
            $deposit_product->set_price(0);
            $deposit_product->set_regular_price(0);
            $deposit_product->save();

            update_option('wahrb_deposit_product_id', $deposit_product->get_id());
        }

        // Check if balance product already exists
        $balance_product_id = get_option('wahrb_balance_product_id');
        if (!$balance_product_id || !wc_get_product($balance_product_id)) {
            $balance_product = new WC_Product_Simple();
            $balance_product->set_name(__('Booking balance', 'wahra-rentals-bookings'));
            $balance_product->set_slug('wahrb-balance-product');
            $balance_product->set_status('private');
            $balance_product->set_catalog_visibility('hidden');
            $balance_product->set_virtual(true);
            $balance_product->set_sold_individually(true);
            $balance_product->set_price(0);
            $balance_product->set_regular_price(0);
            $balance_product->save();

            update_option('wahrb_balance_product_id', $balance_product->get_id());
        }

        // Check if security deposit product already exists
        $security_product_id = get_option('wahrb_security_product_id');
        if (!$security_product_id || !wc_get_product($security_product_id)) {
            $security_product = new WC_Product_Simple();
            $security_product->set_name(__('Security deposit', 'wahra-rentals-bookings'));
            $security_product->set_slug('wahrb-security-product');
            $security_product->set_status('private');
            $security_product->set_catalog_visibility('hidden');
            $security_product->set_virtual(true);
            $security_product->set_sold_individually(true);
            $security_product->set_price(0);
            $security_product->set_regular_price(0);
            $security_product->save();

            update_option('wahrb_security_product_id', $security_product->get_id());
        }
    }

    /**
     * Set default options
     */
    private static function set_default_options(): void {
        $defaults = [
            // General settings
            'wahrb_settings_general' => [
                'timezone' => wp_timezone_string(),
                'currency' => get_woocommerce_currency(),
                'date_format' => get_option('date_format'),
                'time_format' => get_option('time_format'),
            ],

            // Booking defaults
            'wahrb_settings_booking' => [
                'min_booking_window_hours' => 24,
                'max_booking_window_days' => 365,
                'buffer_before_hours' => 2,
                'buffer_after_hours' => 1,
                'default_min_stay_days' => 1,
                'default_max_stay_days' => 90,
                'hold_duration_minutes' => 30,
                // Slot mode settings
                'slot_buffer_minutes' => 15,
                'default_slot_duration_minutes' => 60,
                'default_min_duration_hours' => 1,
                'default_max_duration_hours' => 8,
                'default_business_hours_start' => '09:00',
                'default_business_hours_end' => '18:00',
                // Service mode settings
                'service_buffer_minutes' => 10,
                'default_service_duration_minutes' => 60,
                'default_capacity_per_slot' => 1,
            ],

            // Payment settings — per-category structure
            'wahrb_settings_payment' => [
                'categories' => [
                    'accommodation' => [
                        'deposit_enabled' => true,
                        'deposit_type' => 'percent',
                        'deposit_value' => 30,
                        'deposit_refundable' => true,
                        'security_deposit_enabled' => true,
                        'security_mode' => 'capture',
                        'balance_enabled' => true,
                        'balance_due_days_before' => 3,
                        'balance_allow_cod' => true,
                    ],
                    'vehicle' => [
                        'deposit_enabled' => true,
                        'deposit_type' => 'percent',
                        'deposit_value' => 30,
                        'deposit_refundable' => true,
                        'security_deposit_enabled' => true,
                        'security_mode' => 'capture',
                        'balance_enabled' => true,
                        'balance_due_days_before' => 3,
                        'balance_allow_cod' => true,
                    ],
                    'equipment' => [
                        'deposit_enabled' => true,
                        'deposit_type' => 'percent',
                        'deposit_value' => 30,
                        'deposit_refundable' => true,
                        'security_deposit_enabled' => true,
                        'security_mode' => 'capture',
                        'balance_enabled' => true,
                        'balance_due_days_before' => 3,
                        'balance_allow_cod' => true,
                    ],
                    'space' => [
                        'deposit_enabled' => true,
                        'deposit_type' => 'percent',
                        'deposit_value' => 30,
                        'deposit_refundable' => true,
                        'security_deposit_enabled' => true,
                        'security_mode' => 'capture',
                        'balance_enabled' => true,
                        'balance_due_days_before' => 3,
                        'balance_allow_cod' => true,
                    ],
                    'service' => [
                        'deposit_enabled' => false,
                        'deposit_type' => 'percent',
                        'deposit_value' => 30,
                        'deposit_refundable' => true,
                        'security_deposit_enabled' => false,
                        'security_mode' => 'capture',
                        'balance_enabled' => false,
                        'balance_due_days_before' => 3,
                        'balance_allow_cod' => true,
                    ],
                    'product' => [
                        'deposit_enabled' => false,
                        'deposit_type' => 'percent',
                        'deposit_value' => 30,
                        'deposit_refundable' => true,
                        'security_deposit_enabled' => false,
                        'security_mode' => 'capture',
                        'balance_enabled' => false,
                        'balance_due_days_before' => 3,
                        'balance_allow_cod' => true,
                    ],
                ],
            ],

            // Cancellation policies
            'wahrb_settings_cancellation' => [
                'flexible' => [
                    'name' => __('Flexible', 'wahra-rentals-bookings'),
                    'description' => __('Free cancellation up to 24h before start', 'wahra-rentals-bookings'),
                    'refund_percent' => 100,
                    'deadline_hours' => 24,
                ],
                'moderate' => [
                    'name' => __('Moderate', 'wahra-rentals-bookings'),
                    'description' => __('50% refund up to 72h before start', 'wahra-rentals-bookings'),
                    'refund_percent' => 50,
                    'deadline_hours' => 72,
                ],
                'strict' => [
                    'name' => __('Strict', 'wahra-rentals-bookings'),
                    'description' => __('Non-refundable after confirmation', 'wahra-rentals-bookings'),
                    'refund_percent' => 0,
                    'deadline_hours' => 0,
                ],
            ],

            // Email notifications
            'wahrb_settings_emails' => [
                'booking_confirmed_enabled' => true,
                'booking_cancelled_enabled' => true,
                'booking_started_enabled' => true,
                'booking_returned_enabled' => true,
                'booking_completed_enabled' => true,
                'balance_reminder_enabled' => true,
                'checkin_reminder_enabled' => true,
                'checkout_reminder_enabled' => true,
            ],
        ];

        foreach ($defaults as $option_name => $option_value) {
            if (!get_option($option_name)) {
                update_option($option_name, $option_value);
            }
        }

        // Set activation timestamp & setup wizard flag.
        // If wahrb_activated_at already exists, this is an upgrade — skip the wizard.
        // If it does NOT exist, this is a fresh install — show the wizard.
        if (!get_option('wahrb_activated_at')) {
            update_option('wahrb_activated_at', current_time('mysql'));
            // Fresh install: wizard should show (option absent = not completed).
        } else {
            // Existing install upgrading: auto-complete the wizard so it does not appear.
            if (false === get_option('wahrb_setup_wizard_completed')) {
                update_option('wahrb_setup_wizard_completed', true);
            }
        }
    }

    /**
     * Add custom capabilities to roles
     */
    private static function add_capabilities(): void {
        // Vendor capabilities (Dokan sellers + shop_manager for solo mode)
        $vendor_caps = [
            'wahrb_manage_bookings',
            'wahrb_view_bookings',
            'wahrb_create_offers',
            'wahrb_edit_offers',
            'wahrb_manage_pricing',
            'wahrb_manage_availability',
            'wahrb_process_payments',
            'wahrb_view_analytics',
        ];

        // Admin capabilities
        $admin_caps = array_merge($vendor_caps, [
            'wahrb_manage_settings',
            'wahrb_manage_all_bookings',
            'wahrb_manage_vendors',
            'wahrb_view_all_analytics',
            'wahrb_export_data',
        ]);

        // Add to Dokan seller role (if it exists)
        $seller = get_role('seller');
        if ($seller) {
            foreach ($vendor_caps as $cap) {
                $seller->add_cap($cap);
            }
        }

        // Add to administrator role
        $admin = get_role('administrator');
        if ($admin) {
            foreach ($admin_caps as $cap) {
                $admin->add_cap($cap);
            }
        }

        // Add to shop_manager role
        $shop_manager = get_role('shop_manager');
        if ($shop_manager) {
            foreach ($admin_caps as $cap) {
                $shop_manager->add_cap($cap);
            }
        }
    }

    /**
     * Log activation
     */
    private static function log_activation(): void {
        require_once WAHRB_PLUGIN_DIR . 'includes/Database/class-wahrb-database.php';
        $db = WAHRB_Database::instance();

        $db->log('plugin_activated', 'plugin', null, [
            'version' => WAHRB_VERSION,
            'php_version' => PHP_VERSION,
            'wp_version' => get_bloginfo('version'),
            'wc_version' => defined('WC_VERSION') ? WC_VERSION : 'unknown',
        ]);
    }
}
