<?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';

// Only commissioners and admins should be able to do this
if ($authenticated_user_data->role !== 'commissioner' && $authenticated_user_data->role !== 'admin') {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'Access Denied.']);
    exit();
}

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

if (empty($data->fixture_id) || empty($data->action)) {
    http_response_code(400);
    echo json_encode(['message' => 'fixture_id and action are required.']);
    exit();
}

$fixture = new Fixture();
$success = false;

switch ($data->action) {
    case 'start_first_half':
        $success = $fixture->updateStatus($data->fixture_id, 'live', 'first_half_start_time');
        break;
    case 'end_first_half':
        $success = $fixture->updateStatus($data->fixture_id, 'half_time');
        break;
    case 'start_second_half':
        $success = $fixture->updateStatus($data->fixture_id, 'live', 'second_half_start_time');
        break;
    case 'end_match':
        $success = $fixture->updateStatus($data->fixture_id, 'finished');
        break;
    default:
        http_response_code(400);
        echo json_encode(['message' => 'Invalid action provided.']);
        exit();
}

if ($success) {
    http_response_code(200);
    echo json_encode(['message' => 'Match status updated successfully.']);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'Failed to update match status.']);
}

?>