<?php
// Create a Stripe SetupIntent to verify a card without charging
header('Content-Type: application/json');
require __DIR__ . '/stripe_config.php';

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

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([
    'payment_method_types[]' => 'card',
    'usage' => 'off_session'
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/setup_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, 'setup_intent' => $resp]);
    exit;
} else {
    http_response_code($http_code ?: 500);
    $err = json_decode($result, true);
    $message = $err['error']['message'] ?? 'Error creating setup intent';
    echo json_encode(['success' => false, 'message' => $message, 'raw' => $err]);
    exit;
}

?>
