<?php
// Set headers for JSON response
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');

// Bootstrap the application
require_once '../../../core/bootstrap.php';

// Protect this action
require_once '../middleware/validate_token.php';

// Check user role
$allowed_roles = ['commissioner', 'admin', 'super_admin'];
if (!in_array($authenticated_user_data->role, $allowed_roles)) {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'Access Denied. You do not have permission to log match events.']);
    exit();
}

// Instantiate models
$matchEvent = new MatchEvent();
$fixture = new Fixture(); // Instantiate Fixture model to update score

// Get raw posted data
$data = json_decode(file_get_contents("php://input"));

// Validation
$errors = [];
$valid_events = ['goal', 'assist', 'yellow_card', 'red_card', 'substitution']; // 'substitution' is now a special composite type
if (empty($data->fixture_id) || !is_numeric($data->fixture_id)) $errors[] = 'A numeric fixture_id is required.';
if (empty($data->team_id) || !is_numeric($data->team_id)) $errors[] = 'A numeric team_id is required.';
if (empty($data->player_id) || !is_numeric($data->player_id)) $errors[] = 'A numeric player_id is required.';
if (empty($data->event_type) || !in_array($data->event_type, $valid_events)) $errors[] = 'A valid event_type is required.';
if (!isset($data->minute) || !is_numeric($data->minute)) $errors[] = 'A numeric minute is required.';

if (!empty($errors)) {
    http_response_code(400); // Bad Request
    echo json_encode(['errors' => $errors]);
    exit();
}

if ($data->event_type === 'substitution' && (empty($data->player_in_id) || empty($data->player_out_id))) {
    http_response_code(400); // Bad Request
    echo json_encode(['errors' => $errors]);
    exit();
}

// TODO: Add validation to ensure fixture, team, and player exist.

// Handle substitution as a special case
if ($data->event_type === 'substitution') {
    $subData = [
        'fixture_id' => $data->fixture_id,
        'team_id' => $data->team_id,
        'player_out_id' => $data->player_out_id,
        'player_in_id' => $data->player_in_id,
        'minute' => $data->minute
    ];
    if ($matchEvent->logSubstitution($subData)) {
        http_response_code(201);
        echo json_encode(['message' => 'Substitution logged successfully.']);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Substitution could not be logged.']);
    }
} else { // Handle all other event types
    $eventData = [
        'fixture_id' => $data->fixture_id,
        'team_id' => $data->team_id,
        'player_id' => $data->player_id,
        'event_type' => $data->event_type,
        'minute' => $data->minute,
        'assisted_by_player_id' => $data->assisted_by_player_id ?? null
    ];

    $newEventId = $matchEvent->log($eventData);

    if ($newEventId) {
        if ($data->event_type === 'goal') {
            $fixture->incrementScore($data->fixture_id, $data->team_id);
        }
        http_response_code(201);
        echo json_encode(['message' => 'Match event logged successfully. Score updated if applicable.', 'event_id' => $newEventId]);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Match event could not be logged.']);
    }
}
?>