<?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 = ['referee', 'admin', 'super_admin'];
if (!in_array($authenticated_user_data->role, $allowed_roles)) {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'Access Denied. Only Referees or Admins can submit reports.']);
    exit();
}

// Instantiate models
$matchReport = new MatchReport();
$fixture = new Fixture();

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

// Validation
$errors = [];
if (empty($data->fixture_id) || !is_numeric($data->fixture_id)) $errors[] = 'A numeric fixture_id is required.';
if (empty($data->report_content)) $errors[] = 'report_content cannot be empty.';

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

// --- Further Authorization & Validation ---
$targetFixture = $fixture->findById($data->fixture_id);
if (!$targetFixture) {
    http_response_code(404);
    echo json_encode(['message' => 'Fixture not found.']);
    exit();
}

// A referee can only submit a report for a match they are assigned to. Admins can override.
if ($authenticated_user_data->role === 'referee' && $authenticated_user_data->id != $targetFixture->referee_id) {
    http_response_code(403);
    echo json_encode(['message' => 'Access Denied. You are not the assigned referee for this match.']);
    exit();
}

$reportData = [
    'fixture_id' => $data->fixture_id,
    'referee_id' => $authenticated_user_data->id, // The referee is the authenticated user
    'report_content' => htmlspecialchars($data->report_content)
];

if ($matchReport->create($reportData)) {
    http_response_code(201); // Created
    echo json_encode(['message' => 'Match report submitted successfully.']);
} else {
    // This could fail if a report for this fixture by this referee already exists (UNIQUE constraint)
    http_response_code(500);
    echo json_encode(['message' => 'Match report could not be submitted. It may already exist.']);
}
?>