<?php
if (!defined('ABSPATH')) {
    exit;
}

require_once KDSAMREF_PRO_PLUGIN_PATH . 'includes/class-kdsamref-pro-codeon-client.php';

class KDSAMREF_Pro_License_Manager {
    private static $instance = null;
    private $option_key = 'kdsamref_pro_license_key';
    private $status_key = 'kdsamref_pro_license_status';
    private $client;

    public static function instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct() {
        $this->client = new KDSAMREF_Pro_Codeon_Client('orderable-kds-pro', 'https://codeon.ch');
        add_action('admin_post_kdsamref_pro_save_license', array($this, 'handle_save_license'));
        add_action('admin_post_kdsamref_pro_deactivate_license', array($this, 'handle_deactivate_license'));
        // AJAX endpoints
        add_action('wp_ajax_kdsamref_pro_ajax_validate', array($this, 'ajax_validate_license'));
        add_action('wp_ajax_kdsamref_pro_ajax_deactivate', array($this, 'ajax_deactivate_license'));

        // Telemetry is opt-in: only if explicitly enabled in options
        add_action('wp_loaded', function () {
            if (is_admin() && current_user_can('manage_options')) {
                $opt_in = (bool) get_option('kdsamref_pro_telemetry_opt_in', false);
                if ($opt_in) {
                    $this->client->track_usage('admin_access');
                }
            }
        });
    }

    public static function is_license_valid() {
        $status = get_option('kdsamref_pro_license_status', array());
        if (empty($status) || !array_key_exists('valid', $status)) {
            $transient = get_transient('kdsamref_pro_license_status');
            if (is_array($transient)) {
                $status = $transient;
            }
        }

        // If status already inactive/invalid, do not attempt refresh
        if (empty($status['valid']) || (!empty($status['status']) && $status['status'] !== 'active')) {
            return false;
        }

        // Require signed token to consider license valid (JWT hardening)
        $signed_token = get_option('kdsamref_pro_signed_token', '');
        if (empty($signed_token) || !self::is_token_structure_valid($signed_token)) {
            // Try a one-time refresh to fetch a token from server (guarded by transient)
            self::maybe_refresh_token();
            $signed_token = get_option('kdsamref_pro_signed_token', '');
            if (empty($signed_token) || !self::is_token_structure_valid($signed_token)) {
                return false;
            }
        }

        // Validate token signature and claims; if invalid, try one refresh
        if (!self::verify_signed_token($signed_token)) {
            self::maybe_refresh_token();
            $signed_token = get_option('kdsamref_pro_signed_token', '');
            if (empty($signed_token) || !self::verify_signed_token($signed_token)) {
                return false;
            }
        }

        return !empty($status['valid']);
    }

    /**
     * Ensure token exists by calling validate endpoint once per short window
     */
    private static function maybe_refresh_token() {
        if (get_transient('kdsamref_pro_token_refresh_lock')) {
            return;
        }
        set_transient('kdsamref_pro_token_refresh_lock', 1, 5 * MINUTE_IN_SECONDS);
        $license_key = get_option('kdsamref_pro_license_key', '');
        if (empty($license_key)) {
            return;
        }
        // Run a lightweight validate call to fetch fresh token and persist status
        try {
            $client = new KDSAMREF_Pro_Codeon_Client('orderable-kds-pro', 'https://codeon.ch');
            $result = $client->validate_license($license_key);
            if (is_array($result)) {
                update_option('kdsamref_pro_license_status', $result);
            }
        } catch (Exception $e) {
            // ignore
        }
    }

    private static function is_token_structure_valid($token) {
        $parts = explode('.', (string) $token);
        return count($parts) === 3 && strlen($parts[1]) > 0;
    }

    private static function verify_signed_token($token) {
        // Minimal JWT validation without external libs: header.payload.signature (base64url)
        // For production, prefer sodium/openssl verification against a bundled public key.
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            return false;
        }
        list($h64, $p64, $s64) = $parts;
        $payload_json = base64_decode(strtr($p64, '-_', '+/'));
        if (!$payload_json) return false;
        $payload = json_decode($payload_json, true);
        if (!is_array($payload)) return false;

        // Check exp
        if (!empty($payload['exp']) && time() >= intval($payload['exp'])) {
            return false;
        }
        // Check domain claim matches site
        $domain = parse_url(home_url(), PHP_URL_HOST);
        $tokenDomain = $payload['domain'] ?? $payload['aud'] ?? '';
        if (!empty($tokenDomain) && $domain && stripos($domain, $tokenDomain) === false && stripos($tokenDomain, $domain) === false) {
            return false;
        }

        // Optional: verify product_id claim
        $pid = get_option('kdsamref_pro_product_id', '4862');
        if (!empty($payload['product_id']) && strval($payload['product_id']) !== strval($pid)) {
            return false;
        }

        // Signature verification placeholder:
        // If you have a public key, verify signature here. For now, accept token structure/claims.
        return true;
    }

    public function render_license_page() {
        if (!current_user_can('manage_kdsamref_orders') && !current_user_can('manage_woocommerce')) {
            wp_die(__('Permission denied', 'kds-report-for-orderable-pro'));
        }
        $license_key = get_option($this->option_key, '');
        $status = get_option($this->status_key, array('valid' => false));
        $details = $this->client->get_license_details($license_key);
        $server_url = get_option('kdsamref_pro_license_server_url', class_exists('Codeon_License_Manager_V2') ? home_url('/') : 'https://codeon.ch/');
        $product_id = get_option('kdsamref_pro_product_id', '4862');
        $is_active = !empty($status['valid']) && self::is_license_valid();
        $signed_token = get_option('kdsamref_pro_signed_token', '');
        $token_ok = !empty($signed_token) && self::verify_signed_token($signed_token);
        // Compute remaining days from expiry
        $remaining_text = '';
        $expiry_raw = isset($details['expiry_date']) ? $details['expiry_date'] : '';
        if (!empty($expiry_raw)) {
            $expiry_ts = strtotime($expiry_raw);
            if ($expiry_ts) {
                $now_ts = current_time('timestamp', true);
                $diff = $expiry_ts - $now_ts;
                if ($diff >= 0) {
                    $days = max(0, (int) ceil($diff / DAY_IN_SECONDS));
                    $remaining_text = sprintf(_n('%s day remaining', '%s days remaining', $days, 'kds-report-for-orderable-pro'), number_format_i18n($days));
                } else {
                    $days = (int) ceil(abs($diff) / DAY_IN_SECONDS);
                    $remaining_text = sprintf(_n('Expired %s day ago', 'Expired %s days ago', $days, 'kds-report-for-orderable-pro'), number_format_i18n($days));
                }
            }
        }
        ?>
        <div class="wrap kdsamref-pro-license">
            <div class="kdsamref-pro-hero">
                <div class="kdsamref-pro-hero-left">
                    <h1 class="kdsamref-pro-hero-title"><?php esc_html_e('KDS Pro', 'kds-report-for-orderable-pro'); ?></h1>
                    <p class="kdsamref-pro-hero-desc"><?php esc_html_e('Activate your license to unlock premium features and updates.', 'kds-report-for-orderable-pro'); ?></p>
                </div>
                <div class="kdsamref-pro-hero-right">
                    <span class="kdsamref-pro-status-chip <?php echo esc_attr($is_active ? 'ok' : 'off'); ?>">
                        <span class="chip-dot"></span>
                        <?php echo esc_html($is_active ? esc_html__('Active', 'kds-report-for-orderable-pro') : esc_html__('Inactive', 'kds-report-for-orderable-pro')); ?>
                    </span>
                </div>
            </div>
            <div class="kdsamref-pro-grid-2">
            <div class="kdsamref-pro-card">
                <h2><?php esc_html_e('License', 'kds-report-for-orderable-pro'); ?></h2>
                <div class="kdsamref-pro-form" id="kdsamref-pro-license-form">
                    <label class="kdsamref-pro-label"><?php esc_html_e('License Key', 'kds-report-for-orderable-pro'); ?></label>
                    <div class="kdsamref-pro-input-group">
                        <input type="text" id="kdsamref_pro_license_key" value="<?php echo esc_attr($is_active ? $license_key : ''); ?>" class="kdsamref-pro-input monospace" placeholder="XXXX-XXXX-XXXX-XXXX-XXXX-XXXX" />
                        <div class="kdsamref-pro-actions">
                            <button type="button" class="kdsamref-pro-button primary" id="kdsamref_pro_validate_btn"><?php esc_html_e('Save & Validate', 'kds-report-for-orderable-pro'); ?></button>
                            <?php if ($is_active) : ?>
                                <button type="button" class="kdsamref-pro-button danger" id="kdsamref_pro_deactivate_btn"><?php esc_html_e('Deactivate', 'kds-report-for-orderable-pro'); ?></button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="kdsamref-pro-card">
                <h2 class="card-title"><?php esc_html_e('Telemetry', 'kds-report-for-orderable-pro'); ?></h2>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="kdsamref-pro-form-inline">
                    <?php wp_nonce_field('kdsamref_pro_save_telemetry', 'kdsamref_pro_telemetry_nonce'); ?>
                    <input type="hidden" name="action" value="kdsamref_pro_save_telemetry" />
                    <label class="kdsamref-pro-switch">
                        <input type="checkbox" name="kdsamref_pro_telemetry_opt_in" value="1" <?php checked((bool) get_option('kdsamref_pro_telemetry_opt_in', true)); ?> />
                        <span class="slider"></span>
                    </label>
                    <span class="kdsamref-pro-switch-label"><?php esc_html_e('Share anonymous usage to improve stability and features', 'kds-report-for-orderable-pro'); ?></span>
                    <button type="submit" class="button kdsamref-pro-button"><?php esc_html_e('Save', 'kds-report-for-orderable-pro'); ?></button>
                </form>
            </div>

            <!-- Server settings hidden: embedded configuration -->

            <!-- Deactivate handled via AJAX -->

            <?php if ($is_active) : ?>
            <div class="kdsamref-pro-details-card">
                <div class="details-card-header"><?php esc_html_e('License Details', 'kds-report-for-orderable-pro'); ?></div>
                <div class="detail-row">
                    <div class="detail-label"><?php esc_html_e('Status', 'kds-report-for-orderable-pro'); ?></div>
                    <div class="detail-value"><?php echo esc_html($details['status'] ?? ($status['valid'] ? 'active' : 'inactive')); ?></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><?php esc_html_e('Expiry', 'kds-report-for-orderable-pro'); ?></div>
                    <div class="detail-value">
                        <?php echo esc_html($details['expiry_date'] ?? ''); ?>
                        <?php if (!empty($remaining_text)) : ?>
                            <span class="detail-muted">(<?php echo esc_html($remaining_text); ?>)</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><?php esc_html_e('Domain', 'kds-report-for-orderable-pro'); ?></div>
                    <div class="detail-value"><?php echo esc_html($details['domain'] ?? ''); ?></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><?php esc_html_e('Subscription', 'kds-report-for-orderable-pro'); ?></div>
                    <div class="detail-value"><?php echo esc_html($details['subscription_type'] ?? ''); ?></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><?php esc_html_e('Customer', 'kds-report-for-orderable-pro'); ?></div>
                    <div class="detail-value"><?php 
                        $cn = $details['customer_name'] ?? '';
                        $ce = $details['customer_email'] ?? '';
                        echo esc_html(trim($cn)) . ( $ce ? ' &lt;' . esc_html($ce) . '&gt;' : '' );
                    ?></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label"><?php esc_html_e('Usage', 'kds-report-for-orderable-pro'); ?></div>
                    <div class="detail-value"><?php echo esc_html(($details['usage_count'] ?? 0) . ' / ' . ($details['max_usage'] ?? '∞')); ?></div>
                </div>
            </div>
            <?php endif; ?>
            <!-- styles moved to assets/css/pro-license.css -->
        </div>
        <?php
    }

    public function handle_save_license() {
        if (!current_user_can('manage_kdsamref_orders') && !current_user_can('manage_woocommerce')) {
            wp_die(__('Permission denied', 'kds-report-for-orderable-pro'));
        }
        check_admin_referer('kdsamref_pro_save_license', 'kdsamref_pro_nonce');

        $license_key = isset($_POST['kdsamref_pro_license_key']) ? sanitize_text_field($_POST['kdsamref_pro_license_key']) : '';
        update_option($this->option_key, $license_key);

        if (!empty($license_key)) {
            $result = $this->client->activate_license($license_key);
            update_option($this->status_key, $result);
        } else {
            delete_option($this->status_key);
        }

        wp_safe_redirect(add_query_arg(array('page' => 'kdsamref-pro-license'), admin_url('admin.php')));
        exit;
    }

    public function ajax_validate_license() {
        check_ajax_referer('kdsamref_pro_license_nonce', 'nonce');
        if (!current_user_can('manage_kdsamref_orders') && !current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kds-report-for-orderable-pro')));
        }
        $license_key = isset($_POST['license_key']) ? sanitize_text_field($_POST['license_key']) : '';
        if (empty($license_key)) {
            wp_send_json_error(array('message' => __('License key is required', 'kds-report-for-orderable-pro')));
        }
        update_option($this->option_key, $license_key);
        // Always call validate first to fetch latest server-side status (suspended/expired)
        $validated = $this->client->validate_license($license_key);
        update_option($this->status_key, $validated);
        $active = !empty($validated['valid']) && self::is_license_valid();
        // If validate says invalid but user clicked Save & Validate to (re)activate, attempt activation afterwards
        if (!$active) {
            $activated = $this->client->activate_license($license_key);
            update_option($this->status_key, $activated);
            $active = !empty($activated['valid']) && self::is_license_valid();
            $final = $activated;
        } else {
            $final = $validated;
        }
        wp_send_json_success(array(
            'active' => $active,
            'status' => $final,
        ));
    }

    public function ajax_deactivate_license() {
        check_ajax_referer('kdsamref_pro_license_nonce', 'nonce');
        if (!current_user_can('manage_kdsamref_orders') && !current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kds-report-for-orderable-pro')));
        }
        $license_key = get_option($this->option_key, '');
        if (empty($license_key)) {
            wp_send_json_error(array('message' => __('No license key found', 'kds-report-for-orderable-pro')));
        }
        $result = $this->client->deactivate_license($license_key);
        update_option($this->status_key, $result);
        delete_option('kdsamref_pro_signed_token');
        wp_send_json_success(array('status' => $result));
    }

    public function handle_save_telemetry() {
        if (!current_user_can('manage_kdsamref_orders') && !current_user_can('manage_woocommerce')) {
            wp_die(__('Permission denied', 'kds-report-for-orderable-pro'));
        }
        check_admin_referer('kdsamref_pro_save_telemetry', 'kdsamref_pro_telemetry_nonce');
        $opt_in = isset($_POST['kdsamref_pro_telemetry_opt_in']) ? 1 : 0;
        update_option('kdsamref_pro_telemetry_opt_in', $opt_in ? 1 : 0);
        wp_safe_redirect(add_query_arg(array('page' => 'kdsamref-pro-license'), admin_url('admin.php')));
        exit;
    }

    public function handle_deactivate_license() {
        if (!current_user_can('manage_kdsamref_orders') && !current_user_can('manage_woocommerce')) {
            wp_die(__('Permission denied', 'kds-report-for-orderable-pro'));
        }
        check_admin_referer('kdsamref_pro_deactivate_license', 'kdsamref_pro_deactivate_nonce');

        $license_key = get_option($this->option_key, '');
        if (!empty($license_key)) {
            $result = $this->client->deactivate_license($license_key);
            update_option($this->status_key, $result);
        }

        wp_safe_redirect(add_query_arg(array('page' => 'kdsamref-pro-license'), admin_url('admin.php')));
        exit;
    }
}