<?php
session_start();

// ============================================================
// DATABASE CONNECTION
// ============================================================
try {
    // Try to connect to database in parent directory (for subdomains)
    if (file_exists('database.db')) {
        $db = new PDO('sqlite:database.db');
    } elseif (file_exists('database.db')) {
        $db = new PDO('sqlite:database.db');
    } else {
        $db = new PDO('sqlite:database.db');
    }
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ============================================================
// GET INSTITUTION ID FROM URL PATH (Path-based approach)
// ============================================================
$institution_id_from_url = '';
$path = $_SERVER['REQUEST_URI'];
// Remove query string if present
$path = strtok($path, '?');
// Get the last segment of the path
$path_parts = explode('/', trim($path, '/'));
$last_segment = end($path_parts);

// Check if the last segment looks like an institution ID (alphanumeric, 10 chars)
if (preg_match('/^[A-Z0-9]{10}$/', $last_segment)) {
    $institution_id_from_url = $last_segment;
}

// ============================================================
// GET SUBDOMAIN FROM URL (Subdomain approach - for backward compatibility)
// ============================================================
$host = $_SERVER['HTTP_HOST'];
$subdomain = '';

// Extract subdomain from host (e.g., 8e6up8wh10.caosce.net)
if (strpos($host, '.') !== false) {
    $parts = explode('.', $host);
    if (count($parts) > 2) {
        $subdomain = strtolower($parts[0]);
    }
}

// ============================================================
// FETCH SCHOOL DATA
// ============================================================
$school_info = null;

// Try to find school from URL path first (priority)
if (!empty($institution_id_from_url)) {
    try {
        $stmt = $db->prepare("SELECT * FROM schools WHERE LOWER(institution_id) = LOWER(:institution_id) LIMIT 1");
        $stmt->bindParam(':institution_id', $institution_id_from_url);
        $stmt->execute();
        $school_info = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($school_info) {
            $_SESSION['institution_id'] = $school_info['institution_id'];
            $_SESSION['school_name'] = $school_info['school_name'];
            $_SESSION['school'] = $school_info;
        }
    } catch (PDOException $e) {
        // Silently fail
    }
}

// If not found from URL path, try subdomain
if (!$school_info && !empty($subdomain)) {
    try {
        $stmt = $db->prepare("SELECT * FROM schools WHERE LOWER(institution_id) = LOWER(:institution_id) LIMIT 1");
        $stmt->bindParam(':institution_id', $subdomain);
        $stmt->execute();
        $school_info = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($school_info) {
            $_SESSION['institution_id'] = $school_info['institution_id'];
            $_SESSION['school_name'] = $school_info['school_name'];
            $_SESSION['school'] = $school_info;
        }
    } catch (PDOException $e) {
        // Silently fail
    }
}

// If still not found, check session
if (!$school_info && isset($_SESSION['institution_id'])) {
    try {
        $stmt = $db->prepare("SELECT * FROM schools WHERE institution_id = :institution_id LIMIT 1");
        $stmt->bindParam(':institution_id', $_SESSION['institution_id']);
        $stmt->execute();
        $school_info = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($school_info) {
            $_SESSION['school_name'] = $school_info['school_name'];
            $_SESSION['school'] = $school_info;
        }
    } catch (PDOException $e) {
        // Silently fail
    }
}

// If still no school info, try to get from session
if (!$school_info && isset($_SESSION['school'])) {
    $school_info = $_SESSION['school'];
}

// ============================================================
// GET ALL SCHOOLS FOR ADMIN DISPLAY
// ============================================================
try {
    $stmt = $db->query("SELECT * FROM schools ORDER BY id DESC");
    $all_schools = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $all_schools = [];
}

// ============================================================
// GET SCHOOL STATISTICS
// ============================================================
$total_schools = count($all_schools);
$pending_schools = 0;
$approved_schools = 0;
$suspended_schools = 0;

foreach ($all_schools as $school) {
    if ($school['status'] === 'pending') $pending_schools++;
    elseif ($school['status'] === 'approved') $approved_schools++;
    elseif ($school['status'] === 'suspended') $suspended_schools++;
}

// Determine which school to display
$display_school_name = $school_info['school_name'] ?? $_SESSION['school_name'] ?? 'CAOSCE';
$display_institution_id = $school_info['institution_id'] ?? $_SESSION['institution_id'] ?? '';

// 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><?php echo htmlspecialchars($display_school_name); ?> · Network</title>
    <link rel="icon" type="image/x-icon" href="CAOSCE Network.ico">

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,400;14..32,500;14..32,600;14..32,700;14..32,800;14..32,900&display=swap" rel="stylesheet">

    <!-- 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: Arial, Helvetica, sans-serif;
            background: #f0f4fb;
            color: #10233f;
            line-height: 1.5;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        a {
            text-decoration: none;
            color: inherit;
        }

        /* ----- palette ----- */
        :root {
            --ink: #10233f;
            --dark: #071a31;
            --muted: #4f6580;
            --muted-light: #7c8ea8;
            --primary: #1a6cf0;
            --primary-dark: #0e4db0;
            --purple: #6d5dfc;
            --green: #16a085;
            --orange: #ee8b35;
            --red: #d92d20;
            --line: #e2eaf2;
            --bg: #f0f4fb;
            --white: #ffffff;
            --shadow-sm: 0 8px 28px rgba(16, 35, 63, 0.06);
            --shadow-md: 0 16px 48px rgba(16, 35, 63, 0.08);
            --radius: 24px;
        }

        /* ----- top 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: var(--ink);
            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;
            transition: 0.2s;
            position: relative;
            text-decoration: none;
        }

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

        .nav-links a:hover,
        .nav-links a.active {
            color: var(--primary);
        }

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

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

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

        /* ----- main container ----- */
        .main-wrap {
            flex: 1;
            max-width: 1360px;
            width: 100%;
            margin: 0 auto;
            padding: 40px 5vw 30px;
        }

        /* ----- dashboard card ----- */
        .dashboard-card {
            background: #ffffff;
            border-radius: var(--radius);
            padding: 40px 44px;
            box-shadow: var(--shadow-md);
            border: 1px solid #eef4fa;
            transition: 0.25s;
        }

        .dashboard-card:hover {
            box-shadow: 0 20px 60px rgba(16, 35, 63, 0.10);
        }

        /* ----- header ----- */
        .dash-header {
            display: flex;
            flex-wrap: wrap;
            align-items: flex-end;
            justify-content: space-between;
            margin-bottom: 32px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eef4fa;
        }

        .dash-header h1 {
            font-size: 32px;
            font-weight: 800;
            letter-spacing: -0.6px;
            background: linear-gradient(135deg, #10233f 0%, #1a6cf0 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin: 0;
        }

        .dash-header .sub {
            font-size: 14px;
            color: var(--muted-light);
            font-weight: 500;
            margin-top: 4px;
        }

        .dash-header .badge-version {
            background: #eef4fa;
            padding: 6px 18px;
            border-radius: 40px;
            font-size: 13px;
            font-weight: 600;
            color: #2d4560;
            letter-spacing: 0.3px;
        }

        /* ----- school profile ----- */
        .school-profile {
            background: linear-gradient(145deg, #f8faff, #eef4fb);
            border-radius: 20px;
            padding: 24px 32px;
            margin-bottom: 38px;
            border: 1px solid #e2eaf2;
            box-shadow: inset 0 1px 4px rgba(255, 255, 255, 0.8);
        }

        .school-profile-top {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;
        }

        .school-left {
            display: flex;
            align-items: center;
            gap: 18px;
            flex-wrap: wrap;
        }

        .school-left .school-badge {
            background: var(--primary);
            color: white;
            font-weight: 700;
            font-size: 13px;
            padding: 4px 20px;
            border-radius: 40px;
            letter-spacing: 0.3px;
            box-shadow: 0 4px 10px rgba(26, 108, 240, 0.2);
        }

        .school-name {
            font-size: 40px;
            font-weight: 700;
            color: var(--ink);
            margin-right: 6px;
        }

        .school-id {
            font-size: 14px;
            font-weight: 700;
            background: white;
            padding: 4px 16px;
            border-radius: 30px;
            border: 1px solid #dee8f2;
            color: #10233f;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            letter-spacing: 0;
        }

        .school-id strong {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            font-weight: 700;
        }

        .school-detail {
            display: flex;
            flex-wrap: wrap;
            gap: 12px 28px;
            color: #2f4a6b;
            font-size: 14px;
        }

        .school-detail i {
            color: var(--primary);
            width: 18px;
            margin-right: 5px;
        }

        .school-detail span {
            background: white;
            padding: 2px 14px 2px 10px;
            border-radius: 30px;
            border: 1px solid #dee8f2;
            font-weight: 500;
            font-size: 13px;
        }

        .no-data {
            color: var(--muted-light);
            font-weight: 500;
            font-style: italic;
            padding: 8px 0;
        }

        /* ----- all schools inside profile ----- */
        .all-schools-section {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 2px dashed #dce5ef;
        }

        .all-schools-section .section-label {
            font-size: 30px;
            font-weight: 600;
            color: var(--muted);
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .schools-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 10px;
        }

        .school-item {
            background: white;
            border-radius: 10px;
            padding: 12px 16px;
            border: 1px solid #eef4fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: 0.2s;
        }

        .school-item:hover {
            border-color: #c8d8ec;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        }

        .school-item .school-info {
            display: flex;
            flex-direction: column;
        }

        .school-item .school-info .name {
            font-weight: 600;
            color: var(--ink);
            font-size: 30px;
        }

        .school-item .school-info .id {
            font-size: 20px;
            color: var(--muted-light);
            font-family: monospace;
        }

        .school-item .status-badge {
            font-size: 10px;
            font-weight: 600;
            padding: 2px 10px;
            border-radius: 20px;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .status-approved {
            background: #d4edda;
            color: #155724;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-suspended {
            background: #f8d7da;
            color: #721c24;
        }

        .schools-empty {
            color: var(--muted-light);
            font-size: 14px;
            text-align: center;
            padding: 10px 0;
        }

        /* ----- action grid ----- */
        .action-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
            gap: 18px;
            margin-top: 8px;
        }

        .action-card {
            background: white;
            border-radius: 18px;
            padding: 18px 12px 16px;
            box-shadow: 0 6px 20px rgba(16, 35, 63, 0.04);
            border: 1px solid #eef4fa;
            transition: all 0.2s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            cursor: pointer;
        }

        .action-card:hover {
            transform: translateY(-6px);
            box-shadow: 0 18px 34px rgba(16, 35, 63, 0.08);
            border-color: #c8d8ec;
        }

        .action-card .icon-wrap {
            font-size: 28px;
            background: #f2f7ff;
            width: 56px;
            height: 56px;
            display: grid;
            place-items: center;
            border-radius: 40px;
            margin-bottom: 12px;
            color: var(--primary);
            transition: 0.2s;
        }

        .action-card:hover .icon-wrap {
            background: var(--primary);
            color: white;
        }

        .action-card .action-label {
            font-weight: 700;
            font-size: 15px;
            color: var(--ink);
            margin-bottom: 6px;
        }

        .action-card .action-desc {
            font-size: 12px;
            color: var(--muted-light);
            font-weight: 500;
        }

        .action-card form {
            width: 100%;
        }

        .action-card button {
            background: transparent;
            border: none;
            width: 100%;
            padding: 0;
            font: inherit;
            color: inherit;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .action-card.highlight .icon-wrap {
            background: linear-gradient(135deg, #eef4fb, #dce7f5);
            color: #1a6cf0;
        }

        .action-card.highlight:hover .icon-wrap {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
        }

        /* ----- footer ----- */
        .footer {
            margin-top: 40px;
            padding: 24px 5vw 20px;
            background: var(--dark);
            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;
            }

            .dashboard-card {
                padding: 28px 20px;
            }

            .dash-header h1 {
                font-size: 26px;
            }

            .school-name {
                font-size: 18px;
            }

            .school-profile-top {
                flex-direction: column;
                align-items: flex-start;
                gap: 14px;
            }

            .school-detail {
                gap: 10px;
            }

            .action-grid {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            }

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

        @media (max-width: 550px) {
            .dash-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
            }

            .dash-header .badge-version {
                align-self: flex-start;
            }

            .school-left {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }

            .action-grid {
                grid-template-columns: 1fr 1fr;
                gap: 12px;
            }

            .action-card {
                padding: 14px 8px;
            }

            .action-card .icon-wrap {
                width: 48px;
                height: 48px;
                font-size: 22px;
            }

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

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

        @media (max-width: 400px) {
            .action-grid {
                grid-template-columns: 1fr;
            }
        }

        /* School Portal Banner */
        .school-portal-banner {
            background: #eef4ff;
            border: 1px solid #1a6cf0;
            border-radius: 8px;
            padding: 12px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 10px;
        }

        .school-portal-banner code {
            background: white;
            padding: 4px 12px;
            border-radius: 4px;
            border: 1px solid #d9e2eb;
            font-size: 14px;
        }

        .school-portal-banner .badge {
            background: #1a6cf0;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
    </style>

    <script>
        window.onload = function() {
            fetch('activatedstudentsmain.php')
                .then(response => response.text())
                .then(data => console.log(data))
                .catch(err => console.error('Error:', err));
        };
    </script>
</head>

<body>

    <!-- ============================================================
         NAVIGATION
         ============================================================ -->
    <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="active"><i class="fas fa-th-large"></i> Admin Dashboard</a>
            <a href="logout.php" class="nav-logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </header>

    <!-- ============================================================
         MAIN
         ============================================================ -->
    <main class="main-wrap">
        <div class="dashboard-card">
            <!-- school profile (dynamic from database) -->
            <div class="school-profile">
                
                <!-- All Schools Section (inside profile) -->
                <div class="all-schools-section">

                    <div class="schools-grid">
                        <?php if (!empty($all_schools)): ?>
                            <?php foreach ($all_schools as $school): ?>
                                <div class="school-item">
                                    <div class="school-info">
                                        <span class="name"><?php echo htmlspecialchars($school['school_name']); ?></span>
                                        <span class="id">ID: <?php echo htmlspecialchars($school['institution_id'] ?? 'Not assigned'); ?></span>
                                    </div>
                                    <span class="status-badge status-<?php echo $school['status'] ?? 'pending'; ?>">
                                        <?php echo ucfirst($school['status'] ?? 'Pending'); ?>
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="schools-empty">
                                <i class="fas fa-info-circle"></i> No schools registered yet.
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- action grid -->
            <div class="action-grid">

                <!-- 1. Insert Student -->
                <div class="action-card">
                    <form method="post" action="insert_student_data.php">
                        <button type="submit" name="action" value="show_form">
                            <div class="icon-wrap"><i class="fas fa-user-plus"></i></div>
                            <div class="action-label">Add Student</div>
                            <div class="action-desc">Add new students</div>
                        </button>
                    </form>
                </div>

                <!-- 2. Class List -->
                <div class="action-card" onclick="window.location.href='classes.php'">
                    <div class="icon-wrap"><i class="fas fa-users"></i></div>
                    <div class="action-label">Class List</div>
                    <div class="action-desc">Class/Level</div>
                </div>

                <!-- 3. OSCE Candidates -->
                <div class="action-card">
                    <form method="post" action="show_all_students_details.php">
                        <button type="submit" name="action" value="display_data">
                            <div class="icon-wrap"><i class="fas fa-tablet-alt"></i></div>
                            <div class="action-label">OSCE Candidates</div>
                            <div class="action-desc">View full list</div>
                        </button>
                    </form>
                </div>

                <!-- 4. Search Student -->
                <div class="action-card">
                    <form method="post" action="candidate.php">
                        <button type="submit" name="action" value="activated_students">
                            <div class="icon-wrap"><i class="fas fa-search"></i></div>
                            <div class="action-label">Search Student</div>
                            <div class="action-desc">Find by Exam no/name</div>
                        </button>
                    </form>
                </div>

                <!-- 5. Verification Portal -->
                <div class="action-card highlight">
                    <form method="post" action="candidate_link.php">
                        <button type="submit" name="action" value="activated_students">
                            <div class="icon-wrap"><i class="fas fa-shield-alt"></i></div>
                            <div class="action-label">Verification Portal</div>
                            <div class="action-desc">Verify students</div>
                        </button>
                    </form>
                </div>

               

                <!-- 7. OSCE Result Table -->
                <div class="action-card" onclick="window.location.href='result.php'">
                    <div class="icon-wrap"><i class="fas fa-table"></i></div>
                    <div class="action-label">OSCE Result Table</div>
                    <div class="action-desc">OSCE Scores</div>
                </div>

                <!-- 8. Exam Settings -->
                <div class="action-card" onclick="window.location.href='exam_manager.php'">
                    <div class="icon-wrap"><i class="fas fa-cog"></i></div>
                    <div class="action-label">Exam Settings</div>
                    <div class="action-desc">Configure OSCE</div>
                </div>

                <!-- 9. Login Settings -->
                <div class="action-card" onclick="window.location.href='settings.php'">
                    <div class="icon-wrap"><i class="fas fa-key"></i></div>
                    <div class="action-label">Login Settings</div>
                    <div class="action-desc">Change Login Details</div>
                </div>

                <!-- 10. Software Download -->
                <div class="action-card" onclick="window.location.href='software.php'">
                    <div class="icon-wrap"><i class="fas fa-download"></i></div>
                    <div class="action-label">Software Download</div>
                    <div class="action-desc">Download Software</div>
                </div>

            </div> <!-- /action-grid -->

        </div> <!-- /dashboard-card -->
    </main>

    <!-- ============================================================
         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>
            <?php if (!empty($display_institution_id)): ?>
                <span><strong><?php echo htmlspecialchars($display_institution_id); ?></strong></span>
            <?php endif; ?>
        </div>
    </footer>

</body>

</html>