<?php
// api/daily_match.php

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

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

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

if (!$user_id) {
    echo json_encode(["error" => "Kullanıcı ID bulunamadı"]);
    exit;
}

// Günün maçını al
$stmt = $pdo->query("SELECT * FROM daily_matches ORDER BY date DESC LIMIT 1");
$match = $stmt->fetch();

if (!$match) {
    echo json_encode(["error" => "Günün maçı bulunamadı"]);
    exit;
}

// Tahmin seçeneklerini al
$stmt = $pdo->prepare("SELECT * FROM daily_match_options WHERE match_id = ?");
$stmt->execute([$match['id']]);
$options = $stmt->fetchAll();

// Kullanıcının varsa yaptığı tahmini çek
$stmt = $pdo->prepare("SELECT selected_option FROM daily_predictions WHERE user_id = ? AND match_id = ?");
$stmt->execute([$user_id, $match['id']]);
$userPrediction = $stmt->fetchColumn();

$response = [
    "success" => true,
    "match" => [
        "id" => $match['id'],
        "country" => $match['country'],
        "league" => $match['league'],
        "date" => $match['date'],
        "time" => $match['time'],
        "homeTeam" => $match['home_team'],
        "awayTeam" => $match['away_team'],
        "isStarted" => (bool) $match['is_started'],
        "options" => array_map(function ($opt) {
            return [
                "id" => $opt['id'],
                "text" => $opt['option_text']
            ];
        }, $options),
        "user_prediction" => $userPrediction ?: null
    ]
];

echo json_encode($response);