<?php
header('Content-Type: application/json');
require __DIR__ . '/stripe_config.php';

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
$id = $data['setup_intent_id'] ?? null;

if (!$id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing setup_intent_id']);
    exit;
}

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;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/setup_intents/' . urlencode($id));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $stripe_secret . ':');
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($code >= 200 && $code < 300) {
    $resp = json_decode($result, true);
    $status = $resp['status'] ?? null;
    if ($status === 'succeeded') {
        echo json_encode(['success' => true, 'status' => $status, 'setup_intent' => $resp]);
    } else {
        http_response_code(422);
        echo json_encode(['success' => false, 'status' => $status, 'message' => 'SetupIntent not succeeded', 'setup_intent' => $resp]);
    }
    exit;
} else {
    http_response_code($code ?: 500);
    $err = json_decode($result, true);
    $message = $err['error']['message'] ?? 'Error fetching SetupIntent';
    echo json_encode(['success' => false, 'message' => $message, 'raw' => $err]);
    exit;
}

?>
