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

class VMO_Subscription_Manager {
    
    public function __construct() {
        add_action('wp_ajax_vmo_subscription_checkout', [$this, 'handle_checkout']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_init', [$this, 'verify_stripe_session']);
    }

    public function verify_stripe_session() {
        if (!isset($_GET['session_id']) || !isset($_GET['payment']) || $_GET['payment'] !== 'success') {
            return;
        }

        $session_id = sanitize_text_field(wp_unslash($_GET['session_id']));
        // Prevent reprocessing
        if (get_transient('vmo_processed_' . $session_id)) {
            return;
        }

        // ── Client mode: verify via master proxy ──
        if (defined('VMO_CLIENT_MODE') && VMO_CLIENT_MODE === true) {
            $this->verify_stripe_session_via_master($session_id);
            return;
        }

        $secret_key = get_option('vmo_stripe_secret_key');
        if (!$secret_key) return;

        if (!class_exists('\Stripe\Stripe')) {
            if (file_exists(VMO_AI_BUILDER_DIR . 'vendor/autoload.php')) {
                require_once VMO_AI_BUILDER_DIR . 'vendor/autoload.php';
            } else {
                 return; // Cannot verify
            }
        }

        try {
            \Stripe\Stripe::setApiKey($secret_key);
            $session = \Stripe\Checkout\Session::retrieve($session_id);

            if ($session->payment_status === 'paid') {
                $user_id = get_current_user_id();
                if (!$user_id) return;

                // Determine plan from metadata if possible, or line items
                $plan = $session->metadata->plan ?? 'unknown';

                // Update User Status
                if ($plan !== 'unknown') {
                    
                    // Grant tokens based on plan (basic logic)
                    $tokens = 0;
                    $is_pack = in_array($plan, ['phone_m', 'phone_l', 'power_dialer', 'phone_xl'], true);

                    if ($is_pack) {
                        switch ($plan) {
                            case 'phone_m':
                                $tokens = 252000;
                                break;
                            case 'phone_l':
                                $tokens = 630000;
                                break;
                            case 'power_dialer':
                                $tokens = 1417500;
                                break;
                            case 'phone_xl':
                                $tokens = 2000000;
                                break;
                        }
                    } elseif (function_exists('vmo_get_plan_checkout_token_grant')) {
                        $tokens = vmo_get_plan_checkout_token_grant($plan, 0);
                    }

                    // For Packs: Do NOT change subscription status, just add tokens + expiry
                    if ($is_pack) {
                        $expiry = time() + YEAR_IN_SECONDS;
                        update_user_meta($user_id, 'vmo_phone_pack_expiry', $expiry);
                        // Also flag that they own this pack usage right
                        update_user_meta($user_id, 'vmo_has_phone_pack', 'true');
                    } else {
                        // For Main Plans: Update Status
                        update_user_meta($user_id, 'vmo_subscription_status', $plan);
                        if (function_exists('vmo_queue_plan_signup_bonus')) {
                            vmo_queue_plan_signup_bonus($user_id, $plan);
                        }

                        // Generate license key for master/client authentication
                        if ( function_exists( 'vmo_generate_license_key' ) ) {
                            $license_result = vmo_generate_license_key( $user_id, $plan );
                            if ( is_wp_error( $license_result ) ) {
                                error_log( 'VMO Subscription: License key generation failed — ' . $license_result->get_error_message() );
                            }
                        }
                    }

                    if ($tokens > 0) {
                        $current = (int) get_user_meta($user_id, 'vmo_token_balance', true);
                        update_user_meta($user_id, 'vmo_token_balance', $current + $tokens);
                    }
                }

                // Mark as processed (expiry 24h)
                set_transient('vmo_processed_' . $session_id, true, DAY_IN_SECONDS);
            }

        } catch (\Exception $e) {
            error_log('VMO Stripe Verification Error: ' . $e->getMessage());
        }
    }

    public function register_settings() {
        // Register Annual Price IDs
        register_setting('vmo_settings_group', 'vmo_price_tester_annual');
        register_setting('vmo_settings_group', 'vmo_price_starter_annual');
        register_setting('vmo_settings_group', 'vmo_price_pro_annual');
        register_setting('vmo_settings_group', 'vmo_price_elite_annual');
        register_setting('vmo_settings_group', 'vmo_price_enterprise_annual');
        
        // Register Phone Booster Packs
        // register_setting('vmo_settings_group', 'vmo_price_pack_phone_s'); // Removed
        register_setting('vmo_settings_group', 'vmo_price_pack_phone_m');
        register_setting('vmo_settings_group', 'vmo_price_pack_phone_l');
        register_setting('vmo_settings_group', 'vmo_price_pack_power_dialer');
        register_setting('vmo_settings_group', 'vmo_price_pack_phone_xl');
    }

    public function handle_checkout() {
        check_ajax_referer('vmo_builder_nonce', 'security');

        $plan = sanitize_text_field($_POST['plan'] ?? '');
        $billing_cycle = sanitize_text_field($_POST['billing_cycle'] ?? 'monthly');
        $user_id = get_current_user_id();
        $user = get_userdata($user_id);

        if (!$user || empty($user->user_email)) {
            wp_send_json_error(['message' => 'User email is missing.']);
        }

        // ── Client mode: create checkout via master proxy ──
        if (defined('VMO_CLIENT_MODE') && VMO_CLIENT_MODE === true) {
            $this->handle_checkout_via_master($plan, $billing_cycle, $user);
            return;
        }

        // Map plan names to product/price option keys
        $plan_map = [
            // NOTE: monthly Price IDs are stored in the historical `vmo_plan_*_product` options
            // (the settings UI labels them as “Monthly Price ID”).
            'tester' => ['monthly_price' => 'vmo_plan_tester_product', 'annual_price' => 'vmo_price_tester_annual'],
            'starter' => ['monthly_price' => 'vmo_plan_starter_product', 'annual_price' => 'vmo_price_starter_annual'],
            'pro' => ['monthly_price' => 'vmo_plan_pro_product', 'annual_price' => 'vmo_price_pro_annual'],
            'elite' => ['monthly_price' => 'vmo_plan_elite_product', 'annual_price' => 'vmo_price_elite_annual'],
            'enterprise' => ['monthly_price' => 'vmo_plan_enterprise_product', 'annual_price' => 'vmo_price_enterprise_annual'],
            
            // Phone Packs (One-time, use monthly_price slot as generic price holder)
            // 'phone_s' => ['monthly_price' => 'vmo_price_pack_phone_s', 'annual_price' => 'vmo_price_pack_phone_s'], // Removed
            'phone_m' => ['monthly_price' => 'vmo_price_pack_phone_m', 'annual_price' => 'vmo_price_pack_phone_m'],
            'phone_l' => ['monthly_price' => 'vmo_price_pack_phone_l', 'annual_price' => 'vmo_price_pack_phone_l'],
            'power_dialer' => ['monthly_price' => 'vmo_price_pack_power_dialer', 'annual_price' => 'vmo_price_pack_power_dialer'],
            'phone_xl'     => ['monthly_price' => 'vmo_price_pack_phone_xl', 'annual_price' => 'vmo_price_pack_phone_xl']
        ];

        if (!isset($plan_map[$plan])) {
            wp_send_json_error(['message' => 'Invalid plan selected.']);
        }

        // Resolve Stripe Price ID
        $price_id = '';
        if ($billing_cycle === 'annual') {
            $price_id = trim((string) get_option($plan_map[$plan]['annual_price']));
        } else {
            // Monthly uses the value stored in `vmo_plan_*_product` (historical name).
            $price_id = trim((string) get_option($plan_map[$plan]['monthly_price']));

            // Back-compat: if someone previously set a dedicated monthly key like `vmo_price_starter`.
            if (!$price_id) {
                $legacy_monthly_key = 'vmo_price_' . $plan;
                $legacy_monthly_val = trim((string) get_option($legacy_monthly_key));
                if (strpos($legacy_monthly_val, 'price_') === 0) {
                    $price_id = $legacy_monthly_val;
                }
            }
        }

        // Enforce Stripe Price IDs for checkout.
        if ($price_id && strpos($price_id, 'price_') !== 0) {
            $price_id = '';
        }

        if (!$price_id) {
            if ($billing_cycle === 'annual') {
                 wp_send_json_error(['message' => 'Annual pricing for this plan is not yet configured.']);
            }
            wp_send_json_error(['message' => 'Plan is not configured. Please contact support.']);
        }

        // Initialize Stripe
        $secret_key = get_option('vmo_stripe_secret_key');
        if (!$secret_key) {
            wp_send_json_error(['message' => 'Payment system not configured.']);
        }

        if (!class_exists('\Stripe\Stripe')) {
            require_once VMO_AI_BUILDER_DIR . 'vendor/autoload.php';
        }

        try {
            \Stripe\Stripe::setApiKey($secret_key);

            // Determine if this is a one-time pack or a subscription
            $is_pack = in_array($plan, ['phone_m', 'phone_l', 'power_dialer', 'phone_xl']);
            $mode = $is_pack ? 'payment' : 'subscription';

            $checkout_args = [
                'payment_method_types' => ['card'],
                'customer_email' => $user->user_email,
                'allow_promotion_codes' => true, // ✅ Allow promo codes at checkout
                'line_items' => [[
                    'price' => $price_id,
                    'quantity' => 1,
                ]],
                'mode' => $mode,
                'success_url' => admin_url('admin.php?page=vmo-ai-dashboard&payment=success&session_id={CHECKOUT_SESSION_ID}'),
                'cancel_url' => admin_url('admin.php?page=vmo-my-plan&payment=cancel'),
                'metadata' => [
                    'user_id' => $user_id,
                    'plan' => $plan,
                    'billing_cycle' => $billing_cycle
                ]
            ];

            $session = \Stripe\Checkout\Session::create($checkout_args);

            wp_send_json_success(['checkout_url' => $session->url]);
        } catch (Exception $e) {
            error_log('VMO Stripe Error: ' . $e->getMessage());
            wp_send_json_error(['message' => 'Payment initialization failed: ' . $e->getMessage()]);
        }
    }

    /**
     * Client-mode: Create Stripe Checkout Session via master proxy.
     * The master holds the real Stripe key and Price IDs.
     */
    private function handle_checkout_via_master($plan, $billing_cycle, $user) {
        $proxy_base = defined('VMO_MASTER_PROXY_URL')
            ? preg_replace('#/proxy$#', '', VMO_MASTER_PROXY_URL)
            : rtrim(get_option('vmo_master_proxy_url', 'https://getvmo.com/wp-json/vmo-builder/v1/proxy'), '/proxy');

        $response = wp_remote_post($proxy_base . '/stripe-checkout/create', array(
            'headers' => array(
                'Content-Type'       => 'application/json',
                'X-VMO-Installation' => get_option('vmo_installation_id', ''),
                'X-VMO-License'      => get_option('vmo_license_key', ''),
                'X-VMO-Plan'         => get_user_meta(get_current_user_id(), 'vmo_subscription_status', true),
            ),
            'body'    => wp_json_encode(array(
                'plan'           => $plan,
                'billing_cycle'  => $billing_cycle,
                'customer_email' => $user->user_email,
                'success_url'    => admin_url('admin.php?page=vmo-ai-dashboard&payment=success&session_id={CHECKOUT_SESSION_ID}'),
                'cancel_url'     => admin_url('admin.php?page=vmo-my-plan&payment=cancel'),
            )),
            'timeout' => 30,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => 'Could not connect to payment server. Please try again.'));
            return;
        }

        $status = wp_remote_retrieve_response_code($response);
        $result = json_decode(wp_remote_retrieve_body($response), true);

        if ($status >= 200 && $status < 300 && !empty($result['checkout_url'])) {
            wp_send_json_success(array('checkout_url' => $result['checkout_url']));
        } else {
            $msg = $result['message'] ?? $result['data']['message'] ?? 'Payment initialization failed.';
            wp_send_json_error(array('message' => $msg));
        }
    }

    /**
     * Client-mode: Verify Stripe Checkout Session via master proxy.
     * Master verifies, updates its records, and returns the result.
     * Client updates local user meta accordingly.
     */
    private function verify_stripe_session_via_master($session_id) {
        $proxy_base = defined('VMO_MASTER_PROXY_URL')
            ? preg_replace('#/proxy$#', '', VMO_MASTER_PROXY_URL)
            : rtrim(get_option('vmo_master_proxy_url', 'https://getvmo.com/wp-json/vmo-builder/v1/proxy'), '/proxy');

        $response = wp_remote_post($proxy_base . '/stripe-checkout/verify', array(
            'headers' => array(
                'Content-Type'       => 'application/json',
                'X-VMO-Installation' => get_option('vmo_installation_id', ''),
                'X-VMO-License'      => get_option('vmo_license_key', ''),
                'X-VMO-Plan'         => get_user_meta(get_current_user_id(), 'vmo_subscription_status', true),
            ),
            'body'    => wp_json_encode(array('session_id' => $session_id)),
            'timeout' => 30,
        ));

        if (is_wp_error($response)) {
            error_log('VMO Client Stripe Verify Error: ' . $response->get_error_message());
            return;
        }

        $result = json_decode(wp_remote_retrieve_body($response), true);

        if (empty($result['success'])) {
            return;
        }

        // Update local user records based on master's verification
        $user_id = get_current_user_id();
        if (!$user_id) return;

        if (!empty($result['plan']) && $result['plan'] !== 'unknown') {
            if (empty($result['is_pack'])) {
                update_user_meta($user_id, 'vmo_subscription_status', $result['plan']);
            } else {
                update_user_meta($user_id, 'vmo_phone_pack_expiry', time() + YEAR_IN_SECONDS);
                update_user_meta($user_id, 'vmo_has_phone_pack', 'true');
            }
        }

        if (!empty($result['token_balance'])) {
            update_user_meta($user_id, 'vmo_token_balance', (int) $result['token_balance']);
        }

        // Mark as processed locally too
        set_transient('vmo_processed_' . $session_id, true, DAY_IN_SECONDS);
    }
}
