<?php
namespace orderflow;

/**
 * License Admin Class
 *
 * This class handles the license activation page and admin notices.
 */
class Core {
    use \orderflow\Traits\Core;

    /**
     * Initialize the class
     */
    public static function init() {
        // Handle form submissions early
        add_action('admin_init', [__CLASS__, 'handle_license_form_submission']);
        // Load custom styles for admin page
        add_action('admin_enqueue_scripts', [__CLASS__, 'load_admin_styles']);
        
        // Check and sync license on user requests (when website is used)
        // This runs on every page load, but only syncs if 1 minute has passed
        add_action('init', [__CLASS__, 'check_and_sync_license'], 20);
    }

    /**
     * Check if license sync is needed and perform sync if required
     * Only syncs if 1 minute has passed since last check
     */
    public static function check_and_sync_license() {
        // Check if we have a license to sync
        $data = self::get_license_data();
        if ($data['status'] !== 'active' || empty($data['key'])) {
            return;
        }

        // Check last sync time using transient
        $last_sync = get_transient('orderflow_license_last_sync');
        
        // If last sync was more than 1 minute ago (60 seconds), sync now
        if ($last_sync === false || (time() - $last_sync) >= 60) {
            // Perform sync in background (non-blocking)
            self::sync_license_data_background();
            
            // Update last sync time (store for 2 minutes to avoid duplicate checks)
            set_transient('orderflow_license_last_sync', time(), 120);
        }
    }

    /**
     * Sync license data in background (non-blocking)
     */
    private static function sync_license_data_background() {
        // Process sync (this will make the API call and update data)
        self::sync_license_data();
    }

    /**
     * Handle license form submission
     */
    public static function handle_license_form_submission() {
        $page_slug = 'orderflow-license-settings'; // The slug for your license page

        // Check if we are on the license page
        if (!isset($_GET['page']) || $_GET['page'] !== $page_slug) {
            return;
        }

        $redirect_url = admin_url('admin.php?page=' . $page_slug);

        // Handle activation
        if (isset($_POST['activate_license']) && check_admin_referer('license_activation_nonce')) {
            $license_key = sanitize_text_field($_POST['license_key']);
            $result = self::activate_license($license_key);

            if ($result['success']) {
                $redirect_url = add_query_arg('license_message', 'activated', $redirect_url);
            } else {
                // Pass the error message (e.g., 'expired', 'invalid_key')
                $error_code = sanitize_key($result['message']);
                $redirect_url = add_query_arg('license_message', $error_code, $redirect_url);
            }
            wp_redirect($redirect_url);
            exit;
        }

        // Handle deactivation
        if (isset($_POST['deactivate_license']) && check_admin_referer('license_deactivation_nonce')) {
            $result = self::deactivate_license();
            if ($result['success']) {
                $redirect_url = add_query_arg('license_message', 'deactivated', $redirect_url);
            } else {
                $redirect_url = add_query_arg('license_message', 'deactivation_failed', $redirect_url);
            }
            wp_redirect($redirect_url);
            exit;
        }
    }

    /**
     * Render license activation page
     */
    public static function render_license_page() {
        // Get license info
        $license_info = self::get_license_info();
        $remaining_days = self::get_remaining_days();
        $subscription_package = self::get_subscription_package(); // Get subscription package
        $is_active = self::is_license_active(); // Centralized check

        echo "<div class='order-flow-main-box'>";
        require_once __DIR__ . "/admin/promo.php";


        // Display notices based on URL parameter
        if (isset($_GET['license_message'])) {
            $message = sanitize_text_field($_GET['license_message']);

            // Handle specific messages and use CUSTOM CSS classes
            switch ($message) {
                case 'activated':
                    echo '<div class="orderflow-admin-notice orderflow-success-notice is-dismissible"><p>✅ License activated successfully.</p></div>';
                    break;
                case 'deactivated':
                    echo '<div class="orderflow-admin-notice orderflow-success-notice is-dismissible"><p>✅ License deactivated successfully. You can now use this license on another site.</p></div>';
                    break;
                case 'deactivation_failed':
                    echo '<div class="orderflow-admin-notice orderflow-error-notice is-dismissible"><p>❌ License deactivation failed. Please try again.</p></div>';
                    break;
                case 'expired':
                    echo '<div class="orderflow-admin-notice orderflow-error-notice is-dismissible"><p>🛑 Your license key has expired. Please renew it.</p></div>';
                    break;
                case 'already_used':
                    echo '<div class="orderflow-admin-notice orderflow-error-notice is-dismissible"><p>⚠️ This license key is already in use on another site. Please deactivate it from that site first, then activate it here.</p></div>';
                    break;
                case 'invalid_key':
                    echo '<div class="orderflow-admin-notice orderflow-error-notice is-dismissible"><p>❌ Invalid license key. Please check and try again.</p></div>';
                    break;
                default:
                    // Generic error
                    echo '<div class="orderflow-admin-notice orderflow-error-notice is-dismissible"><p>License activation failed. Reason: ' . esc_html($message) . '</p></div>';
                    break;
            }
        }
        ?>


        <div class="wrap-area" style="margin-top: 20px;">
            <div class="license-card">
                <?php if ($is_active): ?>
                    <?php
                    // Define variables for cleaner HTML
                    $masked_key = substr($license_info['key'], 0, 8) . str_repeat('*', 10);
                    $domain = esc_html($license_info['domain']);
                    ?>
                    <div class="license-header">
                        <h1 class="license-settings-title">License Settings</h1>
                        <p class="license-settings-description">Manage your Order Flow license key to activate the plugin.</p>
                    </div>

                    <div class="license-details">
                        <div class="license-field">
                            <div class="field-label">License Key</div>
                            <div class="field-value"><?php echo esc_html($masked_key); ?></div>
                        </div>

                        <div class="license-field">
                            <div class="field-label">Domain</div>
                            <div class="field-value"><?php echo $domain; ?></div>
                        </div>

                        <div class="license-field">
                            <div class="field-label">Subscription Package</div>
                            <div class="field-value"><?php echo esc_html($subscription_package); ?></div>
                        </div>
                    </div>

                    <div class="license-actions">
                        <form method="post">
                            <?php wp_nonce_field('license_deactivation_nonce'); ?>
                            <input type="submit" name="deactivate_license" class="button button-deactivate" value="Deactivate License">
                        </form>
                    </div>

                    <div class="license-status-section">
                        <h3>License Status</h3>
                        <table class="license-status-table">
                            <tr>
                                <th>Status</th>
                                <td><span class="status-active">Active</span></td>
                            </tr>
                            <tr>
                                <th>Domain</th>
                                <td><?php echo $domain; ?></td>
                            </tr>
                            <tr>
                                <th>License Key</th>
                                <td><?php echo esc_html($masked_key); ?></td>
                            </tr>
                            <tr>
                                <th>Activated On</th>
                                <td><?php echo esc_html(wp_date('F j, Y g:i a', strtotime($license_info['activated_at']))); ?></td>
                            </tr>
                            <tr>
                                <th>Subscription Package</th>
                                <td><?php echo esc_html($subscription_package); ?></td>
                            </tr>
                            <tr>
                                <th>Remaining Days</th>
                                <td>
                                    <?php
                                    if ($remaining_days < 0) {
                                        echo 'Lifetime';
                                    } elseif ($remaining_days === 0) {
                                        // The license has expired (expiry date is today or past)
                                        echo 'Expired';
                                    } else {
                                        echo esc_html($remaining_days) . ' ' . ($remaining_days === 1 ? 'day' : 'days');
                                    }
                                    ?>
                                </td>
                            </tr>
                        </table>
                    </div>

                <?php else: // License is NOT active ?>
                    <div class="license-header">
                        <h2>Current License</h2>

                        <?php
                        // Check why it's not active
                        $is_expired = (!empty($license_info['key']) && self::is_license_expired());
                        ?>

                        <?php if ($is_expired): ?>
                            <div class="license-status inactive">
                                <span class="status-indicator" style="background-color: #d63638;"></span>
                                <span>Expired</span>
                            </div>
                        <?php else: ?>
                            <div class="license-status inactive">
                                <span class="status-indicator"></span>
                                <span>Inactive</span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="license-form-container">
                        <p>Enter your license key to activate the plugin:</p>
                        <form method="post">
                            <?php wp_nonce_field('license_activation_nonce'); ?>
                            <div class="form-field">
                                <input type="text" name="license_key" class="regular-text license-input"
                                       placeholder="Enter your license key" required
                                       value="<?php echo esc_attr($license_info['key']); ?>">
                            </div>
                            <div class="form-field">
                                <input type="submit" name="activate_license" class="button button-primary button-activate" value="Activate License">
                            </div>
                        </form>

                        <?php if ($is_expired): ?>
                            <div class="orderflow-admin-notice orderflow-error-notice" style="margin-top: 15px;">
                                <p><strong>Your license has expired.</strong></p>
                                <p><strong>Subscription Package:</strong> <?php echo esc_html($subscription_package); ?></p>
                                <p>
                                    <a href="https://xionweb.xyz/"
                                       class="button button-primary" target="_blank">Renew License</a>
                                </p>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        echo "<div>";
    }

    /**
     * Enqueue custom admin styles
     */
    public static function load_admin_styles() {
        // Check if we are on the license page before adding inline styles
        $screen = get_current_screen();
        $page_slug = 'orderflow-license-settings';
        if ($screen && $screen->id === 'toplevel_page_' . $page_slug) {
            $custom_styles = self::get_custom_notice_styles();
            // Using 'wp-admin' as the handle to ensure styles load after base admin styles
            wp_add_inline_style( 'wp-admin', $custom_styles );
        }
    }

    /**
     * Get CSS for custom admin notices
     *
     * @return string CSS code.
     */
    public static function get_custom_notice_styles() {
        return "
            .orderflow-admin-notice {
                margin: 10px 0 15px 0;
                padding: 12px;
                border-left: 5px solid;
                border-radius: 3px;
                font-size: 14px;
                box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
                position: relative; /* For dismiss button */
            }
            .orderflow-admin-notice p {
                margin: 0;
                padding: 0;
            }

            .orderflow-success-notice {
                background-color: #e5f2e8; /* Light Green */
                border-left-color: #4CAF50 !important; /* Green */
                color: #1e6c27; /* Darker Green Text */
            }

            .orderflow-error-notice {
                background-color: #f7e7e7; /* Light Red/Pink */
                border-left-color: #D32F2F !important; /* Red */
                color: #8c1e1e; /* Darker Red Text */
            }
            
            /* Style for dismiss button */
            .orderflow-admin-notice.is-dismissible {
                padding-right: 38px;
            }
            .orderflow-admin-notice .notice-dismiss {
                text-decoration: none;
                position: absolute;
                top: 50%;
                right: 1px;
                padding: 9px 12px;
                height: auto;
                border: none;
                background: none;
                transform: translateY(-50%);
                color: inherit;
            }
            .orderflow-admin-notice .notice-dismiss:before {
                content: '\\f153';
                font-family: 'dashicons';
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
                width: 16px;
                height: 16px;
                font-size: 16px;
                display: block;
            }
        ";
    }


    /**
     * Get subscription package name
     */
    public static function get_subscription_package() {
        $license_info = self::get_license_info();

        // Check if the 'type' key exists in the license information.
        if (empty($license_info['type'])) {
            return 'N/A';
        }

        $package_map = [
            'trial'      => '3 Days Trial',
            'monthly'    => '1 Month',
            '6_months'   => '6 Months',
            'yearly'     => '1 Year',
            'lifetime'   => 'Lifetime',
        ];

        // Return the human-readable name, or the original type if not found.
        return isset($package_map[$license_info['type']]) ? $package_map[$license_info['type']] : $license_info['type'];
    }

}