<?php
set_time_limit(36000); // 10 hours in seconds
session_start();

// ============================================================
// DATABASE CONNECTION
// ============================================================
try {
    $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 - TRY MULTIPLE METHODS
// ============================================================
$institution_id = '';

// Method 1: Try to get from URL path
$path = $_SERVER['REQUEST_URI'];
$path = strtok($path, '?');
$path_parts = explode('/', trim($path, '/'));
$last_segment = end($path_parts);

if (preg_match('/^[A-Z0-9]{10}$/', $last_segment)) {
    $institution_id = $last_segment;
}

// Method 2: Try to get from session
if (empty($institution_id) && isset($_SESSION['institution_id'])) {
    $institution_id = $_SESSION['institution_id'];
}

// Method 3: Try to get from session school array
if (empty($institution_id) && isset($_SESSION['school']['institution_id'])) {
    $institution_id = $_SESSION['school']['institution_id'];
}

// Method 4: Try to get the first approved school from database
if (empty($institution_id)) {
    try {
        $stmt = $db->query("SELECT institution_id FROM schools WHERE status = 'approved' LIMIT 1");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result && !empty($result['institution_id'])) {
            $institution_id = $result['institution_id'];
            // Store in session for future use
            $_SESSION['institution_id'] = $institution_id;
        }
    } catch (PDOException $e) {
        // Silently fail
    }
}

// ============================================================
// GET SCHOOL INFO
// ============================================================
$school_info = null;
if (!empty($institution_id)) {
    try {
        $stmt = $db->prepare("SELECT * FROM schools WHERE institution_id = :institution_id LIMIT 1");
        $stmt->bindParam(':institution_id', $institution_id);
        $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'];
        }
    } catch (PDOException $e) {
        // Silently fail
    }
}

// ============================================================
// CREATE THE ACCESS CONTROL TABLE
// ============================================================
$db->exec("
    CREATE TABLE IF NOT EXISTS candidate_access (
        id INTEGER PRIMARY KEY CHECK (id = 1),
        is_open INTEGER DEFAULT 0,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");

// Ensure there's a row (id = 1) in the table
$check = $db->query("SELECT COUNT(*) FROM candidate_access")->fetchColumn();
if ($check == 0) {
    $db->exec("INSERT INTO candidate_access (id, is_open) VALUES (1, 0)");
}

// Handle toggle request
$message = '';
if (isset($_POST['toggle_access'])) {
    $current = $db->query("SELECT is_open FROM candidate_access WHERE id = 1")->fetchColumn();
    $new_status = $current == 1 ? 0 : 1;
    $stmt = $db->prepare("UPDATE candidate_access SET is_open = :status, updated_at = CURRENT_TIMESTAMP WHERE id = 1");
    $stmt->bindParam(':status', $new_status, PDO::PARAM_INT);
    $stmt->execute();
    $message = $new_status == 1 ? "Candidate link is now OPEN" : "Candidate link is now CLOSED";
}

// Get current status
$is_open = $db->query("SELECT is_open FROM candidate_access WHERE id = 1")->fetchColumn();

// ============================================================
// BUILD THE URL WITH INSTITUTION ID AS SUBDOMAIN
// Format: https://www.INSTITUTION_ID.caosce.net/candidate_view.php
// ============================================================
$subdomain = strtolower($institution_id);
$candidate_url = "candidate_view.php";

// Build the full URL with www.subdomain format
if (!empty($subdomain)) {
    $full_url = "https://www.{$subdomain}.caosce.net/" . $candidate_url;
} else {
    // Fallback if no institution ID found
    $full_url = "https://www.caosce.net/" . $candidate_url;
}

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

// School name for display
$display_school_name = $school_info['school_name'] ?? $_SESSION['school_name'] ?? 'School';
?>
<!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); ?> · Candidate Link</title>
    <link rel="icon" type="image/x-icon" href="CAOSCE Network.ico">

    <!-- Font Awesome 6 (Free) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* ----- RESET & BASE ----- */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

        /* ----- MAIN CONTAINER ----- */
        main {
            flex: 1;
            padding: 30px 5vw;
            display: flex;
            justify-content: center;
            align-items: flex-start;
        }

        .container {
            background: white;
            border-radius: 24px;
            padding: 32px 36px;
            max-width: 650px;
            width: 100%;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
            border: 1px solid #eef4fa;
        }

        /* ----- PAGE HEADER ----- */
        .page-header {
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 2px solid #f0f4fb;
        }

        .page-header .institution-badge {
            display: inline-block;
            background: #1a6cf0;
            color: white;
            padding: 2px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 6px;
        }

        .page-header h1 {
            font-size: 24px;
            color: #10233f;
            display: flex;
            align-items: center;
            gap: 10px;
        }

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

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

        /* ----- STATUS CARD ----- */
        .status-card {
            background: #f8fafc;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 24px;
            text-align: center;
            border: 1px solid #eef4fa;
        }

        .status-label {
            font-size: 13px;
            color: #6b7a8f;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .status-value {
            font-size: 30px;
            font-weight: 700;
            display: inline-block;
            padding: 8px 28px;
            border-radius: 40px;
        }

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

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

        /* ----- URL BOX ----- */
        .url-box {
            background: #f8fafc;
            border-radius: 12px;
            padding: 16px 20px;
            margin: 20px 0;
            border: 1px solid #eef4fa;
        }

        .url-label {
            font-size: 12px;
            color: #6b7a8f;
            margin-bottom: 6px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .url-value {
            font-family: 'Courier New', monospace;
            font-size: 16px;
            color: #10233f;
            word-break: break-all;
            background: white;
            padding: 10px 14px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .url-value .highlight {
            color: #1a6cf0;
            font-weight: 700;
            font-size: 18px;
        }

        .url-value .www-highlight {
            color: #e67e22;
            font-weight: 700;
        }

        .copy-btn {
            background: #1a6cf0;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 8px;
            margin-top: 12px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .copy-btn:hover {
            background: #1057c0;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 108, 240, 0.3);
        }

        /* ----- TOGGLE BUTTON ----- */
        .toggle-btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 16px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .toggle-btn:hover {
            transform: translateY(-2px);
        }

        .toggle-open {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            box-shadow: 0 4px 14px rgba(40, 167, 69, 0.25);
        }

        .toggle-open:hover {
            box-shadow: 0 8px 24px rgba(40, 167, 69, 0.35);
        }

        .toggle-closed {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            box-shadow: 0 4px 14px rgba(220, 53, 69, 0.25);
        }

        .toggle-closed:hover {
            box-shadow: 0 8px 24px rgba(220, 53, 69, 0.35);
        }

        /* ----- MESSAGE ----- */
        .message {
            padding: 12px 16px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            animation: slideDown 0.4s ease;
        }

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

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

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

        /* ----- BACK LINK ----- */
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            color: #1a6cf0;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: 0.2s;
        }

        .back-link:hover {
            color: #1057c0;
            text-decoration: underline;
        }

        /* ----- INSTITUTION INFO ----- */
        .institution-info {
            background: #f0f7ff;
            border-radius: 10px;
            padding: 12px 16px;
            margin-bottom: 20px;
            border: 1px solid #d9e8f5;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
        }

        .institution-info .label {
            font-size: 13px;
            color: #4f6580;
            font-weight: 500;
        }

        .institution-info .value {
            font-size: 14px;
            font-weight: 700;
            color: #10233f;
        }

        .institution-info .id-value {
            font-family: 'Courier New', monospace;
            background: white;
            padding: 2px 12px;
            border-radius: 6px;
            border: 1px solid #d9e8f5;
            font-size: 16px;
            font-weight: 700;
            color: #1a6cf0;
        }

        /* ----- DOMAIN DISPLAY ----- */
        .domain-display {
            background: #f8fafc;
            border-radius: 10px;
            padding: 12px 16px;
            margin-bottom: 20px;
            border: 1px solid #eef4fa;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .domain-display .label {
            font-size: 12px;
            color: #6b7a8f;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .domain-display .domain {
            font-family: 'Courier New', monospace;
            font-size: 18px;
            font-weight: 700;
            color: #1a6cf0;
        }

        .domain-display .domain .www {
            color: #e67e22;
        }

        .domain-display .domain .id {
            color: #1a6cf0;
            font-size: 20px;
        }

        .domain-display .domain .tld {
            color: #6b7a8f;
        }

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

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

            .container {
                padding: 24px 18px;
            }

            .page-header h1 {
                font-size: 20px;
            }

            .status-value {
                font-size: 24px;
                padding: 6px 20px;
            }

            .url-value {
                font-size: 13px;
            }

            .url-value .highlight {
                font-size: 15px;
            }

            .domain-display .domain {
                font-size: 15px;
            }

            .domain-display .domain .id {
                font-size: 17px;
            }

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

            .institution-info {
                flex-direction: column;
                align-items: flex-start;
            }

            .domain-display {
                flex-direction: column;
                align-items: flex-start;
            }
        }

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

            .brand-icon {
                width: 30px;
                height: 30px;
                font-size: 14px;
            }

            .container {
                padding: 18px 14px;
            }
        }
    </style>
</head>

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

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

            <!-- Page Header -->
            <div class="page-header">
               
                <h1>
                    <i class="fas fa-link"></i>
                    Candidate Link Manager
                </h1>
                <div class="subtitle">Control access to the candidates verification page</div>
            </div>

          
            <!-- Message -->
            <?php if ($message): ?>
                <div class="message message-success">
                    <i class="fas <?= strpos($message, 'OPEN') !== false ? 'fa-unlock' : 'fa-lock' ?>"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <!-- Status Card -->
            <div class="status-card">
                <div class="status-label">
                    <i class="fas fa-circle" style="font-size:10px; color:<?= $is_open ? '#28a745' : '#dc3545' ?>;"></i>
                    Current Status
                </div>
                <div class="status-value <?= $is_open ? 'status-open' : 'status-closed' ?>">
                    <?= $is_open ? '🔓 OPEN' : '🔒 CLOSED' ?>
                </div>
            </div>

            <!-- URL Box -->
            <div class="url-box">
                <div class="url-label">
                    <i class="fas fa-globe"></i> Candidate View Link
                </div>
                <div class="url-value" id="candidateUrl">
                    <?php if (!empty($subdomain)): ?>
                        <span style="color: #6b7a8f;">https://</span>
                        <span class="www-highlight">www.</span>
                        <span class="highlight"><?php echo htmlspecialchars($subdomain); ?></span>
                        <span style="color: #6b7a8f;">.caosce.net/<?php echo htmlspecialchars($candidate_url); ?></span>
                    <?php else: ?>
                        <span style="color: #999;">No institution ID found. Please ensure a school is registered and approved.</span>
                    <?php endif; ?>
                </div>
                <?php if (!empty($subdomain)): ?>
                    <button class="copy-btn" onclick="copyUrl()">
                        <i class="fas fa-copy"></i> Copy Link
                    </button>
                <?php endif; ?>
            </div>

            <!-- Toggle Button -->
            <form method="POST">
                <button type="submit" name="toggle_access" class="toggle-btn <?= $is_open ? 'toggle-closed' : 'toggle-open' ?>">
                    <i class="fas <?= $is_open ? 'fa-lock' : 'fa-unlock' ?>"></i>
                    <?= $is_open ? 'Close Candidate Access' : 'Open Candidate Access' ?>
                </button>
            </form>

            <!-- Back Link -->
            <a href="admin.php" class="back-link">
                <i class="fas fa-arrow-left"></i> Back to Admin Panel
            </a>

        </div>
    </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($institution_id)): ?>
                <span><strong><?php echo htmlspecialchars($institution_id); ?></strong></span>
            <?php endif; ?>
        </div>
    </footer>

    <!-- ============================================================
         SCRIPTS
         ============================================================ -->
    <script>
        function copyUrl() {
            const url = document.getElementById('candidateUrl').innerText.trim();
            // Clean up the URL text (remove extra spaces)
            const cleanUrl = url.replace(/\s+/g, '').trim();

            navigator.clipboard.writeText(cleanUrl).then(() => {
                alert('✅ Link copied to clipboard!\n\n' + cleanUrl);
            }).catch(() => {
                // Fallback for older browsers
                const textarea = document.createElement('textarea');
                textarea.value = cleanUrl;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                alert('✅ Link copied to clipboard!\n\n' + cleanUrl);
            });
        }
    </script>

</body>

</html>