<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: includes/class-license-handler.php
// Description: License activation/deactivation logic — NUCLEAR+++
// Last Edited: 2026-03-29
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class LicenseHandler
{
    private static ?self $instance = null;

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

    private function __construct()
    {
        add_action('admin_post_amai_activate_free_license', [$this, 'handle_activate']);
        add_action('wp_ajax_amai_activate_free_license',    [$this, 'handle_activate_ajax']);
        add_action('admin_post_amai_deactivate_license',    [$this, 'handle_deactivate']);
    }

    // --------------------------------------------------
    // Full page POST handler (fallback — kept for safety)
    // --------------------------------------------------
    public function handle_activate(): void
    {
        check_admin_referer('amai_activate_free_license', '_wpnonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized', 'Error', ['response' => 403]);
        }

        $first_name = sanitize_text_field((string) ($_POST['first_name'] ?? ''));
        $email      = sanitize_email((string) ($_POST['email'] ?? ''));
        $consent    = isset($_POST['consent']) ? 1 : 0;

        if (!$consent || $first_name === '' || $email === '' || !is_email($email)) {
            wp_redirect(add_query_arg('error', 'invalid_input', wp_get_referer()));
            exit;
        }

        $key = bin2hex(random_bytes(20));
        update_option('automarketer_ai_license_key', $key);
        update_option('automarketer_ai_license_status', 'active');

        wp_redirect(add_query_arg('success', 'activated', wp_get_referer()));
        exit;
    }

    // --------------------------------------------------
    // AJAX handler — used by the modal JS
    // --------------------------------------------------
    public function handle_activate_ajax(): void
    {
        if (!wp_verify_nonce(sanitize_text_field((string) ($_POST['_wpnonce'] ?? '')), 'amai_activate_free_license')) {
            wp_send_json_error(['message' => 'Security check failed.'], 403);
            return;
        }

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
            return;
        }

        $first_name = sanitize_text_field((string) ($_POST['first_name'] ?? ''));
        $email      = sanitize_email((string) ($_POST['email'] ?? ''));
        $consent    = isset($_POST['consent']) ? 1 : 0;

        if (!$consent || $first_name === '' || $email === '' || !is_email($email)) {
            wp_send_json_error(['message' => 'Please fill in all required fields and check the consent box.']);
            return;
        }

        $key = bin2hex(random_bytes(20));
        update_option('automarketer_ai_license_key', $key);
        update_option('automarketer_ai_license_status', 'active');

        wp_send_json_success(['message' => 'Activated']);
    }

    // --------------------------------------------------
    // Deactivate handler
    // --------------------------------------------------
    public function handle_deactivate(): void
    {
        check_admin_referer('amai_deactivate_license', '_wpnonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized', 'Error', ['response' => 403]);
        }

        update_option('automarketer_ai_license_key', '');
        update_option('automarketer_ai_license_status', 'deactivated');

        wp_redirect(add_query_arg('success', 'deactivated', wp_get_referer()));
        exit;
    }
}