<?php
session_start();

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

// ============================================================
// CREATE LEVELS TRACKING TABLE
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS levels_tracking (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        table_name TEXT UNIQUE,
        display_name TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");

// ============================================================
// GENERATE TABLE NAME FROM DISPLAY NAME
// ============================================================
function generateTableName($display_name)
{
    $name = strtolower(trim($display_name));
    $name = preg_replace('/[^a-z0-9_]/', '_', $name);
    $name = preg_replace('/_+/', '_', $name);
    return 'level_' . $name;
}

// ============================================================
// RESIZE IMAGE FUNCTION
// ============================================================
function resizeImage($imagePath)
{
    $imageInfo = getimagesize($imagePath);
    $mimeType = $imageInfo['mime'];

    switch ($mimeType) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($imagePath);
            break;
        case 'image/png':
            $image = imagecreatefrompng($imagePath);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($imagePath);
            break;
        case 'image/webp':
            $image = imagecreatefromwebp($imagePath);
            break;
        default:
            throw new Exception("⚠️ Unsupported image type: $mimeType");
    }

    $originalWidth = imagesx($image);
    $originalHeight = imagesy($image);

    $resizedImage = imagecreatetruecolor(200, 200);

    if ($mimeType == 'image/png' || $mimeType == 'image/gif') {
        imagecolortransparent($resizedImage, imagecolorallocatealpha($resizedImage, 0, 0, 0, 127));
        imagealphablending($resizedImage, false);
        imagesavealpha($resizedImage, true);
    }

    $ratio = min(200 / $originalWidth, 200 / $originalHeight);
    $newWidth = (int)($originalWidth * $ratio);
    $newHeight = (int)($originalHeight * $ratio);

    $x = (int)((200 - $newWidth) / 2);
    $y = (int)((200 - $newHeight) / 2);

    imagecopyresampled($resizedImage, $image, $x, $y, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

    ob_start();
    switch ($mimeType) {
        case 'image/jpeg':
            imagejpeg($resizedImage, null, 90);
            break;
        case 'image/png':
            imagepng($resizedImage, null, 9);
            break;
        case 'image/gif':
            imagegif($resizedImage);
            break;
        case 'image/webp':
            imagewebp($resizedImage, null, 90);
            break;
    }
    $resizedImageData = ob_get_clean();

    imagedestroy($image);
    imagedestroy($resizedImage);

    return $resizedImageData;
}

// ============================================================
// HANDLE CREATE LEVEL
// ============================================================
$message = '';
$message_type = '';

if (isset($_POST['create_level'])) {
    $display_name = trim($_POST['display_name'] ?? '');

    if (empty($display_name)) {
        $message = '⚠️ Please enter a display name.';
        $message_type = 'error';
    } else {
        $table_name = generateTableName($display_name);

        $check = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='$table_name'")->fetch();

        if ($check) {
            $message = '⚠️ A level with this name already exists.';
            $message_type = 'error';
        } else {
            $db->exec("
                CREATE TABLE '$table_name' (
                    user_id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    picture BLOB,
                    sex TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ");

            $stmt = $db->prepare("INSERT INTO levels_tracking (table_name, display_name) VALUES (?, ?)");
            $stmt->execute([$table_name, $display_name]);

            $message = "Level '$display_name' created successfully!";
            $message_type = 'success';
        }
    }
}

// ============================================================
// HANDLE DELETE LEVEL
// ============================================================
if (isset($_POST['delete_level'])) {
    $table_name = $_POST['table_name'] ?? '';
    $display_name = $_POST['display_name'] ?? '';

    if ($table_name === 'students') {
        $message = "❌ The OSCE Candidates (students table) cannot be deleted.";
        $message_type = 'error';
    } elseif (!empty($table_name)) {
        try {
            $db->exec("DROP TABLE IF EXISTS '$table_name'");
            $stmt = $db->prepare("DELETE FROM levels_tracking WHERE table_name = ?");
            $stmt->execute([$table_name]);

            $message = "Level '$display_name' deleted successfully!";
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = "❌ Error deleting level: " . $e->getMessage();
            $message_type = 'error';
        }
    }
}

// ============================================================
// HANDLE DELETE ALL STUDENTS FROM OSCE CANDIDATES
// ============================================================
if (isset($_POST['delete_all_students'])) {
    if (isset($_POST['confirm_delete_all']) && $_POST['confirm_delete_all'] === 'yes') {
        try {
            $db->exec("DELETE FROM students");
            $message = "All OSCE Candidates data has been deleted successfully!";
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = "❌ Error deleting students: " . $e->getMessage();
            $message_type = 'error';
        }
    } else {
        $message = "⚠️ Please confirm deletion by checking the confirmation box.";
        $message_type = 'error';
    }
}

// ============================================================
// HANDLE DELETE STUDENT
// ============================================================
if (isset($_POST['delete_student'])) {
    $table_name = $_POST['table_name'] ?? '';
    $user_id = $_POST['user_id'] ?? '';

    if (!empty($table_name) && !empty($user_id)) {
        try {
            $stmt = $db->prepare("DELETE FROM '$table_name' WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $message = "🗑️ Student deleted successfully!";
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = "❌ Error deleting student: " . $e->getMessage();
            $message_type = 'error';
        }
    }
}

// ============================================================
// HANDLE MOVE DATA (COPY to OSCE Candidates, MOVE to others)
// ============================================================
if (isset($_POST['move_data'])) {
    $source_table = $_POST['source_table'] ?? '';
    $dest_table = $_POST['dest_table'] ?? '';
    $move_type = $_POST['move_type'] ?? 'all';
    $selected_ids = $_POST['selected_ids'] ?? [];

    // Prevent moving FROM the students table
    if ($source_table === 'students') {
        $message = "❌ Cannot move/copy data out of OSCE Candidates table.";
        $message_type = 'error';
        goto end_move;
    }

    $is_copy_to_exam = ($dest_table === 'students');

    if (empty($source_table) || empty($dest_table)) {
        $message = '⚠️ Please select source and destination tables.';
        $message_type = 'error';
    } elseif ($source_table === $dest_table) {
        $message = '⚠️ Source and destination tables cannot be the same.';
        $message_type = 'error';
    } else {
        try {
            $check = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='$source_table'")->fetch();
            if (!$check) {
                $message = '❌ Source table does not exist.';
                $message_type = 'error';
                goto end_move;
            }

            $check = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='$dest_table'")->fetch();
            if (!$check) {
                $message = '❌ Destination table does not exist.';
                $message_type = 'error';
                goto end_move;
            }

            if ($move_type === 'all') {
                $db->exec("
                    INSERT OR REPLACE INTO '$dest_table' (user_id, name, picture, sex, created_at)
                    SELECT user_id, name, picture, sex, created_at FROM '$source_table'
                ");

                if (!$is_copy_to_exam) {
                    $db->exec("DELETE FROM '$source_table'");
                    $message = "All data moved successfully!";
                } else {
                    $message = "All data copied to OSCE Candidates successfully! (Source data preserved)";
                }
                $message_type = 'success';
            } elseif ($move_type === 'selected' && !empty($selected_ids)) {
                $placeholders = implode(',', array_fill(0, count($selected_ids), '?'));

                $stmt = $db->prepare("
                    INSERT OR REPLACE INTO '$dest_table' (user_id, name, picture, sex, created_at)
                    SELECT user_id, name, picture, sex, created_at FROM '$source_table'
                    WHERE user_id IN ($placeholders)
                ");
                $stmt->execute($selected_ids);

                if (!$is_copy_to_exam) {
                    $stmt = $db->prepare("DELETE FROM '$source_table' WHERE user_id IN ($placeholders)");
                    $stmt->execute($selected_ids);
                    $message = "Selected data moved successfully! " . count($selected_ids) . " records moved.";
                } else {
                    $message = "Selected data copied to OSCE Candidates successfully! " . count($selected_ids) . " records copied. (Source data preserved)";
                }
                $message_type = 'success';
            } elseif ($move_type === 'single' && isset($_POST['single_id'])) {
                $single_id = $_POST['single_id'];

                $stmt = $db->prepare("
                    INSERT OR REPLACE INTO '$dest_table' (user_id, name, picture, sex, created_at)
                    SELECT user_id, name, picture, sex, created_at FROM '$source_table'
                    WHERE user_id = ?
                ");
                $stmt->execute([$single_id]);

                if (!$is_copy_to_exam) {
                    $stmt = $db->prepare("DELETE FROM '$source_table' WHERE user_id = ?");
                    $stmt->execute([$single_id]);
                    $message = "Record moved successfully!";
                } else {
                    $message = "Record copied to OSCE Candidates successfully! (Source data preserved)";
                }
                $message_type = 'success';
            } else {
                $message = '⚠️ No data selected to move.';
                $message_type = 'error';
            }

            end_move:
        } catch (PDOException $e) {
            $message = "❌ Error moving data: " . $e->getMessage();
            $message_type = 'error';
        }
    }
}

// ============================================================
// FETCH ALL LEVELS (including the main students table)
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS students (
        user_id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        picture BLOB,
        sex TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
");

$check = $db->query("SELECT COUNT(*) FROM levels_tracking WHERE table_name = 'students'")->fetchColumn();
if ($check == 0) {
    $db->exec("INSERT INTO levels_tracking (table_name, display_name) VALUES ('students', 'OSCE Candidates')");
}

$levels = $db->query("SELECT * FROM levels_tracking ORDER BY 
    CASE WHEN table_name = 'students' THEN 0 ELSE 1 END, 
    created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

$level_data = [];
foreach ($levels as $level) {
    try {
        $stmt = $db->query("SELECT * FROM '{$level['table_name']}' ORDER BY created_at DESC");
        $level_data[$level['table_name']] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $level_data[$level['table_name']] = [];
    }
}

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

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* ... (all existing styles remain the same) ... */
        * {
            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;
        }

        .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 {
            flex: 1;
            padding: 30px 5vw;
        }

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

        .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;
        }

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

        .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-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-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-warning {
            background: #f39c12;
            color: white;
        }

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

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

        .btn-xs {
            padding: 4px 10px;
            font-size: 11px;
            border-radius: 16px;
        }

        .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;
        }

        .badge-exam {
            background: #28a745;
        }

        .badge-copy {
            background: #6c5ce7;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 6px;
            color: #10233f;
            font-size: 14px;
        }

        .form-group label i {
            margin-right: 6px;
            color: #1a6cf0;
        }

        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 15px;
            transition: 0.3s;
            background: white;
        }

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

        .form-control[disabled] {
            background: #f0f4fb;
            cursor: not-allowed;
        }

        .form-hint {
            font-size: 12px;
            color: #6b7a8f;
            margin-top: 4px;
        }

        .level-item {
            border: 1px solid #eef4fa;
            border-radius: 12px;
            margin-bottom: 12px;
            overflow: hidden;
            transition: 0.3s;
        }

        .level-item:hover {
            border-color: #d9e2eb;
        }

        .level-item.exam-page {
            border-color: #28a745;
        }

        .level-item.exam-page .level-header {
            background: #e8f5e9;
        }

        .level-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 14px 18px;
            background: #f8fafc;
            cursor: pointer;
            transition: 0.2s;
        }

        .level-header:hover {
            background: #f0f4fb;
        }

        .level-header .level-info {
            display: flex;
            align-items: center;
            gap: 14px;
            flex-wrap: wrap;
        }

        .level-header .level-info .level-name {
            font-weight: 600;
            font-size: 16px;
            color: #10233f;
        }

        .level-header .level-info .level-count {
            font-size: 13px;
            color: #6b7a8f;
            background: #e9ecef;
            padding: 2px 12px;
            border-radius: 20px;
        }

        .level-header .level-actions {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .level-header .level-actions .toggle-icon {
            transition: transform 0.3s ease;
            color: #6b7a8f;
            font-size: 16px;
        }

        .level-header .level-actions .toggle-icon.open {
            transform: rotate(180deg);
        }

        .level-body {
            display: none;
            padding: 18px;
            background: white;
            border-top: 1px solid #eef4fa;
        }

        .level-body.open {
            display: block;
        }

        .level-body .table-wrapper {
            overflow-x: auto;
            border-radius: 10px;
            border: 1px solid #eef4fa;
            margin-bottom: 16px;
        }

        .level-body table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        .level-body table th {
            background: #f8fafc;
            color: #10233f;
            font-weight: 600;
            padding: 10px 14px;
            text-align: left;
            border-bottom: 2px solid #e2eaf2;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .level-body table td {
            padding: 9px 14px;
            border-bottom: 1px solid #eef4fa;
            vertical-align: middle;
        }

        .level-body table tr:last-child td {
            border-bottom: none;
        }

        .level-body table tr:hover td {
            background: #f8fafc;
        }

        .level-body table td img {
            border-radius: 6px;
            width: 40px;
            height: 40px;
            object-fit: cover;
            border: 2px solid #eef4fa;
        }

        .level-body .actions-cell {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        .level-body .actions-cell .btn {
            padding: 4px 10px;
            font-size: 11px;
            border-radius: 16px;
        }

        .level-body .move-section {
            background: #f8fafc;
            border-radius: 10px;
            padding: 16px;
            border: 1px solid #eef4fa;
        }

        .level-body .move-section .move-row {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        .level-body .move-section select {
            padding: 8px 14px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            min-width: 200px;
        }

        .level-body .move-section select:focus {
            outline: none;
            border-color: #1a6cf0;
        }

        .level-body .move-section .btn {
            padding: 8px 18px;
            font-size: 13px;
        }

        .checkbox-cell {
            text-align: center;
        }

        .checkbox-cell input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: #1a6cf0;
        }

        .empty-state {
            text-align: center;
            padding: 30px 20px;
            color: #6b7a8f;
        }

        .empty-state i {
            font-size: 32px;
            color: #d9e2eb;
            display: block;
            margin-bottom: 8px;
        }

        .empty-levels {
            text-align: center;
            padding: 40px 20px;
            color: #6b7a8f;
        }

        .empty-levels i {
            font-size: 48px;
            color: #d9e2eb;
            display: block;
            margin-bottom: 12px;
        }

        .notification {
            padding: 14px 20px;
            border-radius: 12px;
            font-weight: 500;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: slideDown 0.4s ease;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }

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

        .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;
        }

        .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: 480px;
            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) 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: 16px;
            color: #10233f;
            text-align: center;
        }

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

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

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

        .photo-preview {
            text-align: center;
            margin: 10px 0 16px 0;
        }

        .photo-preview img {
            width: 100px;
            height: 100px;
            border-radius: 12px;
            object-fit: cover;
            border: 3px solid #eef4fa;
        }

        .photo-preview .no-photo {
            color: #999;
            font-size: 13px;
            padding: 10px;
            background: #f8fafc;
            border-radius: 8px;
        }

        .checkbox-inline {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 4px;
        }

        .checkbox-inline input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #1a6cf0;
            cursor: pointer;
        }

        .checkbox-inline label {
            font-weight: 400;
            font-size: 13px;
            color: #4f6580;
            cursor: pointer;
        }

        .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;
        }

        @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;
            }

            .header-actions {
                width: 100%;
            }

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

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

            .level-header .level-actions {
                width: 100%;
                flex-wrap: wrap;
            }

            .level-body .move-section .move-row {
                flex-direction: column;
                align-items: stretch;
            }

            .level-body .move-section select {
                width: 100%;
            }

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

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

            .card {
                padding: 18px 16px;
            }

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

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

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

            .level-header .level-info {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
            }

            .level-body table {
                font-size: 12px;
            }

            .level-body table th,
            .level-body table td {
                padding: 6px 10px;
            }

            .level-body table td img {
                width: 30px;
                height: 30px;
            }

            .level-body .actions-cell {
                flex-direction: column;
            }

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

        @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>
        <div class="container">

            <div class="page-header">
                <div>
                    <h1>
                        <i class="fas fa-layer-group"></i>
                        Levels Manager
                    </h1>
                    <div class="subtitle">
                        <i class="fas fa-graduation-cap"></i>
                        Create, view, and manage student level tables
                    </div>
                </div>
                <div class="header-actions">
                    <a href="admin.php" class="btn btn-back">
                        <i class="fas fa-arrow-left"></i> Go Back
                    </a>
                </div>
            </div>

            <?php if ($message): ?>
                <div class="notification <?= $message_type === 'success' ? 'notification-success' : 'notification-error' ?>" id="notify">
                    <i class="fas <?= $message_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
                    <span><?= htmlspecialchars($message) ?></span>
                </div>
                <script>
                    setTimeout(() => {
                        const n = document.getElementById('notify');
                        if (n) n.style.display = 'none';
                    }, 5000);
                </script>
            <?php endif; ?>

            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">
                        <i class="fas fa-plus-circle"></i>
                        Create New Level
                    </h2>
                 
                </div>
                <form method="POST" action="">
                    <div class="form-group">
                        <label for="display_name"><i class="fas fa-tag"></i> Level Name</label>
                        <input type="text" name="display_name" id="display_name" class="form-control"
                            placeholder="e.g., 200 Level First Semester 2023 Set" required>
                        <div class="form-hint">This will be used to create the table. Special characters will be replaced with underscores.</div>
                    </div>
                    <button type="submit" name="create_level" class="btn btn-success" style="width:100%; justify-content:center; padding:14px;">
                        <i class="fas fa-plus-circle"></i> Create Level
                    </button>
                </form>
            </div>

            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">
                        <i class="fas fa-list-ul"></i>
                        Existing Levels
                    </h2>
                    <span class="badge"><?= count($levels) ?> Levels</span>
                </div>

                <?php if (count($levels) > 0): ?>
                    <?php foreach ($levels as $level):
                        $table_name = $level['table_name'];
                        $records = $level_data[$table_name] ?? [];
                        $record_count = count($records);
                        $is_exam_page = ($table_name === 'students');
                    ?>
                        <div class="level-item <?= $is_exam_page ? 'exam-page' : '' ?>">
                            <div class="level-header" onclick="toggleLevel('<?= $table_name ?>')">
                                <div class="level-info">
                                    <span class="level-name">
                                        <i class="fas <?= $is_exam_page ? 'fa-file-alt' : 'fa-graduation-cap' ?>" style="color:<?= $is_exam_page ? '#28a745' : '#1a6cf0' ?>;"></i>
                                        <?= htmlspecialchars($level['display_name']) ?>
                                        <?php if ($is_exam_page): ?>
                                            <span style="font-size:11px; background:#28a745; color:white; padding:2px 10px; border-radius:12px; margin-left:6px;">Destination</span>
                                        <?php endif; ?>
                                    </span>
                                    <span class="level-count">
                                        <i class="fas fa-users"></i>
                                        <?= $record_count ?> Students
                                    </span>
                                    <?php if ($is_exam_page): ?>
                                        <span class="badge badge-exam" style="font-size:10px;">
                                            <i class="fas fa-arrow-down"></i> Receive Only
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div class="level-actions">
                                    <?php if (!$is_exam_page): ?>
                                        <button class="btn btn-danger btn-sm" onclick="event.stopPropagation(); confirmDelete('<?= htmlspecialchars($table_name) ?>', '<?= htmlspecialchars($level['display_name']) ?>')">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    <?php endif; ?>
                                    <span class="toggle-icon" id="toggle_<?= $table_name ?>">
                                        <i class="fas fa-chevron-down"></i>
                                    </span>
                                </div>
                            </div>

                            <div class="level-body" id="body_<?= $table_name ?>">
                                <?php if ($record_count > 0): ?>
                                    <div class="table-wrapper">
                                        <table>
                                            <thead>
                                                <tr>
                                                    <th style="width:40px;">
                                                        <?php if (!$is_exam_page): ?>
                                                            <input type="checkbox" id="select_all_<?= $table_name ?>" onchange="toggleAll('<?= $table_name ?>', this.checked)">
                                                        <?php else: ?>
                                                            <span style="color:#999;">#</span>
                                                        <?php endif; ?>
                                                    </th>
                                                    <th>Exam No</th>
                                                    <th>Name</th>
                                                    <th>Sex</th>
                                                    <th>Photo</th>
                                                    <th style="width:180px;">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($records as $row): ?>
                                                    <tr>
                                                        <td class="checkbox-cell">
                                                            <?php if (!$is_exam_page): ?>
                                                                <input type="checkbox" class="row_checkbox_<?= $table_name ?>" value="<?= htmlspecialchars($row['user_id']) ?>">
                                                            <?php else: ?>
                                                                <span style="color:#999;">-</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><strong><?= htmlspecialchars($row['user_id']) ?></strong></td>
                                                        <td><?= htmlspecialchars($row['name']) ?></td>
                                                        <td><?= htmlspecialchars($row['sex'] ?? 'N/A') ?></td>
                                                        <td>
                                                            <?php if ($row['picture']): ?>
                                                                <img src="data:image/jpeg;base64,<?= base64_encode($row['picture']) ?>" alt="Photo">
                                                            <?php else: ?>
                                                                <span style="color:#999; font-size:11px;">No photo</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <div class="actions-cell">
                                                                <button class="btn btn-danger btn-xs" onclick="confirmDeleteStudent('<?= $table_name ?>', '<?= htmlspecialchars($row['user_id']) ?>')">
                                                                    <i class="fas fa-trash"></i> Delete
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <?php if (!$is_exam_page): ?>
                                        <!-- Move Section - Only for non-exam pages -->
                                        <div class="move-section">
                                            <form method="POST" onsubmit="return confirm('Are you sure you want to move the selected data?');">
                                                <input type="hidden" name="source_table" value="<?= $table_name ?>">
                                                <input type="hidden" name="move_type" id="move_type_<?= $table_name ?>" value="selected">

                                                <div class="move-row">
                                                    <span style="font-weight:600; font-size:14px;">
                                                        <i class="fas fa-arrow-right" style="color:#1a6cf0;"></i> Move/Copy to:
                                                    </span>
                                                    <select name="dest_table" required>
                                                        <option value="">-- Select Destination --</option>
                                                        <?php foreach ($levels as $dest): ?>
                                                            <?php if ($dest['table_name'] !== $table_name): ?>
                                                                <option value="<?= htmlspecialchars($dest['table_name']) ?>">
                                                                    <?= htmlspecialchars($dest['display_name']) ?>
                                                                    <?php if ($dest['table_name'] === 'students'): ?>
                                                                        (Copy)
                                                                    <?php endif; ?>
                                                                </option>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    </select>

                                                    <input type="hidden" name="selected_ids[]" id="selected_ids_<?= $table_name ?>" value="">

                                                    <button type="submit" name="move_data" class="btn btn-warning btn-sm" onclick="prepareMove('<?= $table_name ?>', 'selected')">
                                                        <i class="fas fa-arrow-right"></i> Move Selected
                                                    </button>
                                                    <button type="submit" name="move_data" class="btn btn-primary btn-sm" onclick="prepareMove('<?= $table_name ?>', 'all')">
                                                        <i class="fas fa-arrow-right"></i> Move All
                                                    </button>
                                                </div>
                                                <div style="margin-top:8px; font-size:12px; color:#6b7a8f;">
                                                    <i class="fas fa-info-circle"></i>
                                                    <strong>Note:</strong> Moving to <strong>"OSCE Candidates"</strong> will <span style="color:#6c5ce7; font-weight:600;">COPY</span> the data (source preserved).
                                                    Moving to other levels will <span style="color:#dc3545; font-weight:600;">CUT/MOVE</span> the data (source removed).
                                                </div>
                                            </form>
                                        </div>
                                    <?php else: ?>
                                        <!-- OSCE Candidates - Delete All Button -->
                                        <div style="margin-top:15px; padding:15px; background:#fff3cd; border-radius:10px; border:1px solid #ffc107;">
                                            <form method="POST" onsubmit="return confirm('⚠️ Are you sure you want to delete ALL OSCE Candidates data? This action CANNOT be undone!');">
                                                <div style="display:flex; align-items:center; gap:15px; flex-wrap:wrap;">
                                                    <span style="font-weight:600; color:#856404;">
                                                        <i class="fas fa-exclamation-triangle"></i> Delete All Data:
                                                    </span>
                                                    <label style="display:flex; align-items:center; gap:8px; font-weight:400; font-size:14px; cursor:pointer;">
                                                        <input type="checkbox" name="confirm_delete_all" value="yes" required>
                                                        I confirm to delete all OSCE Candidates data
                                                    </label>
                                                    <button type="submit" name="delete_all_students" class="btn btn-danger btn-sm">
                                                        <i class="fas fa-trash-alt"></i> Delete All
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    <?php endif; ?>

                                <?php else: ?>
                                    <div class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <p>No students in this level yet.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-levels">
                        <i class="fas fa-layer-group"></i>
                        <p>No levels created yet.</p>
                        <p style="font-size:14px; color:#a0b0c4;">Create your first level using the form above.</p>
                    </div>
                <?php endif; ?>
            </div>

        </div>
    </main>

    <!-- Delete Student Confirmation Modal -->
    <div id="deleteStudentModal" class="modal">
        <div class="modal-content">
            <button class="close" onclick="closeDeleteStudentModal()">&times;</button>
            <h2><i class="fas fa-exclamation-triangle" style="color:#dc3545;"></i> Delete Student</h2>
            <p>Are you sure you want to permanently delete this student? This action <strong>cannot be undone</strong>.</p>
            <form method="POST" id="deleteStudentForm">
                <input type="hidden" name="delete_student" value="1">
                <input type="hidden" name="table_name" id="delete_student_table">
                <input type="hidden" name="user_id" id="delete_student_id">
                <div class="modal-actions">
                    <button type="button" class="btn btn-back" onclick="closeDeleteStudentModal()">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash-alt"></i> Yes, Delete
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Level 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 Level</h2>
            <p>Are you sure you want to permanently delete the level <strong id="deleteDisplayName"></strong>?<br>
                This will remove <strong>all student data</strong> associated with it. This action <strong>cannot be undone</strong>.</p>
            <form method="POST" id="deleteForm">
                <input type="hidden" name="delete_level" value="1">
                <input type="hidden" name="table_name" id="deleteTableName">
                <input type="hidden" name="display_name" id="deleteDisplayNameInput">
                <div class="modal-actions">
                    <button type="button" class="btn btn-back" onclick="closeDeleteModal()">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash-alt"></i> Yes, Delete
                    </button>
                </div>
            </form>
        </div>
    </div>

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

    <script>
        function toggleLevel(tableName) {
            const body = document.getElementById('body_' + tableName);
            const icon = document.getElementById('toggle_' + tableName);

            if (body.classList.contains('open')) {
                body.classList.remove('open');
                icon.classList.remove('open');
                icon.innerHTML = '<i class="fas fa-chevron-down"></i>';
            } else {
                body.classList.add('open');
                icon.classList.add('open');
                icon.innerHTML = '<i class="fas fa-chevron-up"></i>';
            }
        }

        function toggleAll(tableName, checked) {
            const checkboxes = document.querySelectorAll('.row_checkbox_' + tableName);
            checkboxes.forEach(cb => {
                cb.checked = checked;
            });
        }

        function prepareMove(tableName, moveType) {
            const selectedIdsInput = document.getElementById('selected_ids_' + tableName);
            const moveTypeInput = document.getElementById('move_type_' + tableName);

            moveTypeInput.value = moveType;

            if (moveType === 'selected') {
                const checkboxes = document.querySelectorAll('.row_checkbox_' + tableName + ':checked');
                const ids = [];
                checkboxes.forEach(cb => {
                    ids.push(cb.value);
                });

                if (ids.length === 0) {
                    alert('Please select at least one student to move.');
                    return false;
                }

                selectedIdsInput.value = ids.join(',');
            } else {
                const destSelect = document.querySelector('select[name="dest_table"]');
                const destValue = destSelect ? destSelect.value : '';
                const isCopyToExam = (destValue === 'students');

                const confirmMsg = isCopyToExam ?
                    'Are you sure you want to COPY ALL students from this level to OSCE Candidates? (Source data will be preserved)' :
                    'Are you sure you want to move ALL students from this level?';

                if (!confirm(confirmMsg)) {
                    return false;
                }
                selectedIdsInput.value = '';
            }

            return true;
        }

        function confirmDeleteStudent(tableName, userId) {
            document.getElementById('delete_student_table').value = tableName;
            document.getElementById('delete_student_id').value = userId;
            document.getElementById('deleteStudentModal').style.display = 'flex';
        }

        function closeDeleteStudentModal() {
            document.getElementById('deleteStudentModal').style.display = 'none';
        }

        function confirmDelete(tableName, displayName) {
            document.getElementById('deleteDisplayName').textContent = displayName;
            document.getElementById('deleteTableName').value = tableName;
            document.getElementById('deleteDisplayNameInput').value = displayName;
            document.getElementById('deleteModal').style.display = 'flex';
        }

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

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

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

</body>

</html>