<?php
// FINAL - Includes session fix and safe PWA registration
session_start(); 
require_once 'config.php';

// (The entire PHP login logic remains the same as before)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $username = strtolower(trim($_POST['username'] ?? ''));
    $index_number = trim($_POST['index_number'] ?? '');
    if (empty($username) || empty($index_number)) {
        echo json_encode(['success' => false, 'message' => 'Please enter your first name and index number.']);
        exit();
    }
    try {
        $stmt = $pdo->prepare("SELECT id, full_name, password_hash, class_id FROM students WHERE username = ?");
        $stmt->execute([$username]);
        $student = $stmt->fetch();
        if ($student && password_verify($index_number, $student['password_hash'])) {
            session_regenerate_id(true);
            $_SESSION['student_id'] = $student['id'];
            $_SESSION['student_full_name'] = $student['full_name'];
            $_SESSION['student_class_id'] = $student['class_id'];
            echo json_encode(['success' => true, 'redirect_url' => BASE_URL . '/student/dashboard.php']);
            exit();
        } else {
            echo json_encode(['success' => false, 'message' => 'Oops! Your name or index number is not correct. Please try again.']);
            exit();
        }
    } catch (PDOException $e) {
        error_log($e->getMessage()); 
        echo json_encode(['success' => false, 'message' => 'A server error occurred. Please tell your teacher!']);
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Login - TTTEDDDEL</title>
    <link rel="manifest" href="/homework_portal/manifest.json">
    <meta name="theme-color" content="#ff0000"/>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        /* (All CSS remains the same) */
        body { font-family: 'Poppins', sans-serif; background-color: #f0f4f8; }
        .form-input { background-color: #f1f5f9; border: 2px solid #e2e8f0; border-radius: 12px; padding: 1rem; font-size: 1rem; transition: border-color 0.3s, box-shadow 0.3s; }
        .form-input:focus { outline: none; border-color: #4dd0e1; box-shadow: 0 0 0 3px rgba(77, 208, 225, 0.3); }
        .submit-btn { background-color: #ff7043; color: white; font-weight: bold; font-size: 1.1rem; border-radius: 12px; padding: 0.8rem 1.5rem; transition: background-color 0.3s, transform 0.2s, opacity 0.2s; border: none; box-shadow: 0 4px 15px rgba(255, 112, 67, 0.3); }
        .submit-btn:hover { background-color: #ff5722; transform: translateY(-2px); }
        .submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
    </style>
</head>
<body class="flex items-center justify-center min-h-screen p-4">
    <div class="w-full max-w-sm">
        <div class="text-center mb-8">
            <h1 class="text-6xl font-bold text-red-600 tracking-widest font-sans">TTTEDDDEL</h1>
            <p class="text-sm font-semibold text-blue-800 mt-1">Teacher-Student Interactive System</p>
            <p class="text-sm text-blue-800">by Ele Infocomm Technologies</p>
        </div>
        <div class="bg-white rounded-2xl shadow-lg p-8">
            <h2 class="text-2xl font-bold text-center text-gray-700">Student Login</h2>
            <div id="error-container" class="p-4 my-4 text-sm text-orange-800 bg-orange-100 rounded-lg text-center hidden"></div>
            <form id="login-form" action="login.php" method="POST" class="space-y-5">
                <div>
                    <label for="username" class="block mb-1 text-sm font-medium text-gray-600">Your First Name</label>
                    <input type="text" name="username" id="username" class="form-input w-full" placeholder="e.g., Juma" required>
                </div>
                <div>
                    <label for="index_number" class="block mb-1 text-sm font-medium text-gray-600">Your Index Number</label>
                    <input type="password" name="index_number" id="index_number" class="form-input w-full" placeholder="e.g., 12345" required>
                </div>
                <button type="submit" id="submit-button" class="submit-btn w-full">Let's Go!</button>
            </form>
        </div>
    </div>
    <script>
        // (The login form submission script remains the same)
        document.addEventListener('DOMContentLoaded', function() {
            const loginForm = document.getElementById('login-form');
            const errorContainer = document.getElementById('error-container');
            const submitButton = document.getElementById('submit-button');
            if (loginForm) {
                loginForm.addEventListener('submit', function (e) {
                    e.preventDefault(); 
                    submitButton.disabled = true;
                    submitButton.textContent = 'Checking...';
                    errorContainer.classList.add('hidden');
                    const formData = new FormData(this);
                    fetch(this.action, { method: 'POST', body: formData })
                    .then(response => {
                        if (!response.ok) throw new Error('Network response was not ok');
                        return response.json();
                    })
                    .then(data => {
                        if (data.success && data.redirect_url) {
                            window.location.href = data.redirect_url;
                        } else {
                            errorContainer.textContent = data.message || 'An unknown error occurred.';
                            errorContainer.classList.remove('hidden');
                            submitButton.disabled = false;
                            submitButton.textContent = 'Let\'s Go!';
                        }
                    })
                    .catch(error => {
                        console.error('Fetch error:', error);
                        errorContainer.textContent = 'A network error occurred. Please check your connection and try again.';
                        errorContainer.classList.remove('hidden');
                        submitButton.disabled = false;
                        submitButton.textContent = 'Let\'s Go!';
                    });
                });
            }

            // PWA registration logic
            const isMobile = /Mobi/i.test(window.navigator.userAgent);
            if (isMobile && 'serviceWorker' in navigator) {
                window.addEventListener('load', () => {
                    // UPDATED registration with a specific scope for safety
                    navigator.serviceWorker.register('/homework_portal/sw.js', { scope: '/homework_portal/' })
                        .then(reg => console.log('ServiceWorker registered successfully.'))
                        .catch(err => console.log('ServiceWorker registration failed: ', err));
                });
            }
        });
    </script>
</body>
</html>