<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require '../../../db.php';

$method = $_SERVER['REQUEST_METHOD'];
$data = json_decode(file_get_contents("php://input"));

// Mock User ID from request (Security Warning: same as above)
$user_id = isset($_GET['user_id']) ? $_GET['user_id'] : (isset($data->user_id) ? $data->user_id : null);

if (!$user_id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'User ID required']);
    exit();
}

try {
    if ($method === 'GET') {
        $stmt = $pdo->prepare("SELECT * FROM user_payment_methods WHERE user_id = ? ORDER BY is_default DESC, created_at DESC");
        $stmt->execute([$user_id]);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    } 
    elseif ($method === 'POST') {
        // Add new method
        if (!isset($data->type) || !isset($data->details)) {
            throw new Exception("Missing type or details");
        }
        
        $details = is_string($data->details) ? $data->details : json_encode($data->details);
        
        $sql = "INSERT INTO user_payment_methods (user_id, type, details, is_default) VALUES (?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user_id, $data->type, $details, 0]);
        
        echo json_encode(['success' => true, 'message' => 'Payment method added']);
    }
    elseif ($method === 'DELETE') {
        if (!isset($data->id)) throw new Exception("ID required");
        
        $stmt = $pdo->prepare("DELETE FROM user_payment_methods WHERE id = ? AND user_id = ?");
        $stmt->execute([$data->id, $user_id]);
        
        echo json_encode(['success' => true, 'message' => 'Payment method deleted']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
