<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

session_start(); // Start the session to access user information

// Check if the user is logged in (you might have a different session variable)
if (!isset($_SESSION['user_id'])) {
    http_response_code(401); // Unauthorized
    echo json_encode(['message' => 'You must be logged in to submit a comment.']);
    exit();
}

$fixture_id = filter_input(INPUT_POST, 'fixture_id', FILTER_VALIDATE_INT);
$comment_text = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); // Get raw comment
$comment = htmlspecialchars($comment_text, ENT_QUOTES, 'UTF-8'); // Sanitize for output

if (!$fixture_id || !$comment) {
    http_response_code(400);
    echo json_encode(['message' => 'Fixture ID and comment are required.']);
    exit();
}

$user_id = $_SESSION['user_id']; // Assuming you store the user ID in $_SESSION['user_id']

$commentModel = new MatchComment();

try {
    $result = $commentModel->submitComment($fixture_id, $user_id, $comment);
    if ($result) {
        http_response_code(201);
        echo json_encode(['message' => 'Comment submitted successfully.']);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Failed to submit comment.']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred while submitting the comment.', 'error' => $e->getMessage()]);
}
?>
