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

defined('ABSPATH') || exit;

/**
 * Deactivator class
 */
class WAHRB_Deactivator {

    /**
     * Deactivate plugin
     */
    public static function deactivate(): void {
        // Clear scheduled events
        self::clear_scheduled_events();

        // Flush rewrite rules
        flush_rewrite_rules();

        // Log deactivation
        self::log_deactivation();

        // Note: We do NOT delete tables or options on deactivation
        // This preserves data in case of accidental deactivation
        // Full cleanup should be done via uninstall.php
    }

    /**
     * Clear scheduled cron events
     */
    private static function clear_scheduled_events(): void {
        $events = [
            'wahrb_cleanup_expired_holds',
            'wahrb_process_balance_orders',
            'wahrb_daily_cron_event',
        ];

        foreach ($events as $event) {
            $timestamp = wp_next_scheduled($event);
            if ($timestamp) {
                wp_unschedule_event($timestamp, $event);
            }
        }
    }

    /**
     * Log deactivation
     */
    private static function log_deactivation(): void {
        require_once WAHRB_PLUGIN_DIR . 'includes/Database/class-wahrb-database.php';

        try {
            $db = WAHRB_Database::instance();
            $db->log('plugin_deactivated', 'plugin', null, [
                'version' => WAHRB_VERSION,
                'reason' => 'manual_deactivation',
            ]);
        } catch (\Exception $e) {
            // Silently fail - table might not exist
            // Silently fail - table might not exist
            // error_log('WAHRB Deactivation log failed: ' . $e->getMessage());
        }
    }
}
