<?php
session_start();

// CORS and headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php'; // contains $host, $dbname, $username, $password

function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}

if (empty($_POST['user_id']) || empty($_POST['auth']) || empty($_POST['amount']) || empty($_POST['package'])) {
    echo json_encode(['status' => false, 'message' => 'Missing required parameters']);
    exit;
}

$user_id = check_input($_POST['user_id']);
$auth    = check_input($_POST['auth']);
$amount  = check_input($_POST['amount']);
$package = check_input($_POST['package']);

// Verify user first
try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("SELECT id FROM users WHERE user_id = ? AND auth = ?");
    $stmt->execute([$user_id, $auth]);
    if (!$stmt->fetch()) {
        echo json_encode(['status' => false, 'message' => 'Invalid user']);
        exit;
    }
} catch (PDOException $e) {
    echo json_encode(['status' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    exit;
}

// Stripe integration
require_once './stripe-php_/init.php';
\Stripe\Stripe::setApiKey('sk_test_51Qn7DORo551DelC0H2WwHVXAPchbxx4v3cC6nuXO2139cmM0Up1y8nFxF2krYs5KBez9hZp10NdDtLJpDWPxQQih00ufuwCq6A');

$amountInCents = intval(floatval($amount) * 100);

try {
    $session = \Stripe\Checkout\Session::create([
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price_data' => [
                'currency' => 'usd',
                'product_data' => [
                    'name' => $package . ' Package',
                ],
                'unit_amount' => $amountInCents,
            ],
            'quantity' => 1,
        ]],
        'mode' => 'payment',
        'success_url' => 'https://diimdevs.com/mvca/application/pay_success.php?id={CHECKOUT_SESSION_ID}',
        'cancel_url' => 'https://readd/pay_failed',
    ]);

$narration = "30 days subscription for ".$package;
    // ✅ Insert into pending_package_subscriptions
    $insert = $conn->prepare("
        INSERT INTO pending_package_subscriptions (user_id, package, amount, narration, stripe_session_id, status, created_at)
        VALUES (?, ?, ?, ?, ?, 'pending', NOW())
    ");
    $insert->execute([$user_id, $package, $amount, $narration, $session->id]);

    echo json_encode([
        'status' => true,
        'session_id' => $session->id,
        'checkout_url' => $session->url,
    ]);

} catch (\Stripe\Exception\ApiErrorException $e) {
    echo json_encode([
        'status' => false,
        'message' => 'Stripe Error: ' . $e->getMessage(),
    ]);
} catch (Exception $e) {
    echo json_encode([
        'status' => false,
        'message' => 'Error: ' . $e->getMessage(),
    ]);
}

?>