<?php
session_start();
require_once 'db.php';
require 'vendor/autoload.php';

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

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

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

if (!isset($jsonData['card_id']) || !isset($jsonData['action'])) {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
    exit;
}

$cardId = $jsonData['card_id'];
$action = $jsonData['action'];

try {
    $db = new Database();
    $conn = $db->connect();
    
    $stmt = $conn->prepare("SELECT pm.*, u.stripe_customer_id 
                           FROM payment_methods pm
                           JOIN utilisateurs u ON pm.user_id = u.id
                           WHERE pm.id = ? AND pm.user_id = ?");
    $stmt->execute([$cardId, $_SESSION['user_id']]);
    $card = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$card) {
        echo json_encode(['success' => false, 'error' => 'Card not found']);
        exit;
    }
    
    \Stripe\Stripe::setApiKey('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');
    
    if ($action === 'set_default') {
        \Stripe\Customer::update(
            $card['stripe_customer_id'],
            ['default_source' => $card['stripe_card_id']]
        );
        
        $conn->beginTransaction();
        
        $conn->prepare("UPDATE payment_methods SET is_default = 0 WHERE user_id = ?")->execute([$_SESSION['user_id']]);
        $conn->prepare("UPDATE payment_methods SET is_default = 1 WHERE id = ?")->execute([$cardId]);
        
        $conn->commit();
        
        echo json_encode(['success' => true]);
    } 
    elseif ($action === 'delete') {
        $isDefault = $card['is_default'];
        
        \Stripe\Customer::deleteSource(
            $card['stripe_customer_id'],
            $card['stripe_card_id']
        );
        
        $conn->prepare("DELETE FROM payment_methods WHERE id = ?")->execute([$cardId]);
        
        if ($isDefault) {
            $stmt = $conn->prepare("SELECT id, stripe_card_id FROM payment_methods WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
            $stmt->execute([$_SESSION['user_id']]);
            $newDefaultCard = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($newDefaultCard) {
                \Stripe\Customer::update(
                    $card['stripe_customer_id'],
                    ['default_source' => $newDefaultCard['stripe_card_id']]
                );
                
                $conn->prepare("UPDATE payment_methods SET is_default = 1 WHERE id = ?")->execute([$newDefaultCard['id']]);
            }
        }
        
        echo json_encode(['success' => true]);
    }
    else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    if (isset($conn) && $conn->inTransaction()) {
        $conn->rollBack();
    }
    error_log("Error updating payment method: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>