<?php
header('Content-Type: application/json');
require_once '../../core/bootstrap.php';

// --- Authentication & Authorization ---
if (!isset($_SESSION['user_id'])) {
    http_response_code(401); // Unauthorized
    echo json_encode(['error' => 'User not authenticated.']);
    exit();
}

// --- 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) {
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'Invalid or missing player ID.']);
    exit();
}

// If gameweek is not provided, find the latest finished one.
if (!$gameweek) {
    $fixtureModel = new Fixture();
    $gameweek = $fixtureModel->getLatestFinishedGameweek(1); // Assuming league_id 1
    if (!$gameweek) {
        http_response_code(404); // Not Found
        echo json_encode(['error' => 'No completed gameweek found.']);
        exit();
    }
}

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

echo json_encode($breakdown);
?>