<?php
session_start();

// ============================================================
// CONNECT TO OSCE DATABASE
// ============================================================
$db = new PDO('sqlite:database.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


// ============================================================
// OSCE PROCEDURES TABLE
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS OSCE_procedures (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        table_name TEXT UNIQUE
    )
");


// ============================================================
// OSCE PROCEDURE ACTIONS
// ============================================================
if (isset($_POST['action'])) {

    if (
        $_POST['action'] === 'add' &&
        !empty($_POST['table_name'])
    ) {

        $stmt = $db->prepare("
            INSERT OR IGNORE INTO OSCE_procedures (table_name)
            VALUES (:table_name)
        ");

        $stmt->execute([
            ':table_name' => $_POST['table_name']
        ]);

        exit;
    }


    if (
        $_POST['action'] === 'remove' &&
        !empty($_POST['table_name'])
    ) {

        $stmt = $db->prepare("
            DELETE FROM OSCE_procedures
            WHERE table_name = :table_name
        ");

        $stmt->execute([
            ':table_name' => $_POST['table_name']
        ]);

        exit;
    }


    if ($_POST['action'] === 'clear_all') {

        $db->exec("DELETE FROM OSCE_procedures");

        exit;
    }


    if ($_POST['action'] === 'get_selected') {

        $stmt = $db->query("
            SELECT table_name
            FROM OSCE_procedures
            ORDER BY table_name ASC
        ");

        echo json_encode(
            $stmt->fetchAll(PDO::FETCH_COLUMN)
        );

        exit;
    }

    // ============================================================
    // DELETE PROCEDURE TABLE
    // ============================================================
    if ($_POST['action'] === 'delete_table' && !empty($_POST['table_name'])) {
        $tableName = $_POST['table_name'];

        try {
            // First, remove from OSCE_procedures table
            $stmt = $db->prepare("DELETE FROM OSCE_procedures WHERE table_name = :table_name");
            $stmt->execute([':table_name' => $tableName]);

            // Then drop the actual table
            $db->exec("DROP TABLE IF EXISTS '$tableName'");

            echo json_encode(['success' => true, 'message' => "Procedure checklist deleted successfully!"]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => 'Error deleting table: ' . $e->getMessage()]);
        }

        exit;
    }
}


// ============================================================
// FETCH SELECTED PROCEDURES
// ============================================================
$selectedTablesStmt = $db->query("
    SELECT table_name
    FROM OSCE_procedures
    ORDER BY table_name ASC
");

$selectedTables = $selectedTablesStmt->fetchAll(PDO::FETCH_COLUMN);


// ============================================================
// FETCH ALL PRO TABLES
// ============================================================
$query = "
    SELECT name
    FROM sqlite_master
    WHERE type='table'
    AND name LIKE 'PRO%'
    ORDER BY name ASC
";

$stmt = $db->query($query);

$tables = $stmt->fetchAll(PDO::FETCH_COLUMN);


// ============================================================
// FORMAT TABLE NAME
// ============================================================
function formatTableName($name)
{
    $name = preg_replace('/^PRO/', '', $name);
    $name = preg_replace('/(?<!^)([A-Z])/', ' $1', $name);

    return trim($name);
}


// ============================================================
// EXAMINERS TABLE
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS examiners_table (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        examiner_number INTEGER UNIQUE
    )
");


// ============================================================
// EXAMINER ACTIONS
// ============================================================
if (isset($_POST['exam_action'])) {

    if (
        $_POST['exam_action'] === 'add' &&
        isset($_POST['examiner_number'])
    ) {

        $number = (int) $_POST['examiner_number'];

        // Allow only 1-20
        if ($number >= 1 && $number <= 20) {

            // Only one active examiner configuration
            $db->exec("DELETE FROM examiners_table");

            $stmt = $db->prepare("
                INSERT INTO examiners_table (examiner_number)
                VALUES (:num)
            ");

            $stmt->execute([
                ':num' => $number
            ]);
        }

        exit;
    }


    if (
        $_POST['exam_action'] === 'remove' &&
        isset($_POST['examiner_number'])
    ) {

        $stmt = $db->prepare("
            DELETE FROM examiners_table
            WHERE examiner_number = :num
        ");

        $stmt->execute([
            ':num' => $_POST['examiner_number']
        ]);

        exit;
    }


    if ($_POST['exam_action'] === 'get') {

        $stmt = $db->query("
            SELECT examiner_number
            FROM examiners_table
            LIMIT 1
        ");

        echo json_encode(
            $stmt->fetchAll(PDO::FETCH_COLUMN)
        );

        exit;
    }
}


// ============================================================
// PROCEDURES PER EXAMINER TABLE
//
// Stores numbers 1-20 permanently.
// is_selected = 1 means the number is currently selected.
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS procedure_per_examiner (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        procedure_number INTEGER UNIQUE NOT NULL,
        is_selected INTEGER NOT NULL DEFAULT 0
    )
");


// ============================================================
// INSERT NUMBERS 1-20
// ============================================================
for ($i = 1; $i <= 20; $i++) {

    $stmt = $db->prepare("
        INSERT OR IGNORE INTO procedure_per_examiner
        (procedure_number, is_selected)
        VALUES (:number, 0)
    ");

    $stmt->execute([
        ':number' => $i
    ]);
}


// ============================================================
// PROCEDURES PER EXAMINER ACTIONS
// ============================================================
if (isset($_POST['procedure_action'])) {

    // --------------------------------------------------------
    // SELECT NUMBER
    // --------------------------------------------------------
    if (
        $_POST['procedure_action'] === 'add' &&
        isset($_POST['procedure_number'])
    ) {

        $number = (int) $_POST['procedure_number'];

        // Only allow 1-20
        if ($number >= 1 && $number <= 20) {

            // First clear previous selection
            $db->exec("
                UPDATE procedure_per_examiner
                SET is_selected = 0
            ");

            // Set new selection
            $stmt = $db->prepare("
                UPDATE procedure_per_examiner
                SET is_selected = 1
                WHERE procedure_number = :number
            ");

            $stmt->execute([
                ':number' => $number
            ]);
        }

        exit;
    }


    // --------------------------------------------------------
    // REMOVE SELECTION
    // --------------------------------------------------------
    if ($_POST['procedure_action'] === 'remove') {

        $db->exec("
            UPDATE procedure_per_examiner
            SET is_selected = 0
        ");

        exit;
    }


    // --------------------------------------------------------
    // GET SELECTED NUMBER
    // --------------------------------------------------------
    if ($_POST['procedure_action'] === 'get') {

        $stmt = $db->query("
            SELECT procedure_number
            FROM procedure_per_examiner
            WHERE is_selected = 1
            LIMIT 1
        ");

        $result = $stmt->fetchAll(PDO::FETCH_COLUMN);

        echo json_encode($result);

        exit;
    }


    // --------------------------------------------------------
    // GET ALL AVAILABLE NUMBERS
    // --------------------------------------------------------
    if ($_POST['procedure_action'] === 'get_all') {

        $stmt = $db->query("
            SELECT procedure_number
            FROM procedure_per_examiner
            ORDER BY procedure_number ASC
        ");

        echo json_encode(
            $stmt->fetchAll(PDO::FETCH_COLUMN)
        );

        exit;
    }
}


// ============================================================
// OSCE SCORE TABLE
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS osce_score (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        total_score INTEGER UNIQUE
    )
");


// ============================================================
// OSCE SCORE ACTIONS
// ============================================================
if (isset($_POST['score_action'])) {

    if (
        $_POST['score_action'] === 'add' &&
        isset($_POST['total_score'])
    ) {

        $score = (int) $_POST['total_score'];

        // Only allow 5-100 in increments of 5
        if (
            $score >= 5 &&
            $score <= 100 &&
            $score % 5 === 0
        ) {

            $db->exec("DELETE FROM osce_score");

            $stmt = $db->prepare("
                INSERT INTO osce_score (total_score)
                VALUES (:score)
            ");

            $stmt->execute([
                ':score' => $score
            ]);
        }

        exit;
    }


    if ($_POST['score_action'] === 'remove') {

        $db->exec("DELETE FROM osce_score");

        exit;
    }


    if ($_POST['score_action'] === 'get') {

        $stmt = $db->query("
            SELECT total_score
            FROM osce_score
            LIMIT 1
        ");

        echo json_encode(
            $stmt->fetchAll(PDO::FETCH_COLUMN)
        );

        exit;
    }
}

// Get current page name for active navigation
$current_page = basename($_SERVER['PHP_SELF']);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CAOSCE · Network</title>
    <link rel="icon" type="image/x-icon" href="CAOSCE Network.ico">
    <!-- Font Awesome 6 (Free) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* ----- RESET & BASE ----- */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f0f4fb;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            color: #10233f;
        }

        /* ----- NAVIGATION (SOLID, NON-TRANSPARENT) ----- */
        .navbar {
            position: sticky;
            top: 0;
            z-index: 60;
            background: #ffffff;
            border-bottom: 2px solid #e2eaf2;
            padding: 0 5vw;
            height: 74px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 12px rgba(16, 35, 63, 0.06);
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 800;
            font-size: 20px;
            color: #10233f;
            text-decoration: none;
        }

        .brand-icon {
            width: 38px;
            height: 38px;
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            border-radius: 12px;
            display: grid;
            place-items: center;
            color: white;
            font-size: 18px;
            font-weight: 900;
            box-shadow: 0 8px 18px rgba(26, 108, 240, 0.25);
        }

        .brand-light {
            font-weight: 500;
            color: #4f6580;
        }

        .nav-links {
            display: flex;
            align-items: center;
            gap: 28px;
        }

        .nav-links a {
            font-size: 14px;
            font-weight: 600;
            color: #4f6580;
            text-decoration: none;
            transition: 0.2s;
            position: relative;
            padding: 6px 0;
        }

        .nav-links a i {
            margin-right: 6px;
            font-size: 13px;
        }

        .nav-links a:hover {
            color: #1a6cf0;
        }

        .nav-links a.active {
            color: #1a6cf0;
        }

        .nav-links a.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 3px;
            background: #1a6cf0;
            border-radius: 4px;
        }

        .nav-logout {
            background: #f0f4fb;
            border: 1px solid #d9e2eb;
            border-radius: 30px;
            padding: 6px 18px;
            font-weight: 600;
            font-size: 13px;
            color: #10233f;
            transition: 0.2s;
        }

        .nav-logout:hover {
            background: #e2eaf2;
            border-color: #b0c4d8;
            color: #1a6cf0;
        }

        /* ----- MAIN CONTAINER ----- */
        main {
            flex: 1;
            padding: 30px 5vw;
        }

        .container {
            max-width: 1300px;
            margin: 0 auto;
        }

        /* ----- PAGE HEADER ----- */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px 28px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
            border: 1px solid #eef4fa;
            flex-wrap: wrap;
            gap: 15px;
        }

        .page-header h1 {
            color: #10233f;
            font-weight: 700;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header h1 i {
            color: #1a6cf0;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 22px;
            border: none;
            border-radius: 30px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            font-size: 14px;
        }

        .btn-back {
            background: #e9ecef;
            color: #4f6580;
        }

        .btn-back:hover {
            background: #dde1e6;
            transform: translateY(-2px);
        }

        .btn-primary {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
            box-shadow: 0 4px 14px rgba(26, 108, 240, 0.25);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(26, 108, 240, 0.35);
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(220, 53, 69, 0.25);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(40, 167, 69, 0.3);
        }

        .btn-sm {
            padding: 6px 14px;
            font-size: 12px;
            border-radius: 20px;
        }

        /* ----- CARDS ----- */
        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
            padding: 25px 28px;
            margin-bottom: 25px;
            border: 1px solid #eef4fa;
            transition: 0.3s;
        }

        .card:hover {
            box-shadow: 0 8px 28px rgba(0, 0, 0, 0.08);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 18px;
            padding-bottom: 14px;
            border-bottom: 2px solid #f0f4fb;
            flex-wrap: wrap;
            gap: 10px;
        }

        .card-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #10233f;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-title i {
            color: #1a6cf0;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 5px 14px;
            background: #1a6cf0;
            color: white;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        /* ----- CONFIG GRID ----- */
        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        .config-item {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .config-item label {
            font-weight: 600;
            color: #10233f;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }

        .config-item label i {
            color: #1a6cf0;
        }

        .config-item select {
            padding: 11px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 14px;
            background: white;
            transition: 0.3s;
            cursor: pointer;
        }

        .config-item select:focus {
            outline: none;
            border-color: #1a6cf0;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
        }

        /* ----- SELECTED LIST ----- */
        .selected-list {
            list-style: none;
            margin-top: 12px;
        }

        .selected-list li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 16px;
            margin-bottom: 8px;
            background: #f8fafc;
            border-radius: 10px;
            transition: 0.3s;
            border: 1px solid #eef4fa;
        }

        .selected-list li:hover {
            background: #f0f4fb;
        }

        .selected-list li span {
            font-weight: 500;
            cursor: pointer;
        }

        .selected-list li span:hover {
            color: #1a6cf0;
        }

        .selected-list li button {
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: 0.3s;
            font-size: 14px;
        }

        .selected-list li button:hover {
            background: #c82333;
            transform: scale(1.1);
        }

        .empty-message {
            color: #6b7a8f;
            font-style: italic;
            padding: 8px 0;
        }

        /* ----- SEARCH ----- */
        .search-box {
            position: relative;
            margin-bottom: 18px;
        }

        .search-box i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #6b7a8f;
        }

        .search-box input {
            width: 100%;
            padding: 12px 16px 12px 44px;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            font-size: 15px;
            transition: 0.3s;
            background: white;
        }

        .search-box input:focus {
            outline: none;
            border-color: #1a6cf0;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
        }

        /* ----- TABLE ----- */
        .table-wrapper {
            overflow-x: auto;
            border-radius: 12px;
            border: 1px solid #eef4fa;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        th {
            background: #f8fafc;
            color: #10233f;
            font-weight: 700;
            padding: 13px 18px;
            text-align: left;
            border-bottom: 2px solid #e2eaf2;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        td {
            padding: 12px 18px;
            border-bottom: 1px solid #eef4fa;
            vertical-align: middle;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover td {
            background: #f8fafc;
        }

        .selected-row {
            background: #e8f4ff !important;
        }

        .selected-row:hover td {
            background: #dce8f5 !important;
        }

        /* ----- CHECKBOX ----- */
        .checkbox-container {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
        }

        .custom-checkbox {
            position: relative;
            width: 22px;
            height: 22px;
            display: inline-block;
        }

        .custom-checkbox input {
            opacity: 0;
            position: absolute;
            width: 0;
            height: 0;
        }

        .checkmark {
            position: absolute;
            top: 0;
            left: 0;
            height: 22px;
            width: 22px;
            background-color: white;
            border: 2px solid #6b7a8f;
            border-radius: 6px;
            transition: 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .custom-checkbox input:checked~.checkmark {
            background-color: #1a6cf0;
            border-color: #1a6cf0;
        }

        .custom-checkbox input:checked~.checkmark:after {
            content: "✓";
            color: white;
            font-weight: bold;
            font-size: 14px;
        }

        /* ----- TABLE NAME - CLICKABLE, FULL WIDTH, NO CUTTING ----- */
        .table-name {
            font-weight: 500;
            font-size: 15px;
            color: #1a6cf0;
            white-space: normal;
            word-wrap: break-word;
            word-break: normal;
            max-width: none;
            padding: 8px 12px;
            display: inline-block;
            line-height: 1.5;
            cursor: pointer;
            transition: 0.2s;
            border-radius: 6px;
        }

        .table-name:hover {
            background: #eef4ff;
            color: #0e4db0;
        }

        .table-name-wrapper {
            display: flex;
            align-items: center;
            padding: 4px 0;
        }

        /* ----- ACTION BUTTONS - HORIZONTAL LINE ----- */
        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            flex-wrap: nowrap;
            min-width: 240px;
            white-space: nowrap;
        }

        .btn-action {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border: none;
            border-radius: 8px;
            font-weight: 500;
            cursor: pointer;
            transition: 0.3s;
            font-size: 13px;
            white-space: nowrap;
        }

        .btn-view {
            background: #1a6cf0;
            color: white;
        }

        .btn-view:hover {
            background: #1057c0;
            transform: translateY(-2px);
        }

        .btn-edit {
            background: #f39c12;
            color: white;
        }

        .btn-edit:hover {
            background: #d68910;
            transform: translateY(-2px);
        }

        .btn-delete-procedure {
            background: #dc3545;
            color: white;
        }

        .btn-delete-procedure:hover {
            background: #b91c1c;
            transform: translateY(-2px);
        }

        /* ----- SEPARATOR LINE BETWEEN PROCEDURES ----- */
        .procedure-separator td {
            border-bottom: 2px solid #10233f;
            padding: 0;
            height: 2px;
        }

        /* ----- NO RESULT ----- */
        .no-result {
            text-align: center;
            padding: 40px 20px;
            color: #6b7a8f;
        }

        .no-result i {
            font-size: 40px;
            color: #d9e2eb;
            display: block;
            margin-bottom: 12px;
        }

        /* ----- FLOATING BUTTON ----- */
        .floating-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 16px 28px;
            border-radius: 50px;
            font-weight: 700;
            font-size: 16px;
            text-decoration: none;
            box-shadow: 0 8px 30px rgba(40, 167, 69, 0.35);
            transition: all 0.3s ease;
            z-index: 1000;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            border: none;
            cursor: pointer;
        }

        .floating-btn:hover {
            transform: translateY(-4px) scale(1.02);
            box-shadow: 0 12px 40px rgba(40, 167, 69, 0.45);
        }

        /* ----- DELETE CONFIRMATION MODAL ----- */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(4px);
        }

        .modal-content {
            background: white;
            padding: 30px 35px;
            width: 90%;
            max-width: 450px;
            border-radius: 20px;
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.2);
            animation: modalIn 0.3s ease;
            text-align: center;
        }

        @keyframes modalIn {
            from {
                transform: scale(0.9) translateY(20px);
                opacity: 0;
            }

            to {
                transform: scale(1) translateY(0);
                opacity: 1;
            }
        }

        .modal-content .close {
            float: right;
            font-size: 28px;
            font-weight: 700;
            color: #999;
            cursor: pointer;
            transition: 0.2s;
            background: none;
            border: none;
            padding: 0 8px;
        }

        .modal-content .close:hover {
            color: #333;
        }

        .modal-content h2 {
            font-size: 22px;
            margin-bottom: 12px;
            color: #10233f;
        }

        .modal-content h2 i {
            color: #dc3545;
        }

        .modal-content p {
            color: #6b7a8f;
            margin-bottom: 20px;
            font-size: 15px;
            line-height: 1.6;
        }

        .modal-content .modal-actions {
            display: flex;
            gap: 12px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .modal-content .modal-actions .btn {
            min-width: 120px;
            justify-content: center;
        }

        /* ----- FOOTER ----- */
        .footer {
            margin-top: auto;
            padding: 24px 5vw 20px;
            background: #071a31;
            color: #b6c9dd;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            border-top: 1px solid #1f3550;
        }

        .footer strong {
            color: #dce7f5;
        }

        .footer .meta {
            display: flex;
            gap: 24px;
            align-items: center;
        }

        .footer .meta span {
            color: #7c92ab;
        }

        /* ----- RESPONSIVE ----- */
        @media (max-width: 900px) {
            .navbar {
                padding: 0 4vw;
                height: 68px;
            }

            .nav-links a:not(.nav-logout) {
                display: none;
            }

            .nav-links a.nav-logout {
                display: inline-block;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .config-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .action-buttons {
                flex-direction: column;
                align-items: flex-end;
                gap: 4px;
                min-width: unset;
                white-space: normal;
            }

            .btn-action {
                width: 100%;
                justify-content: center;
                white-space: nowrap;
            }

            .checkbox-container {
                width: 30px;
            }
        }

        @media (max-width: 600px) {
            main {
                padding: 16px 4vw;
            }

            .card {
                padding: 18px 16px;
            }

            .page-header {
                padding: 16px 18px;
            }

            .page-header h1 {
                font-size: 1.4rem;
            }

            th,
            td {
                padding: 10px 12px;
                font-size: 13px;
            }

            .table-name {
                font-size: 13px;
                padding: 6px 8px;
            }

            .action-buttons {
                flex-direction: row;
                flex-wrap: wrap;
                justify-content: center;
                gap: 4px;
            }

            .btn-action {
                width: auto;
                font-size: 11px;
                padding: 4px 10px;
                white-space: nowrap;
            }

            .footer {
                flex-direction: column;
                gap: 10px;
                align-items: flex-start;
            }

            .floating-btn {
                bottom: 16px;
                right: 16px;
                padding: 12px 20px;
                font-size: 14px;
            }

            .modal-content {
                padding: 25px 20px;
            }
        }

        @media (max-width: 400px) {
            .brand {
                font-size: 16px;
            }

            .brand-icon {
                width: 30px;
                height: 30px;
                font-size: 14px;
            }
        }
    </style>
</head>

<body>
    <!-- ============================================================
         NAVIGATION (SOLID, NON-TRANSPARENT)
         ============================================================ -->
    <header class="navbar">
        <a href="admin.php" class="brand">
            <span class="brand-icon">CN</span>
            <span>CAOSCE <span class="brand-light">Network</span></span>
        </a>
        <div class="nav-links">
            <a href="admin.php" class="<?php echo $current_page == 'admin.php' ? 'active' : ''; ?>">
                <i class="fas fa-th-large"></i> Dashboard
            </a>
            <a href="classes.php" class="<?php echo $current_page == 'classes.php' ? 'active' : ''; ?>">
                <i class="fas fa-user-plus"></i> Class lists
            </a>
            <a href="result.php" class="<?php echo $current_page == 'result.php' ? 'active' : ''; ?>">
                <i class="fas fa-chart-pie"></i>OSCE Result
            </a>
            <a href="exam_manager.php" class="<?php echo $current_page == 'exam_manager.php' ? 'active' : ''; ?>">
                <i class="fas fa-sliders-h"></i> Exams settings
            </a>
            <a href="logout.php" class="nav-logout">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
    </header>

    <!-- ============================================================
         MAIN CONTENT
         ============================================================ -->
    <main>
        <div class="container">

            <!-- Page Header -->
            <div class="page-header">
                <h1>
                    <i class="fas fa-list-check"></i>
                    OSCE Procedures Manager
                </h1>

                <div class="header-actions">
                    <a href="admin.php" class="btn btn-back">
                        <i class="fas fa-arrow-left"></i> Back to Admin
                    </a>

                    <a href="new_procedure.php" class="btn btn-primary">
                        <i class="fas fa-plus-circle"></i> New Procedure
                    </a>
                    <!-- ============================================================
     In exam_manager.php - Replace the Global Procedures Checklists button
     ============================================================ -->

                    
                    <!-- Replace with this form-based approach -->
                    <form method="POST" action="https://caosce.net/global_osce_checklists.php" style="display:inline;">
                        <?php
                        // Get the school data from session or database
                        $institution_id = $_SESSION['institution_id'] ?? '';
                        $school_name = $_SESSION['school_name'] ?? '';

                        // If not in session, try to fetch from database
                        if (empty($institution_id) || empty($school_name)) {
                            try {
                                // Get the school data from the database
                                $stmt = $db->prepare("SELECT institution_id, school_name, email, phone, country, city FROM schools WHERE status = 'approved' LIMIT 1");
                                $stmt->execute();
                                $school_data = $stmt->fetch(PDO::FETCH_ASSOC);
                                if ($school_data) {
                                    $institution_id = $school_data['institution_id'] ?? '';
                                    $school_name = $school_data['school_name'] ?? '';
                                }
                            } catch (PDOException $e) {
                                // Silently fail
                            }
                        }
                        ?>
                        <input type="hidden" name="institution_id" value="<?= htmlspecialchars($institution_id) ?>">
                        <input type="hidden" name="school_name" value="<?= htmlspecialchars($school_name) ?>">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-globe"></i> Global Procedures Checklists
                        </button>
                    </form>


                </div>
            </div>

            <!-- Configuration Cards -->
            <div class="config-grid">

                <!-- Examiners Configuration -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user-md"></i>
                            Examiners Configuration
                        </h3>
                    </div>
                    <div class="config-item">
                        <label for="examinerDropdown">
                            <i class="fas fa-users"></i> Examiners Per Ward
                        </label>
                        <select id="examinerDropdown">
                            <option value="">Select Examiners Per Ward</option>
                            <?php for ($i = 1; $i <= 8; $i++): ?>
                                <option value="<?= $i ?>">Examiners Per Ward: <?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                        <ul id="examinerList" class="selected-list"></ul>
                    </div>
                </div>

                <!-- Procedures Per Examiner -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list-ol"></i>
                            Procedures Per Examiner
                        </h3>
                    </div>
                    <div class="config-item">
                        <label for="procedurePerExaminerDropdown">
                            <i class="fas fa-clipboard-list"></i> Number of Procedures
                        </label>
                        <select id="procedurePerExaminerDropdown">
                            <option value="">Select Procedures Per Examiner</option>
                            <?php for ($i = 1; $i <= 20; $i++): ?>
                                <option value="<?= $i ?>"><?= $i ?> Procedure<?= $i == 1 ? '' : 's' ?></option>
                            <?php endfor; ?>
                        </select>
                        <ul id="procedurePerExaminerList" class="selected-list"></ul>
                    </div>
                </div>

                <!-- OSCE Scoring -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-star"></i>
                            OSCE Scoring
                        </h3>
                    </div>
                    <div class="config-item">
                        <label for="scoreDropdown">
                            <i class="fas fa-chart-line"></i> Total Score
                        </label>
                        <select id="scoreDropdown">
                            <option value="">Select Total Score</option>
                            <?php for ($i = 5; $i <= 100; $i += 5): ?>
                                <option value="<?= $i ?>"><?= $i ?> Marks</option>
                            <?php endfor; ?>
                        </select>
                        <ul id="scoreList" class="selected-list"></ul>
                    </div>
                </div>
            </div>

            <!-- Search & Select Procedures -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-magnifying-glass"></i>
                        Search & Select Procedures
                    </h3>
                    <span class="badge">
                        <i class="fas fa-database"></i> <?= count($tables) ?> Procedures
                    </span>
                </div>

                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchInput" placeholder="Search procedure name...">
                </div>

                <div class="card-header" style="margin-top:10px;">
                    <h4 class="card-title" style="font-size:1rem;">
                        <i class="fas fa-check-circle" style="color:#28a745;"></i>
                        Selected Procedures
                    </h4>
                    <button class="btn btn-danger btn-sm" onclick="clearAll()">
                        <i class="fas fa-trash"></i> Remove All
                    </button>
                </div>

                <ul id="selectedList" class="selected-list"></ul>
            </div>

            <!-- Procedures Table -->
            <div class="card">
                <div class="table-wrapper">
                    <table id="tableList">
                        <thead>
                            <tr>
                                <th style="width: 50px;">#</th>
                                <th style="width: 50px;">Select</th>
                                <th>Procedure Name</th>
                                <th style="width: 280px; text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($tables) > 0): ?>
                                <?php
                                $index = 1;
                                foreach ($tables as $table):
                                ?>
                                    <tr class="<?= in_array($table, $selectedTables) ? 'selected-row' : '' ?>">
                                        <td><?= $index++ ?></td>
                                        <td class="checkbox-container">
                                            <label class="custom-checkbox">
                                                <input type="checkbox" class="select-table"
                                                    <?= in_array($table, $selectedTables) ? 'checked' : '' ?>
                                                    data-original="<?= htmlspecialchars($table) ?>">
                                                <span class="checkmark"></span>
                                            </label>
                                        </td>
                                        <td>
                                            <div class="table-name-wrapper">
                                                <span class="table-name" data-original="<?= htmlspecialchars($table) ?>" onclick="toggleCheckbox(this)">
                                                    <?= htmlspecialchars(formatTableName($table)) ?>
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="btn-action btn-view"
                                                    onclick="viewProcedure('<?= htmlspecialchars($table, ENT_QUOTES) ?>')">
                                                    <i class="fas fa-eye"></i> View
                                                </button>
                                                <button class="btn-action btn-edit"
                                                    onclick="editProcedure('<?= htmlspecialchars($table, ENT_QUOTES) ?>')">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <button class="btn-action btn-delete-procedure"
                                                    onclick="confirmDelete('<?= htmlspecialchars($table, ENT_QUOTES) ?>')">
                                                    <i class="fas fa-trash"></i> Delete
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <!-- Black separator line between procedures -->
                                    <?php if ($index <= count($tables)): ?>
                                        <tr class="procedure-separator">
                                            <td colspan="4"></td>
                                        </tr>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="no-result">
                                        <i class="fas fa-inbox"></i>
                                        <p>No procedures found in the database.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div id="noResult" class="no-result" style="display:none;">
                    <i class="fas fa-search"></i>
                    <p>No procedures match your search criteria.</p>
                </div>
            </div>

        </div>
    </main>

    <!-- Floating Create Checklist Button -->
    <a href="new_procedure.php" class="floating-btn">
        <i class="fas fa-plus"></i> Create Checklist
    </a>

    <!-- ============================================================
         DELETE CONFIRMATION MODAL
         ============================================================ -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <button class="close" onclick="closeDeleteModal()">&times;</button>
            <h2><i class="fas fa-exclamation-triangle"></i> Delete Procedure</h2>
            <p>Are you sure you want to permanently delete <strong id="deleteTableName">procedure</strong>?<br>
                This action will remove all associated data and <strong>cannot be undone</strong>.</p>
            <div class="modal-actions">
                <button class="btn btn-back" onclick="closeDeleteModal()">
                    <i class="fas fa-times"></i> Cancel
                </button>
                <button class="btn btn-danger" onclick="deleteProcedure()">
                    <i class="fas fa-trash-alt"></i> Yes, Delete
                </button>
            </div>
        </div>
    </div>

    <!-- ============================================================
         FOOTER
         ============================================================ -->
    <footer class="footer">
        <div>
            <strong><i class="fas fa-network-wired" style="margin-right:8px;"></i> CAOSCE Network</strong>
            <span style="margin-left:18px;">© <?php echo date('Y'); ?> All rights reserved</span>
        </div>
        <div class="meta">
            <span><i class="fas fa-code"></i> v2.0</span>
            <span>|</span>
            <span><i class="fas fa-user-cog"></i> Admin Panel</span>
            <span>|</span>
        </div>
    </footer>

    <!-- ============================================================
         SCRIPTS
         ============================================================ -->
    <script>
        let deleteTableName = '';

        // ============================================================
        // TOGGLE CHECKBOX WHEN CLICKING PROCEDURE NAME
        // ============================================================
        function toggleCheckbox(element) {
            const tableName = element.getAttribute('data-original');
            const checkbox = document.querySelector(`.select-table[data-original="${tableName}"]`);
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                checkbox.dispatchEvent(new Event('change'));
            }
        }

        // ============================================================
        // VIEW / EDIT PROCEDURE
        // ============================================================
        function viewProcedure(tableName) {
            window.location.href = `view_procedure.php?table=${encodeURIComponent(tableName)}`;
        }

        function editProcedure(tableName) {
            window.location.href = `edit_procedure.php?table=${encodeURIComponent(tableName)}`;
        }

        // ============================================================
        // DELETE PROCEDURE
        // ============================================================
        function confirmDelete(tableName) {
            deleteTableName = tableName;
            const displayName = tableName.replace(/^PRO/, '').replace(/(?<!^)([A-Z])/g, ' $1').trim();
            document.getElementById('deleteTableName').textContent = displayName;
            document.getElementById('deleteModal').style.display = 'flex';
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').style.display = 'none';
            deleteTableName = '';
        }

        function deleteProcedure() {
            if (!deleteTableName) return;

            fetch('', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `action=delete_table&table_name=${encodeURIComponent(deleteTableName)}`
                })
                .then(response => response.json())
                .then(data => {
                    closeDeleteModal();
                    if (data.success) {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error deleting table: ' + error);
                });
        }

        // ============================================================
        // PROCEDURE SEARCH - FIXED TO SHOW MATCHING ROWS WITH SEPARATORS
        // ============================================================
        const searchInput = document.getElementById("searchInput");
        const tableList = document.getElementById("tableList");
        const noResult = document.getElementById("noResult");
        const selectedList = document.getElementById("selectedList");

        searchInput.addEventListener("keyup", function() {
            const filter = this.value.toLowerCase();
            const rows = tableList.getElementsByTagName("tr");
            let visibleCount = 0;
            let previousRowVisible = false;

            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                // Skip thead rows (header)
                if (row.parentNode.tagName === 'THEAD') {
                    row.style.display = '';
                    continue;
                }

                // Check if this is a separator row
                const isSeparator = row.classList.contains('procedure-separator');

                // For separator rows, show/hide based on the next data row
                if (isSeparator) {
                    // Check the next row (which should be a data row)
                    let nextRow = null;
                    let nextIndex = i + 1;
                    while (nextIndex < rows.length) {
                        const potentialRow = rows[nextIndex];
                        if (!potentialRow.classList.contains('procedure-separator') && potentialRow.parentNode.tagName !== 'THEAD') {
                            nextRow = potentialRow;
                            break;
                        }
                        nextIndex++;
                    }

                    // If there's a next row and it's visible, show this separator
                    if (nextRow && nextRow.style.display !== 'none') {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                    continue;
                }

                // For data rows (not header, not separator)
                const cell = row.getElementsByTagName("td")[2];
                if (cell) {
                    const txtValue = cell.textContent || cell.innerText;
                    if (txtValue.toLowerCase().includes(filter)) {
                        row.style.display = "";
                        visibleCount++;
                    } else {
                        row.style.display = "none";
                    }
                }
            }

            // Show/hide no result message
            noResult.style.display = visibleCount === 0 ? "block" : "none";
        });

        // ============================================================
        // CHECKBOX SELECTION
        // ============================================================
        document.querySelectorAll(".select-table").forEach(checkbox => {
            checkbox.addEventListener("change", function() {
                const tableName = this.getAttribute("data-original");
                const row = this.closest("tr");
                const action = this.checked ? "add" : "remove";

                if (this.checked) {
                    row.classList.add("selected-row");
                } else {
                    row.classList.remove("selected-row");
                }

                fetch("", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: `action=${action}&table_name=${encodeURIComponent(tableName)}`
                }).then(refreshSelectedList);
            });
        });

        // ============================================================
        // REFRESH SELECTED PROCEDURES
        // ============================================================
        function refreshSelectedList() {
            fetch("", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: "action=get_selected"
                })
                .then(res => res.json())
                .then(data => {
                    selectedList.innerHTML = "";
                    data.sort((a, b) => a.localeCompare(b));

                    if (data.length === 0) {
                        const emptyMsg = document.createElement("li");
                        emptyMsg.innerHTML = '<span class="empty-message">No procedures selected yet</span>';
                        selectedList.appendChild(emptyMsg);
                    } else {
                        data.forEach(name => {
                            let displayName = name
                                .replace(/^PRO/, '')
                                .replace(/(?<!^)([A-Z])/g, ' $1')
                                .trim();

                            const li = document.createElement("li");
                            const nameSpan = document.createElement("span");
                            nameSpan.textContent = displayName;
                            nameSpan.onclick = () => {
                                searchInput.value = displayName;
                                searchInput.dispatchEvent(new Event("keyup"));
                            };

                            const removeBtn = document.createElement("button");
                            removeBtn.innerHTML = "✖";
                            removeBtn.title = "Remove";
                            removeBtn.onclick = () => removeSelected(name);

                            li.appendChild(nameSpan);
                            li.appendChild(removeBtn);
                            selectedList.appendChild(li);
                        });
                    }

                    document.querySelectorAll(".select-table").forEach(chk => {
                        const row = chk.closest("tr");
                        if (data.includes(chk.getAttribute("data-original"))) {
                            chk.checked = true;
                            row.classList.add("selected-row");
                        } else {
                            chk.checked = false;
                            row.classList.remove("selected-row");
                        }
                    });
                });
        }

        // ============================================================
        // REMOVE SELECTED PROCEDURE
        // ============================================================
        function removeSelected(name) {
            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `action=remove&table_name=${encodeURIComponent(name)}`
            }).then(refreshSelectedList);
        }

        // ============================================================
        // CLEAR ALL PROCEDURES
        // ============================================================
        function clearAll() {
            if (confirm("Are you sure you want to remove all selected procedures?")) {
                fetch("", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: "action=clear_all"
                }).then(refreshSelectedList);
            }
        }

        refreshSelectedList();

        // ============================================================
        // EXAMINERS CONFIGURATION
        // ============================================================
        const examinerDropdown = document.getElementById("examinerDropdown");
        const examinerList = document.getElementById("examinerList");

        examinerDropdown.addEventListener("change", function() {
            const num = this.value;
            if (!num) return;

            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `exam_action=add&examiner_number=${encodeURIComponent(num)}`
            }).then(() => {
                examinerDropdown.value = "";
                refreshExaminers();
            });
        });

        function refreshExaminers() {
            fetch("", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: "exam_action=get"
                })
                .then(res => res.json())
                .then(data => {
                    examinerList.innerHTML = "";
                    if (data.length > 0) {
                        const num = data[0];
                        const li = document.createElement("li");
                        li.innerHTML = `
                        <span>Examiners: ${num}</span>
                        <button onclick="deleteExaminer(${num})">✖</button>
                    `;
                        examinerList.appendChild(li);
                    } else {
                        const emptyMsg = document.createElement("li");
                        emptyMsg.innerHTML = '<span class="empty-message">No examiners configured</span>';
                        examinerList.appendChild(emptyMsg);
                    }
                });
        }

        function deleteExaminer(num) {
            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `exam_action=remove&examiner_number=${encodeURIComponent(num)}`
            }).then(refreshExaminers);
        }

        refreshExaminers();

        // ============================================================
        // PROCEDURES PER EXAMINER
        // ============================================================
        const procedurePerExaminerDropdown = document.getElementById("procedurePerExaminerDropdown");
        const procedurePerExaminerList = document.getElementById("procedurePerExaminerList");

        procedurePerExaminerDropdown.addEventListener("change", function() {
            const number = this.value;
            if (!number) return;

            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `procedure_action=add&procedure_number=${encodeURIComponent(number)}`
            }).then(() => {
                procedurePerExaminerDropdown.value = "";
                refreshProceduresPerExaminer();
            });
        });

        function refreshProceduresPerExaminer() {
            fetch("", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: "procedure_action=get"
                })
                .then(res => res.json())
                .then(data => {
                    procedurePerExaminerList.innerHTML = "";
                    if (data.length > 0) {
                        const number = data[0];
                        const li = document.createElement("li");
                        const procedureText = number == 1 ? "Procedure" : "Procedures";
                        li.innerHTML = `
                        <span>${number} ${procedureText} Per Examiner</span>
                        <button onclick="deleteProceduresPerExaminer()" title="Remove">✖</button>
                    `;
                        procedurePerExaminerList.appendChild(li);
                    } else {
                        const emptyMsg = document.createElement("li");
                        emptyMsg.innerHTML = '<span class="empty-message">No procedures per examiner set</span>';
                        procedurePerExaminerList.appendChild(emptyMsg);
                    }
                });
        }

        function deleteProceduresPerExaminer() {
            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: "procedure_action=remove"
            }).then(refreshProceduresPerExaminer);
        }

        refreshProceduresPerExaminer();

        // ============================================================
        // OSCE TOTAL SCORE
        // ============================================================
        const scoreDropdown = document.getElementById("scoreDropdown");
        const scoreList = document.getElementById("scoreList");

        scoreDropdown.addEventListener("change", function() {
            const val = this.value;
            if (!val) return;

            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `score_action=add&total_score=${encodeURIComponent(val)}`
            }).then(() => {
                scoreDropdown.value = "";
                refreshScore();
            });
        });

        function refreshScore() {
            fetch("", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: "score_action=get"
                })
                .then(res => res.json())
                .then(data => {
                    scoreList.innerHTML = "";
                    if (data.length > 0) {
                        const val = data[0];
                        const li = document.createElement("li");
                        li.innerHTML = `
                        <span>Total Score: ${val}</span>
                        <button onclick="deleteScore()" title="Remove">✖</button>
                    `;
                        scoreList.appendChild(li);
                    } else {
                        const emptyMsg = document.createElement("li");
                        emptyMsg.innerHTML = '<span class="empty-message">No score set</span>';
                        scoreList.appendChild(emptyMsg);
                    }
                });
        }

        function deleteScore() {
            fetch("", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: "score_action=remove"
            }).then(refreshScore);
        }

        refreshScore();

        // ============================================================
        // TABLE ROW ANIMATION
        // ============================================================
        document.addEventListener('DOMContentLoaded', function() {
            const rows = document.querySelectorAll('tbody tr');
            rows.forEach((row, index) => {
                row.style.opacity = '0';
                row.style.transform = 'translateY(8px)';
                setTimeout(() => {
                    row.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                    row.style.opacity = '1';
                    row.style.transform = 'translateY(0)';
                }, index * 40);
            });
        });

        // Close modal on outside click
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        // Close modal on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                document.querySelectorAll('.modal').forEach(modal => {
                    modal.style.display = 'none';
                });
            }
        });
    </script>

</body>

</html>