<?php
session_start();

if (isset($_GET["logout"])) {
    unset($_SESSION["exam_questions"], $_SESSION["exam_start"]);
    session_destroy();
    header("Location: /");
    exit;
}

$examFile = __DIR__ . "/exams/dc_emt3.json";
$examTitle = "ESI DC-EMT III Senior Technician / SME Certification Exam";
$passingScore = 80;
$timeLimitMinutes = 120;
$examSize = 80;

if (!file_exists($examFile)) die("Exam bank not found.");

$bank = json_decode(file_get_contents($examFile), true);
if (!is_array($bank)) die("Invalid exam bank.");

function e($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, "UTF-8");
}

function buildExam($bank, $examSize) {
    shuffle($bank);
    if (count($bank) > $examSize) {
        $bank = array_slice($bank, 0, $examSize);
    }

    foreach ($bank as &$q) {
        $correctText = $q["choices"][$q["correct"]];
        shuffle($q["choices"]);
        $q["correct"] = array_search($correctText, $q["choices"], true);
    }
    unset($q);

    return $bank;
}

if (!isset($_SESSION["exam_questions"]) || isset($_GET["new"])) {
    $_SESSION["exam_questions"] = buildExam($bank, $examSize);
    $_SESSION["exam_start"] = time();
}

$questions = $_SESSION["exam_questions"];
$elapsed = time() - ($_SESSION["exam_start"] ?? time());
$timeRemaining = max(0, ($timeLimitMinutes * 60) - $elapsed);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $answers = $_POST["answers"] ?? [];
    $score = 0;
    $total = count($questions);
    $domains = [];

    foreach ($questions as $i => $q) {
        $domain = $q["domain"] ?? "General";
        if (!isset($domains[$domain])) {
            $domains[$domain] = ["correct" => 0, "total" => 0];
        }

        $domains[$domain]["total"]++;

        $selected = isset($answers[$i]) ? intval($answers[$i]) : -1;
        if ($selected === intval($q["correct"])) {
            $score++;
            $domains[$domain]["correct"]++;
        }
    }

    $percent = $total > 0 ? round(($score / $total) * 100) : 0;
    $passed = $percent >= $passingScore;

    unset($_SESSION["exam_questions"], $_SESSION["exam_start"]);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exam Results</title>
<style>
body{font-family:Arial;background:#f1f5f9;margin:0;color:#0f172a}
.box{max-width:950px;margin:50px auto;background:white;padding:35px;border-radius:14px}
.pass{color:#166534}.fail{color:#991b1b}
.card{border:1px solid #e2e8f0;border-radius:10px;padding:15px;margin:12px 0}
.good{border-left:6px solid #16a34a}.mid{border-left:6px solid #ca8a04}.bad{border-left:6px solid #dc2626}
a{display:inline-block;margin:8px 8px 0 0;background:#1d4ed8;color:white;padding:12px 16px;border-radius:8px;text-decoration:none;font-weight:bold}
.gray{background:#334155}.red{background:#991b1b}
</style>
</head>
<body>
<div class="box">
<h1>Exam Results</h1>
<h2 class="<?php echo $passed ? "pass" : "fail"; ?>"><?php echo $passed ? "PASS" : "FAIL"; ?></h2>

<p><strong>Score:</strong> <?php echo $score; ?> / <?php echo $total; ?></p>
<p><strong>Percentage:</strong> <?php echo $percent; ?>%</p>
<p><strong>Passing Score:</strong> <?php echo $passingScore; ?>%</p>

<h2>Performance Feedback</h2>

<?php if ($passed): ?>
<p>You demonstrated acceptable SME-level competency. Continue practicing weaker areas to maintain readiness.</p>
<?php else: ?>
<p>You did not meet the passing score. Review the domain feedback below before retaking the exam.</p>
<?php endif; ?>

<?php foreach ($domains as $domain => $d): ?>
<?php
$dp = $d["total"] > 0 ? round(($d["correct"] / $d["total"]) * 100) : 0;
$class = "bad";
$msg = "Needs practice. Review and retake after study.";
if ($dp >= 80) {
    $class = "good";
    $msg = "Strong performance.";
} elseif ($dp >= 70) {
    $class = "mid";
    $msg = "Acceptable but should improve for SME-level confidence.";
}
?>
<div class="card <?php echo $class; ?>">
<h3><?php echo e($domain); ?></h3>
<p><strong>Score:</strong> <?php echo $d["correct"]; ?> / <?php echo $d["total"]; ?> (<?php echo $dp; ?>%)</p>
<p><?php echo $msg; ?></p>
</div>
<?php endforeach; ?>

<hr>
<a href="exam_dc_emt3.php?new=1">Retake Exam</a>
<a class="gray" href="/">Return Home</a>
<a class="red" href="exam_dc_emt3.php?logout=1">Logout / Exit</a>
</div>
</body>
</html>
<?php
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo e($examTitle); ?></title>
<style>
body{font-family:Arial;background:#f1f5f9;margin:0;color:#0f172a}
.header{background:#0f172a;color:white;padding:22px 36px}
.row{display:flex;justify-content:space-between;align-items:center}
.exit{background:#991b1b;color:white;padding:10px 14px;border-radius:8px;text-decoration:none;font-weight:bold}
.container{max-width:1000px;margin:25px auto;padding:0 20px}
.card{background:white;padding:18px;margin-bottom:16px;border-radius:10px}
.timer{background:#fee2e2;color:#991b1b;padding:12px 16px;margin-bottom:18px;border-radius:10px;font-weight:bold}
.notice{background:white;padding:14px;border-radius:10px;margin-bottom:18px;color:#475569}
.choice{margin:10px 0}
button{background:#1d4ed8;color:white;padding:14px 22px;border:none;border-radius:8px;font-weight:bold;font-size:16px}
</style>
<script>
let timeRemaining = <?php echo $timeRemaining; ?>;
function updateTimer(){
    let m=Math.floor(timeRemaining/60);
    let s=timeRemaining%60;
    document.getElementById("timer").innerText="Time Remaining: "+m+":"+String(s).padStart(2,"0");
    if(timeRemaining<=0){document.getElementById("examForm").submit();}
    timeRemaining--;
}
function confirmExit(e){
    if(!confirm("Exit this exam? Your current attempt will not be saved.")){e.preventDefault();}
}
setInterval(updateTimer,1000);
window.onload=updateTimer;
</script>
</head>
<body>

<div class="header">
<div class="row">
<h1><?php echo e($examTitle); ?></h1>
<a class="exit" href="exam_dc_emt3.php?logout=1" onclick="confirmExit(event)">Exit Exam</a>
</div>
</div>

<div class="container">
<div id="timer" class="timer"></div>
<div class="notice">Questions and answer choices are randomized for each attempt.</div>

<form method="POST" id="examForm">
<?php foreach ($questions as $i => $q): ?>
<div class="card">
<p><strong><?php echo ($i + 1) . ". " . e($q["question"]); ?></strong></p>
<?php foreach ($q["choices"] as $ci => $c): ?>
<div class="choice">
<label>
<input type="radio" name="answers[<?php echo $i; ?>]" value="<?php echo $ci; ?>">
<?php echo e($c); ?>
</label>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<button type="submit">Submit Exam</button>
</form>
</div>

</body>
</html>
