<?php
require_once '../../core/bootstrap.php';

// --- Authentication Check ---
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    exit(json_encode(['error' => 'Unauthorized']));
}

// --- Input Validation ---
$player_id = filter_input(INPUT_GET, 'player_id', FILTER_VALIDATE_INT);
$gameweek = filter_input(INPUT_GET, 'gameweek', FILTER_VALIDATE_INT);

if (!$player_id || !$gameweek) {
    http_response_code(400);
    exit(json_encode(['error' => 'Invalid parameters']));
}

// --- Fetch Data ---
$fantasyPointsModel = new FantasyPoints();
$data = $fantasyPointsModel->getPointsBreakdownForPlayer($player_id, $gameweek);

// --- Process Data ---
// Decode the JSON breakdown string into an object for the frontend
foreach ($data as $row) {
    if (isset($row->breakdown)) {
        $row->breakdown = json_decode($row->breakdown);
    }
}

// --- Output JSON ---
header('Content-Type: application/json');
echo json_encode($data);
?>
