<?php
//session started
require_once 'session_config_school.php';

// Database connection
include_once 'connect.php';

$message = '';
$rememberMe = false;

// Check for forgot password error
if (isset($_GET['forgot_error'])) {
    $message = htmlspecialchars($_GET['forgot_error']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $emis_code = $_POST['emis_code'];
    $password = $_POST['password'];
    $rememberMe = isset($_POST['remember']) ? true : false;

    // Validate input
    if (empty($emis_code) || empty($password)) {
        $message = 'Please fill out both fields.';
    } elseif (!preg_match('/^\d{11}$/', $emis_code)) {
        $message = 'EMIS Code must be exactly 11 digits.';
    } else {
        // Fetch user
        $stmt = $conn->prepare("SELECT * FROM registrations WHERE emis_code = ?");
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            if ($user['status'] == 1) {
                if (password_verify($password, $user['password'])) {
                    // Store previous last login in session
                    $_SESSION['last_login'] = $user['last_login'];

                    // Update last login in DB
                    $update_stmt = $conn->prepare("UPDATE registrations SET last_login = NOW() WHERE emis_code = ?");
                    $update_stmt->bind_param("s", $emis_code);
                    $update_stmt->execute();
                    $update_stmt->close();

                    // Regenerate session securely
                    secureSchoolSessionRegeneration();

                    // Set session variables
                    $_SESSION['emis_code'] = $user['emis_code'];
                    $_SESSION['school_name'] = $user['school_name'];
                    $_SESSION['cate_id'] = $user['cate_id'];
                    $_SESSION['level_id'] = $user['level_id'];

                    // Remember me cookie
                    if ($rememberMe) {
                        $cookieValue = json_encode([
                            'emis_code' => $emis_code,
                            'token' => bin2hex(random_bytes(16))
                        ]);
                        setcookie('remember_school', $cookieValue, time() + 86400 * 30, "/", "", true, true);
                    }

                    header("Location: school_dashboard.php");
                    exit();
                } else {
                    $message = 'Invalid EMIS Code or Password.';
                }
            } else {
                $message = 'Your account is Inactive. Please contact the Database Administrator.';
            }
        } else {
            $message = 'Institute not found in Database.';
        }
        $stmt->close();
    }
}

// Auto-login from remember me cookie
if (!isset($_SESSION['emis_code']) && isset($_COOKIE['remember_school'])) {
    $rememberData = json_decode($_COOKIE['remember_school'], true);
    if (json_last_error() === JSON_ERROR_NONE && isset($rememberData['emis_code'])) {
        $emis_code = $rememberData['emis_code'];

        $stmt = $conn->prepare("SELECT * FROM registrations WHERE emis_code = ?");
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            if ($user['status'] == 1) {
                $_SESSION['last_login'] = $user['last_login'];
                $_SESSION['emis_code'] = $user['emis_code'];
                $_SESSION['school_name'] = $user['school_name'];
                $_SESSION['cate_id'] = $user['cate_id'];
                $_SESSION['level_id'] = $user['level_id'];

                // Update last login
                $update_stmt = $conn->prepare("UPDATE registrations SET last_login = NOW() WHERE emis_code = ?");
                $update_stmt->bind_param("s", $emis_code);
                $update_stmt->execute();
                $update_stmt->close();

                header("Location: school_dashboard.php");
                exit();
            } else {
                $message = 'Your account is Inactive. Please contact the Database Administrator.';
            }
        }
        $stmt->close();
    }
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>School Login</title>
    <link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css">
    <style>
        :root {
            --primary: #3498db;
            --primary-dark: #2980b9;
            --secondary: #2c3e50;
            --light: #ecf0f1;
            --dark: #34495e;
            --success: #2ecc71;
            --warning: #f39c12;
            --danger: #e74c3c;
            --gray: #95a5a6;
            --light-gray: #f5f7fa;
            --border-radius: 8px;
            --box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, rgba(52, 152, 219, 0.85), rgba(46, 204, 113, 0.85)),
                        url('images/login_bg.jpg') center/cover no-repeat fixed;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .login-container {
            width: 100%;
            max-width: 450px;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }
        
        .login-header {
            background: var(--secondary);
            color: white;
            padding: 25px 30px;
            text-align: center;
        }
        
        .login-header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .login-header p {
            font-size: 16px;
            opacity: 0.8;
        }
        
        .login-body {
            padding: 30px;
        }
        
        .input-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--secondary);
            font-size: 14px;
        }
        
        .input-group input {
            width: 100%;
            padding: 14px 15px 14px 45px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 15px;
            transition: var(--transition);
        }
        
        .input-group input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
            outline: none;
        }
        
        .input-group i {
            position: absolute;
            left: 15px;
            top: 40px;
            color: var(--gray);
            font-size: 20px;
        }
        
        .options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            font-size: 14px;
        }
        
        .remember-me {
            display: flex;
            align-items: center;
        }
        
        .remember-me input {
            margin-right: 8px;
            accent-color: var(--primary);
        }
        
        .forgot-password {
            color: var(--primary);
            text-decoration: none;
            transition: var(--transition);
        }
        
        .forgot-password:hover {
            text-decoration: underline;
        }
        
        .btn {
            padding: 14px;
            border: none;
            border-radius: var(--border-radius);
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn-login {
            background: var(--primary);
            color: white;
            width: 100%;
            margin-bottom: 15px;
        }
        
        .btn-login:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
        }
        
        .btn-secondary {
            background: var(--light-gray);
            color: var(--secondary);
            border: 1px solid #ddd;
            flex: 1;
            margin-right: 10px;
        }
        
        .btn-secondary:hover {
            background: #eaeef2;
        }
        
        .btn-danger {
            background: var(--light-gray);
            color: var(--danger);
            border: 1px solid #ddd;
            flex: 1;
        }
        
        .btn-danger:hover {
            background: #fdecea;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .register-link {
            text-align: center;
            font-size: 15px;
            color: var(--secondary);
        }
        
        .register-link a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
            transition: var(--transition);
        }
        
        .register-link a:hover {
            text-decoration: underline;
        }
        
        .notification {
            padding: 12px 15px;
            margin-bottom: 20px;
            border-radius: var(--border-radius);
            background: #fdecea;
            color: var(--danger);
            font-size: 14px;
            display: none;
            border-left: 4px solid var(--danger);
        }
        
        .notification.success {
            background: #eafaf1;
            color: var(--success);
            border-left-color: var(--success);
        }
        
        .notification.info {
            background: #e8f4fd;
            color: var(--primary);
            border-left-color: var(--primary);
        }
        
        .password-strength {
            margin-top: 5px;
            font-size: 12px;
            display: none;
        }
        
        .password-strength.weak {
            color: var(--danger);
        }
        
        .password-strength.medium {
            color: var(--warning);
        }
        
        .password-strength.strong {
            color: var(--success);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        
        .shake {
            animation: shake 0.5s;
        }
        
        @media (max-width: 480px) {
            .login-container {
                margin: 0;
            }
            
            .login-body {
                padding: 25px;
            }
            
            .options {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .btn-secondary, .btn-danger {
                margin-right: 0;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <h1><i class='bx bxs-school header-icon'></i> <strong>School Portal</strong></h1>
            <p>Login with your School EMIS Code</p>
        </div>
        
        <div class="login-body">
            <div id="notification" class="notification"></div>
            
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return validateForm()">
                
                <!-- ✅ ADD CSRF TOKEN HERE (if you implement CSRF protection) -->
                <?php if (isset($_SESSION['csrf_token'])): ?>
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                <?php endif; ?>
    
                <div class="input-group">
                    <label for="emis_code">EMIS Code</label>
                    <i class='bx bxs-school'></i>
                    <input type="text" name="emis_code" id="emis_code" placeholder="Enter 11 digits EMIS Code" 
                           required maxlength="11" oninput="validateEmisCode()"
                           value="<?php 
                                if (isset($_COOKIE['remember_school'])) {
                                    $cookieData = json_decode($_COOKIE['remember_school'], true);
                                    if (json_last_error() === JSON_ERROR_NONE && isset($cookieData['emis_code'])) {
                                        echo htmlspecialchars($cookieData['emis_code']);
                                    }
                                }
                           ?>">
                </div>
                
                <div class="input-group">
                    <label for="password">Password</label>
                    <i class='bx bx-lock-alt'></i>
                    <input type="password" name="password" id="password" placeholder="Enter your password" required>
                    <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('password')" style="left: auto; right: 15px; cursor: pointer;"></i>
                </div>
                
                <div class="options">
                    <div class="remember-me">
                        <input type="checkbox" name="remember" id="remember" <?php echo $rememberMe ? 'checked' : ''; ?>>
                        <label for="remember">Remember me</label>
                    </div>
                    <a href="#" id="forgot-password-link">Forgot Password?</a>
                </div>
                
                <script>
                    document.getElementById('forgot-password-link').addEventListener('click', function(e) {
                        e.preventDefault();
                        var emisCode = document.getElementById('emis_code').value.trim();
                        
                        if (emisCode === '') {
                            showNotification('Please enter your EMIS Code first.', 'error');
                            return;
                        }
                        
                        if (!/^\d{11}$/.test(emisCode)) {
                            showNotification('Please enter a valid 11-digit EMIS Code first.', 'error');
                            return;
                        }
                        
                        // Redirect to forgot password page with EMIS code in query string
                        window.location.href = 'forgot_password_school.php?emis_code=' + encodeURIComponent(emisCode);
                    });
                </script>
                
                <button type="submit" class="btn btn-login">
                    <i class='bx bx-log-in' style="margin-right: 8px;"></i> Login
                </button>
                
                <div class="button-group">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        <i class='bx bx-reset' style="margin-right: 8px;"></i> Reset
                    </button>
                    <button type="button" class="btn btn-danger" onclick="cancelRegistration()">
                        <i class='bx bx-x' style="margin-right: 8px;"></i> Cancel
                    </button>
                </div>
                
                <div class="register-link">
                    New School OR Don't have an Account? <a href="register.php">Register here</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        function resetForm() {
            document.querySelector('form').reset();
            document.getElementById('notification').style.display = 'none';
            document.getElementById('emis_code').style.borderColor = '';
        }

        function cancelRegistration() {
            if (confirm('Are you sure you want to cancel?')) {
                window.location.href = 'index.php';
            }
        }
        
        // Show message if exists
        window.onload = function() {
            <?php if (!empty($message)): ?>
                showNotification('<?php echo $message; ?>', 'error');
            <?php endif; ?>
            
            // Auto-focus on EMIS code field
            document.getElementById('emis_code').focus();
            
            // Validate EMIS code on page load if there's a value
            var emisInput = document.getElementById('emis_code');
            if (emisInput.value) {
                validateEmisCode();
            }
        };

        function showNotification(message, type = 'error') {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification';
            
            if (type === 'success') {
                notification.classList.add('success');
            } else if (type === 'info') {
                notification.classList.add('info');
            }
            
            notification.style.display = 'block';
            
            // Hide after 5 seconds
            setTimeout(() => {
                notification.style.display = 'none';
            }, 5000);
        }

        function togglePasswordVisibility(fieldId) {
            var field = document.getElementById(fieldId);
            var icon = field.nextElementSibling;
            if (field.type === "password") {
                field.type = "text";
                icon.classList.remove('bx-show');
                icon.classList.add('bx-hide');
            } else {
                field.type = "password";
                icon.classList.remove('bx-hide');
                icon.classList.add('bx-show');
            }
        }

        function validateEmisCode() {
            var emisInput = document.getElementById('emis_code');
            var value = emisInput.value;
            
            // Remove all non-digit characters
            var digits = value.replace(/\D/g, '');
            
            // Only allow 11 digits
            if (digits.length > 11) {
                digits = digits.substring(0, 11);
            }
            
            // Update the input value
            emisInput.value = digits;
            
            // Add visual feedback for valid/invalid EMIS code
            if (digits.length === 11) {
                emisInput.style.borderColor = 'var(--success)';
            } else {
                emisInput.style.borderColor = '';
            }
        }

        function validateForm() {
            var emisCode = document.getElementById('emis_code').value;
            var password = document.getElementById('password').value;
            var isValid = true;

            // Validate EMIS code
            if (emisCode === '') {
                showNotification('Please enter your EMIS Code');
                document.getElementById('emis_code').classList.add('shake');
                setTimeout(() => {
                    document.getElementById('emis_code').classList.remove('shake');
                }, 500);
                isValid = false;
            } else if (!/^\d{11}$/.test(emisCode)) {
                showNotification('EMIS Code must be exactly 11 digits');
                document.getElementById('emis_code').classList.add('shake');
                setTimeout(() => {
                    document.getElementById('emis_code').classList.remove('shake');
                }, 500);
                isValid = false;
            }

            // Validate password
            if (password === '') {
                showNotification('Please enter your password');
                document.getElementById('password').classList.add('shake');
                setTimeout(() => {
                    document.getElementById('password').classList.remove('shake');
                }, 500);
                isValid = false;
            }

            return isValid;
        }
    </script>
</body>
</html>
<?php include 'visitor_counter.php'; ?>