<?php
session_start();

// If user is already logged in, redirect to index_login.php
if (isset($_SESSION['username'])) {
    header("Location: index_login.php");
    exit();
}

// Database connection details
include_once 'connect.php';

$message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $emis_code = $_POST['emis_code'];
    $password = $_POST['password'];

    // 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 {
        // Prepare and bind
        $stmt = $conn->prepare("SELECT * FROM registrations WHERE emis_code = ?");
        $stmt->bind_param("s", $emis_code);

        // Execute and store result
        $stmt->execute();
        $result = $stmt->get_result();

        // Check if user exists
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            // Verify password
            if (password_verify($password, $user['password'])) {
                $_SESSION['username'] = $user['school_name'];  // Store school name in session
                header("Location: index_login.php?welcome=" . urlencode($user['school_name']));
                exit();
            } else {
                $message = 'Invalid EMIS Code or Password.';
            }
        } else {
            $message = 'Invalid EMIS Code or Password.';
        }

        $stmt->close();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
        }

        .wrapper {
            width: 420px;
            background: rgba(255, 255, 255, 0.8);
            border: 2px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(20px);
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
            color: #333;
            border-radius: 10px;
            padding: 30px 40px;
        }

        .wrapper h1 {
            font-size: 50px;
            text-align: center;
        }

        .input-box {
            position: relative;
            margin-bottom: 20px;
        }

        .input-box input {
            width: 100%;
            height: 45px;
            background: transparent;
            border: 2px solid rgba(0, 0, 0, .2);
            border-radius: 40px;
            font-size: 16px;
            color: #333;
            padding: 0 40px 0 20px;
            box-sizing: border-box;
        }

        .input-box input::placeholder {
            color: #999;
        }

        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #666;
            display: flex;
            align-items: center;
        }

        .toggle-password .bx {
            font-size: 20px;
        }

        .input-box input:focus, 
        .btn:focus {
            border-color: #4361ee;
            box-shadow: 0 0 5px #4361ee;
            outline: none;
        }

        .remember-forget {
            display: flex;
            justify-content: space-between;
            font-size: 14.5px;
            margin-bottom: 15px;
        }

        .remember-forget label input {
            margin-right: 3px;
        }

        .remember-forget a {
            color: #666;
            text-decoration: none;
        }

        .remember-forget a:hover {
            text-decoration: underline;
        }

        .btn {
            width: 100%;
            height: 45px;
            background: #4361ee;
            border: none;
            outline: none;
            border-radius: 40px;
            box-shadow: 0 0 10px rgba(0, 0, 0, .1);
            cursor: pointer;
            font-size: 16px;
            color: #fff;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .register-link {
            font-size: 14.5px;
            text-align: center;
            margin-top: 15px;
        }

        .register-link p a {
            color: #4361ee;
            text-decoration: none;
            font-weight: 600;
        }

        .register-link p a:hover {
            text-decoration: underline;
        }
    </style>
	
	<link rel="stylesheet" href="login.css">
	<link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css">
	
</head>
<body>
    <div class="wrapper">
        <form action="login.php" method="post" onsubmit="return validateForm()">
            <h1>LOGIN</h1>
            <div class="input-box">
                <input type="text" name="emis_code" id="emis_code" placeholder="Enter School EMIS Code" required pattern="\d{11}" maxlength="11" oninput="validateEmisCode()" tabindex="1">
            </div>
            <div class="input-box">
                <input type="password" name="password" id="password" placeholder="Enter Password" required tabindex="2">
                <div class="toggle-password" onclick="togglePasswordVisibility('password')">
                    <i class='bx bx-show'></i>
                </div>
            </div>
            <div class="remember-forget">
                <label><input type="checkbox" tabindex="3">Remember me</label>
                <a href="#" tabindex="4">Forgot Password?</a>
            </div>
            <button type="submit" class="btn" tabindex="5">Login</button>
            <button type="button" class="btn" onclick="resetForm()" tabindex="6">Reset</button>
            <button type="button" class="btn" onclick="cancelRegistration()" tabindex="7">Cancel</button>
            <div class="register-link">
                <p>Don't have an account? <a href="register.php" tabindex="8">Register</a></p>
            </div>
            <?php if (!empty($message)) : ?>
                <script>
                    alert('<?php echo $message; ?>');
                </script>
            <?php endif; ?>
        </form>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            function resetForm() {
                document.querySelector('form').reset();
            }

            function cancelRegistration() {
                window.location.href = 'index.php';
            }

            function togglePasswordVisibility(fieldId) {
                var field = document.getElementById(fieldId);
                var icon = field.nextElementSibling.querySelector('.bx');
                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 validateForm() {
                var emisCode = document.getElementById('emis_code').value;
                var password = document.getElementById('password').value;

                if (emisCode === '') {
                    alert('Please enter the EMIS Code.');
                    return false;
                }

                if (password === '') {
                    alert('Please enter the password.');
                    return false;
                }

                if (emisCode.length !== 11 || !/^\d{11}$/.test(emisCode)) {
                    alert('EMIS Code must be exactly 11 digits.');
                    return false;
                }

                return true;
            }

            function validateEmisCode() {
                var emisCodeInput = document.getElementById('emis_code');
                var value = emisCodeInput.value;
                emisCodeInput.value = value.replace(/\D/g, '');
            }

            window.resetForm = resetForm;
            window.cancelRegistration = cancelRegistration;
            window.togglePasswordVisibility = togglePasswordVisibility;
            window.validateForm = validateForm;
            window.validateEmisCode = validateEmisCode;
        });
    </script>
</body>
</html>
