<?php
session_start();

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';

header('Content-Type: application/json; charset=utf-8');

// ===============================
// 1) Settings desde BD
// ===============================
$settings = getSettings();
$stripeSecretKey = $settings['stripe_secret_key'] ?? '';

if (!$stripeSecretKey) {
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => 'Stripe Secret Key no configurada.']);
    exit;
}

$baseUrl = rtrim($settings['base_url'] ?? BASE_URL, '/') . '/';

// ===============================
// 2) Leer JSON del front
// ===============================
$inputRaw = file_get_contents('php://input');
$input    = json_decode($inputRaw, true);

if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['error' => true, 'message' => 'JSON inválido']);
    exit;
}

// Validar items
if (!isset($input['items']) || !is_array($input['items']) || empty($input['items'])) {
    http_response_code(400);
    echo json_encode(['error' => true, 'message' => 'Items inválidos']);
    exit;
}

// Validar correo
if (!isset($input['customer_email']) || !filter_var($input['customer_email'], FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => true, 'message' => 'Correo inválido']);
    exit;
}

$customerEmail = $input['customer_email'];

// ===============================
// 3) Validar purchase_token
// ===============================
if (!isset($input['purchase_token']) || !$input['purchase_token']) {
    http_response_code(400);
    echo json_encode(['error' => true, 'message' => 'Falta purchase_token']);
    exit;
}

$purchaseToken = $input['purchase_token'];

// ===============================
// 4) Construir line_items
// ===============================
$line_items = [];

foreach ($input['items'] as $i => $item) {
    if (!isset($item['name'], $item['amount']) || !is_numeric($item['amount'])) {
        http_response_code(400);
        echo json_encode(['error' => true, 'message' => "Item inválido en posición $i"]);
        exit;
    }

    $line_items["line_items[$i][price_data][currency]"]           = 'mxn';
    $line_items["line_items[$i][price_data][product_data][name]"] = $item['name'];
    $line_items["line_items[$i][price_data][unit_amount]"]        = intval($item['amount']) * 100;
    $line_items["line_items[$i][quantity]"]                       = 1;
}

// ===============================
// 5) URLs con pt (CLAVE)
// ===============================
$successUrl = $baseUrl . "success.php?pt=" . urlencode($purchaseToken) . "&session_id={CHECKOUT_SESSION_ID}";
$cancelUrl  = $baseUrl . "cancel.php";

// ===============================
// 6) Payload final a Stripe
// ===============================
$data = array_merge($line_items, [
    'payment_method_types[]' => 'card',
    'mode'                   => 'payment',
    'success_url'            => $successUrl,
    'cancel_url'             => $cancelUrl,
    'customer_email'         => $customerEmail
]);

// Guardar debug
file_put_contents(__DIR__ . '/debug_checkout.txt', json_encode([
    'enviado_a_stripe' => $data,
    'input'            => $input
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

// ===============================
// 7) Llamada a Stripe
// ===============================
$ch = curl_init('https://api.stripe.com/v1/checkout/sessions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, $stripeSecretKey . ':');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

$response    = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);

// ===============================
// 8) Resolver
// ===============================
if ($http_status !== 200 || !isset($result['url'])) {
    http_response_code(500);
    echo json_encode([
        'error'   => true,
        'message' => 'Stripe error',
        'stripe'  => $result
    ]);
    exit;
}

echo json_encode([
    'error' => false,
    'url'   => $result['url']
]);
exit;
