<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../includes/student_auth.php';
require_once __DIR__ . '/../includes/db.php';

header('Content-Type: application/json; charset=utf-8');

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
    echo json_encode(['ok' => false, 'message' => 'Database connection error']);
    exit;
}

$mysqli->set_charset('utf8mb4');

$student_id = (int)(
    $_SESSION['student_id']
    ?? $_SESSION['user_id']
    ?? $_SESSION['id']
    ?? 0
);

$game_url = trim((string)($_POST['game_url'] ?? ''));
$score    = max(0, (int)($_POST['score'] ?? 0));
$total    = max(0, (int)($_POST['total'] ?? 0));
$time_sec = max(0, (int)($_POST['time_sec'] ?? 0));

$statusRaw = strtolower(trim((string)($_POST['status'] ?? 'completed')));

/*
 DB enum supports only:
 completed, timeout
*/
$status = match ($statusRaw) {
    'timeout' => 'timeout',
    default   => 'completed',
};

if ($student_id <= 0 || $game_url === '' || $total <= 0) {
    echo json_encode(['ok' => false, 'message' => 'Invalid attempt data']);
    exit;
}

if ($score > $total) {
    $score = $total;
}

$percent = round(($score / $total) * 100, 2);
$success = ($percent >= 50) ? 1 : 0;

$stmt = $mysqli->prepare("
    INSERT INTO lms_game_attempts
        (student_id, game_url, score, total, percent, success, time_sec, status)
    VALUES
        (?, ?, ?, ?, ?, ?, ?, ?)
");

if (!$stmt) {
    echo json_encode([
        'ok' => false,
        'message' => 'Prepare failed: ' . $mysqli->error
    ]);
    exit;
}

$stmt->bind_param(
    'isiidiis',
    $student_id,
    $game_url,
    $score,
    $total,
    $percent,
    $success,
    $time_sec,
    $status
);

$ok = $stmt->execute();
$error = $stmt->error;
$stmt->close();

if (!$ok) {
    echo json_encode([
        'ok' => false,
        'message' => 'Insert failed: ' . $error
    ]);
    exit;
}

echo json_encode([
    'ok'      => true,
    'score'   => $score,
    'total'   => $total,
    'percent' => $percent,
    'success' => $success,
    'status'  => $status
]);
exit;