<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'db.php';
require 'vendor/autoload.php';

while (ob_get_level()) {
    ob_end_clean();
}

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

function sendResponse($data) {
    echo json_encode($data);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendResponse(['success' => false, 'error' => 'Not authenticated']);
}

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

if (!$requestData || !isset($requestData['token'])) {
    sendResponse(['success' => false, 'error' => 'Invalid request']);
}

$token = $requestData['token'];
$makeDefault = !empty($requestData['makeDefault']);

try {
    \Stripe\Stripe::setApiKey('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');
    
    $db = new Database();
    $conn = $db->connect();
    
    $userQuery = $conn->prepare("SELECT id, email, username, stripe_customer_id FROM utilisateurs WHERE id = ?");
    $userQuery->execute([$_SESSION['user_id']]);
    $user = $userQuery->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        sendResponse(['success' => false, 'error' => 'User not found']);
    }
    
    $stripeCustomerId = $user['stripe_customer_id'];
    
    if (empty($stripeCustomerId)) {
        $customer = \Stripe\Customer::create([
            'email' => $user['email'],
            'name' => $user['username']
        ]);
        
        $stripeCustomerId = $customer->id;
        
        $updateCustomer = $conn->prepare("UPDATE utilisateurs SET stripe_customer_id = ? WHERE id = ?");
        $updateCustomer->execute([$stripeCustomerId, $user['id']]);
    }
    
    $cardSource = \Stripe\Customer::createSource($stripeCustomerId, ['source' => $token]);
    
    $countExisting = $conn->prepare("SELECT COUNT(*) FROM payment_methods WHERE user_id = ?");
    $countExisting->execute([$user['id']]);
    $existingCount = $countExisting->fetchColumn();
    
    $isDefault = ($makeDefault || $existingCount == 0);
    
    if ($isDefault) {
        \Stripe\Customer::update($stripeCustomerId, ['default_source' => $cardSource->id]);
        $resetDefault = $conn->prepare("UPDATE payment_methods SET is_default = 0 WHERE user_id = ?");
        $resetDefault->execute([$user['id']]);
    }
    
    $insertCard = $conn->prepare("
        INSERT INTO payment_methods 
        (user_id, stripe_customer_id, stripe_card_id, last4, brand, exp_month, exp_year, is_default, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $insertCard->execute([
        $user['id'],
        $stripeCustomerId,
        $cardSource->id,
        $cardSource->last4,
        $cardSource->brand,
        $cardSource->exp_month,
        $cardSource->exp_year,
        $isDefault ? 1 : 0
    ]);
    
    sendResponse(['success' => true]);
    
} catch (Exception $e) {
    sendResponse(['success' => false, 'error' => 'Payment failed']);
}
?>