<?php
require_once __DIR__ . '/../auth_middleware.php';
require_once '/home/akgbilis/fi_sf/config.php';

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

// JWT'den user id çek
$userId = $decoded->sub ?? null;

if (!$userId) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Kullanıcının oluşturduğu kuponları çek
$combineStmt = $pdo->prepare("SELECT * FROM user_generated_combines WHERE user_id = ? ORDER BY created_at DESC");
$combineStmt->execute([$userId]);
$combines = $combineStmt->fetchAll(PDO::FETCH_ASSOC);

if (!$combines) {
    echo json_encode(['success' => true, 'coupons' => []]);
    exit;
}

// Her kupona ait maçları çek
foreach ($combines as &$combine) {
    $matchStmt = $pdo->prepare("
        SELECT m.*
        FROM user_generated_combine_matches ugcm
        JOIN matches m ON ugcm.match_id = m.id
        WHERE ugcm.combine_id = ?
    ");
    $matchStmt->execute([$combine['id']]);
    $combine['matches'] = $matchStmt->fetchAll(PDO::FETCH_ASSOC);
}

// Yanıt
echo json_encode([
    'success' => true,
    'coupons' => $combines
]);