<?php
// filepath: c:\Users\KAMRAN\Desktop\AdaWizard-feat-ada-compliance-checker\ada_wizard_app\public\create_checkout_session.php
require_once __DIR__ . '/../includes/auth_check.php'; // Ensures user is logged in
require_once __DIR__ . '/../config/db_connect.php';   // Database connection for fetching website details
require_once __DIR__ . '/../config/db_config.php';    // Add this line to load the price ID constants

// Add debugging here
error_log("=== CREATE CHECKOUT SESSION DEBUG ===");
error_log("REQUEST_METHOD: " . $_SERVER["REQUEST_METHOD"]);
error_log("POST data: " . print_r($_POST, true));
error_log("Session user_id: " . ($_SESSION['user_id'] ?? 'NOT SET'));

// Debug the constants
error_log("STRIPE_MONTHLY_PLAN_PRICE_ID: " . (defined('STRIPE_MONTHLY_PLAN_PRICE_ID') ? STRIPE_MONTHLY_PLAN_PRICE_ID : 'NOT DEFINED'));
error_log("STRIPE_YEARLY_PLAN_PRICE_ID: " . (defined('STRIPE_YEARLY_PLAN_PRICE_ID') ? STRIPE_YEARLY_PLAN_PRICE_ID : 'NOT DEFINED'));
error_log("STRIPE_LIFETIME_PLAN_PRICE_ID: " . (defined('STRIPE_LIFETIME_PLAN_PRICE_ID') ? STRIPE_LIFETIME_PLAN_PRICE_ID : 'NOT DEFINED'));

require_once __DIR__ . '/../config/stripe_init.php';  // Stripe PHP library and API key initialization

$user_id = $_SESSION['user_id'];
$errors = [];

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    // Should not be accessed directly via GET
    error_log("Not POST method, redirecting to dashboard");
    header("Location: dashboard.php");
    exit();
}

$plan_type = $_POST['plan_type'] ?? null;
$website_id_from_form = filter_input(INPUT_POST, 'website_id', FILTER_VALIDATE_INT);

error_log("plan_type: " . ($plan_type ?? 'NULL'));
error_log("website_id_from_form: " . ($website_id_from_form ?? 'NULL'));

// Validate inputs
if (!$website_id_from_form) {
    $errors[] = "Invalid website identifier.";
    error_log("Error: Invalid website identifier");
}

// Updated validation - now supports all three plan types
if (!in_array($plan_type, ['lifetime', 'monthly', 'yearly'])) {
    $errors[] = "Invalid plan type selected.";
    error_log("Error: Invalid plan type selected - " . ($plan_type ?? 'NULL'));
}

// Check if there are validation errors first
if (!empty($errors)) {
    $_SESSION['checkout_errors'] = $errors;
    error_log("CreateCheckoutSession: Validation errors - redirecting to dashboard");
    header("Location: dashboard.php");
    exit();
}

// Set the stripe_price_id based on plan_type using your existing constants
$stripe_price_id = null;
$checkout_mode = 'payment'; // Default for one-time payments

if ($plan_type === 'lifetime') {
    $stripe_price_id = defined('STRIPE_LIFETIME_PLAN_PRICE_ID') ? STRIPE_LIFETIME_PLAN_PRICE_ID : null;
    $checkout_mode = 'payment'; // One-time payment
} elseif ($plan_type === 'monthly') {
    $stripe_price_id = defined('STRIPE_MONTHLY_PLAN_PRICE_ID') ? STRIPE_MONTHLY_PLAN_PRICE_ID : null;
    $checkout_mode = 'subscription'; // Recurring subscription
} elseif ($plan_type === 'yearly') {
    $stripe_price_id = defined('STRIPE_YEARLY_PLAN_PRICE_ID') ? STRIPE_YEARLY_PLAN_PRICE_ID : null;
    $checkout_mode = 'subscription'; // Recurring subscription
}

error_log("Selected stripe_price_id: " . ($stripe_price_id ?? 'NULL'));
error_log("Checkout mode: " . $checkout_mode);

// Validate the stripe_price_id
if (empty($stripe_price_id)) {
    $_SESSION['checkout_errors'] = ["Stripe Price ID for the selected plan is not configured. Please contact support."];
    error_log("CreateCheckoutSession: Stripe Price ID not configured for plan_type: {$plan_type}. Current value: " . ($stripe_price_id ?? 'NULL'));
    header("Location: dashboard.php");
    exit();
}

// Additional validation to ensure price ID looks correct
if (!preg_match('/^price_[a-zA-Z0-9]+$/', $stripe_price_id)) {
    $_SESSION['checkout_errors'] = ["Invalid Stripe Price ID format for the selected plan. Please contact support."];
    error_log("CreateCheckoutSession: Invalid Price ID format for plan_type: {$plan_type}. Current value: {$stripe_price_id}");
    header("Location: dashboard.php");
    exit();
}

// Fetch website details to verify ownership
$user_website = null;
$stmt = $mysqli->prepare("SELECT id, domain_name, widget_id FROM websites WHERE id = ? AND user_id = ?");
if ($stmt) {
    $stmt->bind_param("ii", $website_id_from_form, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $user_website = $result->fetch_assoc();
        error_log("Website found: " . $user_website['domain_name']);
    } else {
        $errors[] = "Website not found or access denied.";
        error_log("Error: Website not found for user_id: {$user_id}, website_id: {$website_id_from_form}");
    }
    $stmt->close();
} else {
    $errors[] = "Database error occurred.";
    error_log("Error: Database query failed - " . $mysqli->error);
}

// If there are errors, redirect back to dashboard
if (!empty($errors)) {
    $_SESSION['checkout_errors'] = $errors;
    header("Location: dashboard.php");
    exit();
}

// Define success and cancel URLs
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domain_name_server = $_SERVER['HTTP_HOST'];
$base_app_path = dirname($_SERVER['SCRIPT_NAME']);
if ($base_app_path === '/' || $base_app_path === '\\') {
    $base_app_path = '';
}

$success_url = $protocol . $domain_name_server . $base_app_path . '/payment_success.php?session_id={CHECKOUT_SESSION_ID}&plan=' . $plan_type;
$cancel_url = $protocol . $domain_name_server . $base_app_path . '/dashboard.php?cancelled=1';

error_log("Success URL: " . $success_url);
error_log("Cancel URL: " . $cancel_url);

// Check if checkout_session_id column exists before trying to update it
$columns_exist = true;
$check_columns_query = "SHOW COLUMNS FROM websites LIKE 'checkout_session_id'";
$result = $mysqli->query($check_columns_query);
if ($result->num_rows === 0) {
    error_log("checkout_session_id column does not exist, skipping database update");
    $columns_exist = false;
}

try {
    // Create Stripe checkout session with dynamic mode
    $checkout_session_params = [
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price' => $stripe_price_id,
            'quantity' => 1,
        ]],
        'mode' => $checkout_mode,
        'success_url' => $success_url,
        'cancel_url' => $cancel_url,
        'client_reference_id' => $user_website['id'],
        'customer_email' => $_SESSION['email'] ?? null,
        'metadata' => [
            'user_id' => (string)$user_id,
            'website_id' => (string)$user_website['id'],
            'plan_type' => $plan_type,
            'domain_name' => $user_website['domain_name']
        ],
    ];

    // Add subscription-specific settings for recurring plans
    if ($checkout_mode === 'subscription') {
        $checkout_session_params['billing_address_collection'] = 'auto';
        $checkout_session_params['allow_promotion_codes'] = true;
    }

    error_log("Creating Stripe session with params: " . json_encode($checkout_session_params, JSON_PRETTY_PRINT));

    $checkout_session = \Stripe\Checkout\Session::create($checkout_session_params);

    error_log("Stripe session created successfully. Session ID: " . $checkout_session->id);
    error_log("Stripe session URL: " . $checkout_session->url);

    // Store checkout session info for verification (only if columns exist)
    if ($columns_exist) {
        $stmt = $mysqli->prepare("UPDATE websites SET checkout_session_id = ?, pending_plan_type = ? WHERE id = ? AND user_id = ?");
        if ($stmt) {
            $stmt->bind_param("ssii", $checkout_session->id, $plan_type, $user_website['id'], $user_id);
            $execute_result = $stmt->execute();
            error_log("Database update result: " . ($execute_result ? 'SUCCESS' : 'FAILED'));
            if (!$execute_result) {
                error_log("Database update error: " . $stmt->error);
            }
            $stmt->close();
        }
    } else {
        error_log("Skipping database update - checkout_session_id column does not exist");
    }

    // Redirect to Stripe Checkout
    header("HTTP/1.1 303 See Other");
    header("Location: " . $checkout_session->url);
    exit();

} catch (\Stripe\Exception\ApiErrorException $e) {
    // Handle Stripe API errors
    $error_message = "Stripe API Error: " . $e->getMessage();
    $_SESSION['checkout_errors'] = [$error_message];
    error_log("CreateCheckoutSession: Stripe API Error for UserID {$user_id}, WebsiteID {$user_website['id']}: " . $e->getMessage());
    error_log("Stripe Error Code: " . ($e->getStripeCode() ?? 'NO_CODE'));
    error_log("Stripe Error Type: " . ($e->getError()->type ?? 'NO_TYPE'));
    header("Location: dashboard.php");
    exit();
} catch (Exception $e) {
    // Handle other errors
    $error_message = "Generic Error: " . $e->getMessage();
    $_SESSION['checkout_errors'] = [$error_message];
    error_log("CreateCheckoutSession: Generic Error for UserID {$user_id}, WebsiteID {$user_website['id']}: " . $e->getMessage());
    error_log("Error file: " . $e->getFile() . " on line " . $e->getLine());
    error_log("Error trace: " . $e->getTraceAsString());
    header("Location: dashboard.php");
    exit();
}

$mysqli->close();
?>
