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

ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

$userId = $decoded->sub ?? null;

$dateFilter = $_GET['date'] ?? null;
$query = "SELECT * FROM combines";
$params = [];

if ($dateFilter) {
    $query .= " WHERE date = :date";
    $params[':date'] = $dateFilter;
}
$query .= " ORDER BY date DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$combines = $stmt->fetchAll();

$results = [];

foreach ($combines as $combine) {
    $combineId = $combine['id'];
    $isVip = strtolower($combine['type']) === 'vip';

    // Satın alındı mı?
    $isPurchased = true;
    if ($isVip) {
        $check = $pdo->prepare("SELECT COUNT(*) FROM combine_purchases WHERE user_id = ? AND combine_id = ?");
        $check->execute([$userId, $combineId]);
        $isPurchased = $check->fetchColumn() > 0;
    }

    // Tip dönüşümleri
    $combine['is_purchased'] = $isPurchased;
    $combine['price'] = (int) $combine['price'];
    $combine['active'] = (int) $combine['active'];
    $combine['canEveryoneSee'] = (int) $combine['canEveryoneSee'];

    // Maçları al
    $stmtMatches = $pdo->prepare("
        SELECT 
            m.id, m.status, m.odds,
            m.home, m.away, m.league, m.country,
            m.date, m.time, m.prediction
        FROM combine_matches cm
        JOIN matches m ON m.id = cm.match_id
        WHERE cm.combine_id = ?
    ");
    $stmtMatches->execute([$combineId]);
    $matches = $stmtMatches->fetchAll();

    $totalOdds = 1.0;
    foreach ($matches as &$match) {
        $match['odds'] = floatval($match['odds']);
        $totalOdds *= $match['odds'];

        // VIP + satın alınmamış + canEveryoneSee = 0 → maç bilgilerini gizle
        $shouldHide = $isVip && !$isPurchased && $combine['canEveryoneSee'] === 0;
        if ($shouldHide) {
            $match['home'] = null;
            $match['away'] = null;
            $match['league'] = null;
            $match['country'] = null;
            $match['date'] = null;
            $match['time'] = null;
            $match['prediction'] = null;
        }
    }

    $combine['matches'] = $matches;
    $combine['total_odds'] = round($totalOdds, 2);
    $results[] = $combine;
}

echo json_encode([
    'success' => true,
    'combines' => $results
]);