<?php
// includes/create-checkout.php
if (!defined('ABSPATH')) exit;

/**
 * AJAX: Create a Stripe Checkout Session
 */
add_action('wp_ajax_vmo_create_checkout', function () {
    check_ajax_referer('vmo_builder_nonce', 'security');

    // Gate off payments until integration is finalized
    if (!defined('VMO_PAYMENTS_ENABLED') || !VMO_PAYMENTS_ENABLED) {
        wp_send_json_error(['message' => 'Payments are temporarily disabled. Please try again later.']);
    }

    $plan    = sanitize_text_field($_POST['plan'] ?? '');
    $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.']);
    }

    $email = $user->user_email;

    // New pack mapping: accept product or price ID from settings; compute tokens
    $pack_map = [
        'starter_pack'    => ['opt' => 'vmo_plan_starter_product',    'tokens' => 72326],
        'pro_pack'        => ['opt' => 'vmo_plan_pro_product',        'tokens' => 144909],
        'business_pack'   => ['opt' => 'vmo_plan_business_product',   'tokens' => 362659],
        'enterprise_pack' => ['opt' => 'vmo_plan_enterprise_product', 'tokens' => 500000, 'priority' => 1],
    ];

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

    $id_or_price = trim((string) get_option($pack_map[$plan]['opt']));
    if (!$id_or_price) {
        wp_send_json_error(['message' => 'Plan is not configured. Please add its Product or Price ID in Settings.']);
    }

    $secret = get_option('vmo_stripe_secret_key');
    if (!$secret) {
        wp_send_json_error(['message' => 'Stripe secret key not configured.']);
    }

    $stripe_init_file = VMO_AI_BUILDER_DIR . 'stripe-sdk/init.php';
    if (file_exists($stripe_init_file) && is_readable($stripe_init_file)) {
        try {
            require_once $stripe_init_file;
            \Stripe\Stripe::setApiKey($secret);
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('VMO: Failed to load Stripe SDK in create-checkout: ' . $e->getMessage());
            }
            wp_send_json_error(['message' => 'Payment system temporarily unavailable.']);
        }
    } else {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('VMO: Stripe SDK file missing in create-checkout: ' . $stripe_init_file);
        }
        wp_send_json_error(['message' => 'Payment system not configured.']);
    }

    try {
        // If value looks like a Price ID (price_), use directly. If Product (prod_), fetch default price.
        $price_id = null; $mode = 'payment';
        if (strpos($id_or_price, 'price_') === 0) {
            $price_id = $id_or_price;
            // Detect recurring vs one-time by inspecting Price
            $price = \Stripe\Price::retrieve($price_id);
            if (!empty($price->recurring)) { $mode = 'subscription'; }
        } elseif (strpos($id_or_price, 'prod_') === 0) {
            $product = \Stripe\Product::retrieve($id_or_price);
            if (!empty($product->default_price)) {
                $price_id = is_string($product->default_price) ? $product->default_price : ($product->default_price->id ?? null);
            }
            if (!$price_id) throw new Exception('Product has no default price.');
            $price = \Stripe\Price::retrieve($price_id);
            if (!empty($price->recurring)) { $mode = 'subscription'; }
        } else {
            throw new Exception('Unsupported ID format. Use prod_... or price_....');
        }

        $tokens_grant = function_exists('vmo_get_plan_checkout_token_grant')
            ? vmo_get_plan_checkout_token_grant($plan, (int) $pack_map[$plan]['tokens'])
            : (int) $pack_map[$plan]['tokens'];
        $priority_compute = class_exists('VMO_Plan_Policy')
            ? VMO_Plan_Policy::plan_has_priority_compute($plan)
            : !empty($pack_map[$plan]['priority']);
        $session = \Stripe\Checkout\Session::create([
            'payment_method_types' => ['card'],
            'mode' => $mode,
            'client_reference_id' => (string) $user_id,
            'customer_email' => $email,
            'line_items' => [[ 'price' => $price_id, 'quantity' => 1 ]],
            // Return to the main builder screen in wp-admin with payment status param
            'success_url' => admin_url('admin.php?page=vmo-ai-builder-main&vmo_payment=success'),
            'cancel_url' => admin_url('admin.php?page=vmo-ai-builder-main&vmo_payment=cancel'),
            'metadata' => array_filter([
                'plan' => $plan,
                'tokens' => $tokens_grant,
                'user_id' => $user_id,
                'priority_compute' => $priority_compute ? 1 : 0
            ])
        ]);

        wp_send_json_success(['url' => $session->url]);
    } catch (Exception $e) {
        wp_send_json_error(['message' => 'VMO Pay error: ' . esc_html($e->getMessage())]);
    }

    wp_die();
});
