<?php
session_start();
error_reporting(E_ALL & ~E_DEPRECATED);

// Connect to the SQLite database
$db = new PDO('sqlite:database.db');

// Check for connection errors
if (!$db) {
    die("Connection failed: " . $db->errorInfo()[2]);
}

// Check if a delete request was made
if (isset($_POST['delete_all'])) {
    $input_password = $_POST['password'];

    // Validate password
    if ($input_password === '123456789') {
        // Prepare and execute the delete query
        $db->exec("DELETE FROM result");
        echo "<p style='color: green;'>Results Table deleted!</p>";
    } else {
        echo "<p style='color: red;'>Incorrect password! </p>";
    }
}

// Check if an export request was made
if (isset($_POST['export_csv'])) {
    // Set headers for the CSV download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="results.csv"');

    // Open output stream for writing
    $output = fopen('php://output', 'w');

    // Add the column headers to the CSV
    fputcsv($output, ['User ID', 'Name', 'ST1', 'ST2', 'ST3', 'ST4', 'ST5', 'ST6', 'ST7', 'ST8', 'Total']);

    // Query to retrieve data from the result table
    $query = 'SELECT user_id, name, "1", "2", "3", "4", "5", "6", "7", "8" FROM result ORDER BY CAST(user_id AS INTEGER) ASC';
    $result = $db->query($query);

    // Fetch and write each row of the result to the CSV
    foreach ($result as $row) {
        // Calculate the total score by summing columns 1 to 8
        $total = $row['1'] + $row['2'] + $row['3'] + $row['4'] + $row['5'] + $row['6'] + $row['7'] + $row['8'];
        fputcsv($output, [
            $row['user_id'],
            strtoupper($row['name']),
            $row['1'],
            $row['2'],
            $row['3'],
            $row['4'],
            $row['5'],
            $row['6'],
            $row['7'],
            $row['8'],
            $total
        ]);
    }

    fclose($output);
    exit; // Stop further execution
}

// Query to retrieve data from the result table, sorting by user_id in ascending order
$query = 'SELECT user_id, name, "1", "2", "3", "4", "5", "6", "7", "8" FROM result ORDER BY CAST(user_id AS INTEGER) ASC';
$result = $db->query($query);

// Check if the query was successful
if (!$result) {
    die("Query failed: " . $db->errorInfo()[2]);
}

// Check if an upload request was made
if (isset($_POST['upload_results'])) {
    // Get all data from local database with properly quoted column names
    $local_data = $db->query('SELECT user_id, name, "1", "2", "3", "4", "5", "6", "7", "8" FROM result');
    $results = [];

    foreach ($local_data as $row) {
        $results[] = [
            'user_id' => $row['user_id'],
            'name' => $row['name'],
            '1' => $row['1'],
            '2' => $row['2'],
            '3' => $row['3'],
            '4' => $row['4'],
            '5' => $row['5'],
            '6' => $row['6'],
            '7' => $row['7'],
            '8' => $row['8']
        ];
    }

    // Encode data as JSON
    $json_data = json_encode($results);

    // Initialize cURL session for uploading result
    $ch = curl_init('https://cbt.net.ng/nduosce/upload.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ['data' => $json_data]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // Execute the request
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code === 200) {
        echo "<p style='color: green;'>$response</p>";
    } else {
        echo "<p style='color: red;'>Upload failed: $response</p>";
    }
}

// Check if a download request was made
if (isset($_POST['download_data'])) {
    $input_password = $_POST['password'];

    // Validate password
    if ($input_password === '123456789') {
        try {
            // Remote database URL
            $remote_url = 'https://cbt.net.ng/nducaosce/result.php';

            // Fetch data from remote server
            $remote_data = file_get_contents($remote_url);

            if ($remote_data === false) {
                throw new Exception("Failed to fetch data from remote server");
            }

            // Parse the HTML table to extract data
            $dom = new DOMDocument();
            @$dom->loadHTML($remote_data);
            $tables = $dom->getElementsByTagName('table');

            if ($tables->length === 0) {
                throw new Exception("No table found in remote data");
            }

            $table = $tables->item(0);
            $rows = $table->getElementsByTagName('tr');

            // Clear existing data
            $db->exec("DELETE FROM result");

            // Prepare insert statement
            $stmt = $db->prepare("INSERT INTO result (user_id, name, \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $imported_count = 0;

            // Skip header row (index 0)
            for ($i = 1; $i < $rows->length; $i++) {
                $cells = $rows->item($i)->getElementsByTagName('td');

                if ($cells->length >= 12) {
                    $user_id = trim($cells->item(1)->textContent);
                    $name = trim($cells->item(2)->textContent);

                    // Extract scores from columns 3 to 10
                    $scores = [];
                    for ($j = 3; $j <= 10; $j++) {
                        $score = trim($cells->item($j)->textContent);
                        $scores[] = is_numeric($score) ? floatval($score) : 0;
                    }

                    // Insert into local database
                    $stmt->execute([$user_id, $name, $scores[0], $scores[1], $scores[2], $scores[3], $scores[4], $scores[5], $scores[6], $scores[7]]);
                    $imported_count++;
                }
            }

            // ✅ Redirect to success page after import
            header("Location: successful_download.php");
            exit;
        } catch (Exception $e) {
            echo "<p style='color: red;'>Error downloading data: " . $e->getMessage() . "</p>";
        }
    } else {
        echo "<p style='color: red;'>Incorrect password!</p>";
    }
}

// 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', 'Roboto', 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;
            background: #ffffff;
            padding: 30px 35px 40px;
            border-radius: 24px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
            border: 1px solid #eef4fa;
        }

        /* ----- HEADER ----- */
        .page-header {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
            gap: 15px;
        }

        .page-header .title-group {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header .title-group h1 {
            font-size: 28px;
            font-weight: 700;
            color: #10233f;
            margin: 0;
        }

        .page-header .title-group .icon-large {
            font-size: 32px;
        }

        .page-header .subtitle {
            font-size: 13px;
            color: #6b7a8f;
            margin-top: 2px;
        }

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

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

        .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-primary {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
        }

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

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

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

        .btn-outline {
            background: transparent;
            border: 2px solid #d9e2eb;
            color: #4f6580;
        }

        .btn-outline:hover {
            background: #f0f4fb;
            border-color: #b0c4d8;
        }

        .btn-info-icon {
            background: transparent;
            border: 2px solid #d9e2eb;
            border-radius: 50%;
            width: 38px;
            height: 38px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: #6b7a8f;
            cursor: pointer;
            transition: 0.3s;
        }

        .btn-info-icon:hover {
            background: #f0f4fb;
            border-color: #b0c4d8;
        }

        /* ----- WARNING BANNER ----- */
        .warning-banner {
            background: #fff3cd;
            border-left: 5px solid #ffc107;
            padding: 12px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .warning-banner i {
            color: #856404;
            font-size: 20px;
        }

        .warning-banner span {
            color: #856404;
            font-size: 14px;
        }

        .warning-banner strong {
            color: #856404;
        }

        /* ----- TOOLBAR ----- */
        .toolbar {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            gap: 15px;
            margin-bottom: 20px;
            padding: 12px 16px;
            background: #f8fafc;
            border-radius: 14px;
            border: 1px solid #eef4fa;
        }

        .toolbar .left {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .toolbar .left label {
            font-weight: 600;
            font-size: 14px;
            color: #4f6580;
        }

        .toolbar .left select {
            padding: 8px 14px;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            font-size: 14px;
            background: white;
            transition: 0.3s;
        }

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

        .toolbar .right {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

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

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

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

        td {
            padding: 12px 16px;
            border-bottom: 1px solid #eef4fa;
        }

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

        tr:hover td {
            background: #f8fafc;
        }

        .total-cell {
            font-weight: 700;
            color: #1a6cf0;
        }

        .text-muted {
            color: #6b7a8f;
        }

        /* ----- MODALS ----- */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            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: 400px;
            border-radius: 20px;
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.2);
            animation: modalIn 0.3s ease;
        }

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

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

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

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

        .modal-content h2 {
            font-size: 22px;
            margin-bottom: 16px;
            color: #10233f;
            text-align: center;
        }

        .modal-content h2 i {
            margin-right: 8px;
        }

        .modal-content input[type="password"] {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 15px;
            margin-bottom: 16px;
            transition: 0.3s;
        }

        .modal-content input[type="password"]:focus {
            outline: none;
            border-color: #1a6cf0;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
        }

        .modal-content .btn {
            width: 100%;
            justify-content: center;
        }

        /* ----- NOTIFICATION MESSAGES ----- */
        .notification {
            padding: 12px 20px;
            border-radius: 12px;
            margin-bottom: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .notification-success {
            background: #d4edda;
            color: #155724;
            border-left: 5px solid #28a745;
        }

        .notification-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 5px solid #dc3545;
        }

        .notification i {
            font-size: 20px;
        }

        /* ----- 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;
            }

            .container {
                padding: 20px 16px;
            }

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

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
                justify-content: center;
            }

            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }

            .toolbar .left {
                justify-content: center;
            }

            .toolbar .right {
                justify-content: center;
            }
        }

        @media (max-width: 600px) {
            .container {
                padding: 14px 12px;
            }

            .page-header .title-group h1 {
                font-size: 22px;
            }

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

            .header-actions .btn {
                font-size: 12px;
                padding: 7px 14px;
            }

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

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

            .warning-banner {
                font-size: 13px;
                padding: 10px 14px;
            }
        }

        @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">

            <!-- Header -->
            <div class="page-header">
                <div class="title-group">

                    <div>
                        <h1>OSCE Results Table</h1>
                        <div class="subtitle">View and manage all student examination results</div>
                    </div>
                </div>
                <div class="header-actions">
                    <button class="btn btn-info-icon" onclick="alert('🔐 Delete Password: 123456789')" title="Show password">
                        <i class="fas fa-info"></i>
                    </button>
                    <button class="btn btn-primary" onclick="window.location.href='admin.php'">
                        <i class="fas fa-arrow-left"></i> Go Back
                    </button>
                </div>
            </div>

            <!-- Warning Banner -->
            <div class="warning-banner">
                <i class="fas fa-exclamation-triangle"></i>
                <span><strong>Warning:</strong> Deleted result table is <strong>permanently removed</strong>. Please <strong>export</strong> results before deletion!</span>
            </div>

            <!-- Toolbar -->
            <div class="toolbar">
                <div class="left">
                    <label for="percentage"><i class="fas fa-percent"></i> Adjust Scores:</label>
                    <select id="percentage" onchange="updateScores()">
                        <option value="100">100%</option>
                        <option value="90">90%</option>
                        <option value="80">80%</option>
                        <option value="70">70%</option>
                        <option value="60">60%</option>
                        <option value="50">50%</option>
                        <option value="40">40%</option>
                        <option value="30">30%</option>
                        <option value="20">20%</option>
                        <option value="10">10%</option>
                    </select>
                    <span class="text-muted" style="font-size:13px;">(adjusts all scores)</span>
                </div>
                <div class="right">
                    <button class="btn btn-success" onclick="exportTableToExcel()">
                        <i class="fas fa-file-excel"></i> Export Excel
                    </button>
                    <button class="btn btn-danger" onclick="document.getElementById('passwordModal').style.display='flex'">
                        <i class="fas fa-trash-alt"></i> Delete Results
                    </button>
                </div>
            </div>

            <!-- Table -->
            <div class="table-wrapper">
                <table id="resultTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Matric No.</th>
                            <th>Name</th>
                            <th>Exm 1</th>
                            <th>Exm 2</th>
                            <th>Exm 3</th>
                            <th>Exm 4</th>
                            <th>Exm 5</th>
                            <th>Exm 6</th>
                            <th>Exm 7</th>
                            <th>Exm 8</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $sn = 1;
                        $has_rows = false;
                        foreach ($result as $row) {
                            $has_rows = true;
                            $total = $row['1'] + $row['2'] + $row['3'] + $row['4'] + $row['5'] + $row['6'] + $row['7'] + $row['8'];
                            echo '<tr>';
                            echo '<td>' . $sn++ . '</td>';
                            echo '<td><strong>' . htmlspecialchars($row['user_id']) . '</strong></td>';
                            echo '<td>' . htmlspecialchars(strtoupper($row['name'])) . '</td>';
                            echo '<td>' . htmlspecialchars($row['1']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['2']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['3']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['4']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['5']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['6']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['7']) . '</td>';
                            echo '<td>' . htmlspecialchars($row['8']) . '</td>';
                            echo '<td class="total-cell">' . $total . '</td>';
                            echo '</tr>';
                        }
                        if (!$has_rows) {
                            echo '<tr><td colspan="12" style="text-align:center; padding:40px; color:#6b7a8f;">
                                    <i class="fas fa-inbox" style="font-size:32px; display:block; margin-bottom:10px;"></i>
                                    No results found.
                                </td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>

        </div>
    </main>

    <!-- ============================================================
         DELETE MODAL
         ============================================================ -->
    <div id="passwordModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="document.getElementById('passwordModal').style.display='none'">&times;</span>
            <h2><i class="fas fa-trash-alt" style="color:#dc3545;"></i> Confirm Deletion</h2>
            <form method="post" action="">
                <input type="password" name="password" placeholder="Enter password" required>
                <input type="hidden" name="delete_all" value="1">
                <button type="submit" class="btn btn-danger">
                    <i class="fas fa-exclamation-triangle"></i> Delete All Results
                </button>
            </form>
        </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>
        // Close modal on outside click
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        // Store original scores for adjustment
        let originalScores = [];

        function initializeOriginalScores() {
            originalScores = [];
            const rows = document.querySelectorAll('#resultTable tbody tr');
            rows.forEach((row) => {
                const cells = row.querySelectorAll('td');
                if (cells.length >= 12) {
                    const rowScores = [];
                    for (let i = 3; i <= 10; i++) {
                        let score = parseFloat(cells[i].innerText);
                        rowScores.push(isNaN(score) ? 0 : score);
                    }
                    originalScores.push(rowScores);
                }
            });
        }

        function updateScores() {
            const percentage = document.getElementById('percentage').value;
            const rows = document.querySelectorAll('#resultTable tbody tr');

            rows.forEach((row, index) => {
                const cells = row.querySelectorAll('td');
                if (cells.length >= 12 && originalScores[index]) {
                    let total = 0;
                    for (let i = 3; i <= 10; i++) {
                        const adjustedScore = originalScores[index][i - 3] * (percentage / 100);
                        cells[i].innerText = adjustedScore.toFixed(2);
                        total += adjustedScore;
                    }
                    cells[11].innerText = total.toFixed(2);
                }
            });
        }

        function exportTableToExcel() {
            let table = document.getElementById("resultTable");
            let rows = table.getElementsByTagName("tr");
            let csvContent = "data:text/csv;charset=utf-8,";

            // Headers (skip S/N)
            let headers = ['Matric No', 'Name', 'Exm 1', 'Exm 2', 'Exm 3', 'Exm 4', 'Exm 5', 'Exm 6', 'Exm 7', 'Exm 8', 'Total'];
            csvContent += headers.join(",") + "\n";

            for (let i = 1; i < rows.length; i++) {
                let cols = rows[i].getElementsByTagName("td");
                if (cols.length === 0) continue;
                let rowData = [];
                for (let j = 1; j < cols.length; j++) {
                    rowData.push(cols[j].innerText);
                }
                csvContent += rowData.join(",") + "\n";
            }

            let encodedUri = encodeURI(csvContent);
            let link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "CAOSCE_results.csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Initialize on load
        document.addEventListener('DOMContentLoaded', function() {
            initializeOriginalScores();
        });
    </script>

</body>

</html>