<?php
// Create a Stripe PaymentIntent (simple implementation using curl)
// Requires auth-system/stripe_config.php to be configured with your secret key.
header('Content-Type: application/json');
require __DIR__ . '/stripe_config.php';

// Read JSON body
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON']);
    exit;
}

$amount = isset($data['amount']) ? (int)$data['amount'] : 0; // amount in smallest currency unit (e.g., cents)
$currency = isset($data['currency']) ? $data['currency'] : 'usd';

if ($amount <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid amount']);
    exit;
}

// Use Stripe Secret Key from config
if (!isset($stripe_secret) || empty($stripe_secret) || strpos($stripe_secret, 'YOUR_SECRET') === 0) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Stripe secret key not configured. Edit auth-system/stripe_config.php']);
    exit;
}

$post = http_build_query([
    'amount' => $amount,
    'currency' => $currency,
    'payment_method_types[]' => 'card'
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $stripe_secret . ':');

$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code >= 200 && $http_code < 300) {
    $resp = json_decode($result, true);
    echo json_encode(['success' => true, 'payment_intent' => $resp]);
    exit;
} else {
    http_response_code($http_code ?: 500);
    $err = json_decode($result, true);
    $message = $err['error']['message'] ?? 'Error creating payment intent';
    echo json_encode(['success' => false, 'message' => $message, 'raw' => $err]);
    exit;
}

?>
