<?php
/**
 * Tom's Java Jive - Create Stripe Payment Intent API
 * Uses cURL-based Stripe integration (no Composer required)
 */

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/stripe.php';

header('Content-Type: application/json');

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$orderId = $input['order_id'] ?? '';

if (empty($orderId)) {
    jsonResponse(['error' => 'Order ID required'], 400);
}

// Get order
$order = db()->fetch(
    "SELECT * FROM orders WHERE order_id = :id",
    ['id' => $orderId]
);

if (!$order) {
    jsonResponse(['error' => 'Order not found'], 404);
}

if ($order['payment_status'] === 'paid') {
    jsonResponse(['error' => 'Order already paid'], 400);
}

// Check if Stripe is configured
if (!isStripeConfigured()) {
    // Demo mode - simulate successful payment
    db()->update('orders',
        [
            'payment_status' => 'paid',
            'order_status' => 'confirmed',
            'stripe_payment_intent' => 'demo_' . bin2hex(random_bytes(8))
        ],
        'order_id = :id',
        ['id' => $orderId]
    );
    
    jsonResponse([
        'demo_mode' => true,
        'message' => 'Payment simulated (Stripe not configured)',
        'redirect' => '/order-confirmation.php?order=' . $orderId
    ]);
}

// Create Stripe Payment Intent using cURL-based API
try {
    $paymentIntent = stripe()->createPaymentIntent(
        $order['total'],
        'usd',
        [
            'metadata' => [
                'order_id' => $orderId,
                'order_number' => $order['order_number']
            ],
            'receipt_email' => $order['customer_email'],
            'description' => 'Order #' . $order['order_number']
        ]
    );
    
    // Store payment intent ID
    db()->update('orders',
        ['stripe_payment_intent' => $paymentIntent['id']],
        'order_id = :id',
        ['id' => $orderId]
    );
    
    jsonResponse([
        'client_secret' => $paymentIntent['client_secret']
    ]);
    
} catch (Exception $e) {
    error_log('Stripe error: ' . $e->getMessage());
    jsonResponse(['error' => 'Payment initialization failed: ' . $e->getMessage()], 500);
}
