<?php
session_start();

// ✅ Connect to SQLite database
$db = new PDO('sqlite:database.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// ✅ Create access control table if it doesn't exist
$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)");
}

// ✅ Check if access is open
$is_open = $db->query("SELECT is_open FROM candidate_access WHERE id = 1")->fetchColumn();

// ✅ If not open, show 404 error
if (!$is_open) {
    http_response_code(404);
    echo '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>404 - Page Not Found</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
                background:  #f0f4fb;
                min-height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
            }
            .error-container {
                background: white;
                border-radius: 24px;
                padding: 40px;
                text-align: center;
                max-width: 500px;
                width: 100%;
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            }
            h1 {
                font-size: 80px;
                color: #667eea;
                margin-bottom: 16px;
            }
            h2 {
                font-size: 24px;
                color: #333;
                margin-bottom: 12px;
            }
            p {
                color: #666;
                margin-bottom: 24px;
            }
            .back-btn {
                display: inline-block;
                background: linear-gradient(135deg, #667eea, #764ba2);
                color: white;
                text-decoration: none;
                padding: 12px 24px;
                border-radius: 12px;
                transition: transform 0.2s;
            }
            .back-btn:hover {
                transform: translateY(-2px);
            }
        </style>
    </head>
    <body>
        <div class="error-container">
            <h1>404 Error</h1>
            <h2>Page Not Found</h2>
            <p>The page you are looking for does not exist or has been moved.</p>

        </div>
    </body>
    </html>';
    exit;
}

// ✅ Handle search request
$searched_user = null;
$search_performed = false;
$search_query = '';

if (isset($_GET['search']) && !empty(trim($_GET['search']))) {
    $search_performed = true;
    $search_query = trim($_GET['search']);

    // Search for user by user_id or name
    $stmt = $db->prepare("SELECT user_id, name, picture FROM students WHERE user_id = :search_term OR name LIKE :search_like LIMIT 1");
    $search_like = '%' . $search_query . '%';
    $stmt->bindParam(':search_term', $search_query, PDO::PARAM_STR);
    $stmt->bindParam(':search_like', $search_like, PDO::PARAM_STR);
    $stmt->execute();
    $searched_user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>OSCE verification</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            background: #f0f4fb;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 500px;
            margin: 0 auto;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .card {
            background: white;
            border-radius: 32px;
            padding: 28px 24px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .logo {
            text-align: center;
            margin-bottom: 24px;
        }

        .logo h1 {
            font-size: 24px;
            color: #333;
            margin-bottom: 6px;
        }

        .logo p {
            font-size: 14px;
            color: #666;
        }

        .search-box {
            margin-bottom: 28px;
        }

        .search-form {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .search-input {
            width: 100%;
            padding: 16px 18px;
            font-size: 16px;
            border: 2px solid #e0e0e0;
            border-radius: 20px;
            outline: none;
            transition: all 0.3s;
            font-family: inherit;
        }

        .search-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .search-btn {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 14px 20px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 20px;
            cursor: pointer;
            transition: transform 0.2s, opacity 0.2s;
            font-family: inherit;
        }

        .search-btn:active {
            transform: scale(0.98);
        }

        .clear-btn {
            background: #6c757d;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }

        .clear-btn:active {
            transform: scale(0.98);
        }

        .result-area {
            margin-top: 20px;
        }

        .no-result {
            text-align: center;
            padding: 40px 20px;
            background: #f8f9fa;
            border-radius: 24px;
        }

        .no-result-icon {
            font-size: 48px;
            margin-bottom: 12px;
        }

        .no-result-text {
            color: #666;
            font-size: 15px;
        }

        .no-result-highlight {
            color: #667eea;
            font-weight: 500;
        }

        .user-card {
            animation: fadeIn 0.4s ease;
        }

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

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

        .user-photo {
            text-align: center;
            margin-bottom: 20px;
        }

        .user-photo img {
            width: 180px;
            height: 180px;
            object-fit: cover;
            border-radius: 50%;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            border: 4px solid white;
            background: #f0f0f0;
        }

        .placeholder-photo {
            width: 180px;
            height: 180px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
            color: white;
            font-size: 64px;
            font-weight: 600;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .user-info {
            text-align: center;
            padding: 8px 0;
        }

        .user-name {
            font-size: 22px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }

        .user-id {
            font-size: 30px;
            font-weight: bold;
            color: #667eea;
            background: #f0f0ff;
            display: inline-block;
            padding: 6px 16px;
            border-radius: 40px;
            font-family: monospace;
            letter-spacing: 0.5px;
        }

        .welcome-message {
            text-align: center;
            padding: 40px 20px;
            background: #f8f9fa;
            border-radius: 24px;
        }

        .welcome-icon {
            font-size: 56px;
            margin-bottom: 16px;
        }

        .welcome-text {
            font-size: 16px;
            color: #666;
            line-height: 1.5;
        }

        .footer {
            text-align: center;
            margin-top: 20px;
            color: rgba(14, 7, 7, 0.76);
            font-size: 24px;
        }

        @media (max-width: 480px) {
            .card {
                padding: 20px 16px;
            }

            .user-photo img,
            .placeholder-photo {
                width: 140px;
                height: 140px;
            }

            .user-name {
                font-size: 20px;
            }

            .user-id {
                font-size: 30px;
            }
        }

        .status {
            margin-top: 12px;
            font-size: 32px;
            font-weight: bold;
        }

        .activated {
            color: green;
        }

        .not-activated {
            color: red;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="card">
            <div class="logo">
                <h1>OSCE Details Verification Portal</h1>
                <p>Enter your Matric Number and Search</p>
            </div>

            <div class="search-box">
                <form class="search-form" method="GET" action="">
                    <input type="text"
                        name="search"
                        class="search-input"
                        placeholder="e.g., UG/01/0101"
                        value="<?= htmlspecialchars($search_query) ?>"
                        autofocus>
                    <button type="submit" class="search-btn">🔍 Search</button>
                    <?php if ($search_performed): ?>
                        <a href="<?= $_SERVER['PHP_SELF'] ?>" class="search-btn clear-btn">Clear Search</a>
                    <?php endif; ?>
                </form>
            </div>

            <div class="result-area">
                <?php if (!$search_performed): ?>
                    <div class="welcome-message">
                        <div class="welcome-icon">👋</div>
                        <div class="welcome-text">
                            Enter your Matric Number<br>
                            to view your Passport photograph, Name and Matric Number
                        </div>
                    </div>
                <?php elseif ($searched_user === false || $searched_user === null): ?>
                    <div class="no-result">
                        <div class="no-result-icon">😕</div>
                        <div class="no-result-text">
                            No student found with<br>
                            <span class="no-result-highlight">"<?= htmlspecialchars($search_query) ?>"</span>
                        </div>
                    </div>
                <?php else: ?>
                    <?php
                    // ✅ Check activation status
                    $uid = trim($searched_user['user_id']);

                    $stmt2 = $db->prepare("
        SELECT user_id 
        FROM activated_students 
        WHERE TRIM(user_id) = :uid 
        COLLATE NOCASE
        LIMIT 1
    ");
                    $stmt2->execute([':uid' => $uid]);

                    $is_activated = $stmt2->fetch(PDO::FETCH_ASSOC) ? true : false;
                    ?>

                    <div class="user-card">
                        <div class="user-photo">
                            <?php if (!empty($searched_user['picture'])): ?>
                                <img src="data:image/jpeg;base64,<?= base64_encode($searched_user['picture']) ?>"
                                    alt="Student Photo">
                            <?php else: ?>
                                <div class="placeholder-photo">
                                    <?= strtoupper(substr($searched_user['name'] ?? '?', 0, 1)) ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="user-info">
                            <div class="user-name"><?= htmlspecialchars($searched_user['name'] ?? 'Not Available') ?></div>
                            <div class="user-id"><?= htmlspecialchars($searched_user['user_id'] ?? 'N/A') ?></div>


                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <div class="footer">
            OSCE • Student Verification Portal
        </div>
    </div>
</body>

</html>