<?php
session_start();
include_once 'connect.php';

$message = '';
$rememberMe = false;

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

    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 {
        $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'])) {
                    $_SESSION['user'] = [
                        'username' => $emis_code,
                        'emis_code' => $emis_code,
                        'school_name' => $user['school_name'],
                        'cate_id' => $user['cate_id'],
                        'level_id' => $user['level_id']
                    ];

                    if ($rememberMe) {
                        setcookie('remember', json_encode(['emis_code' => $emis_code]), time()+86400*30, "/", "", true, true);
                    }

                    header("Location: dashboard_school.php");
                    exit();
                } else {
                    $message = 'Invalid credentials.';
                }
            } else {
                $message = 'Account inactive. Contact administrator.';
            }
        } else {
            $message = 'User not found.';
        }
        $stmt->close();
    }
}

if (empty($_SESSION['user']) && isset($_COOKIE['remember'])) {
    $rememberData = json_decode($_COOKIE['remember'], true);
    if ($rememberData && isset($rememberData['emis_code'])) {
        $stmt = $conn->prepare("SELECT * FROM registrations WHERE emis_code = ?");
        $stmt->bind_param("s", $rememberData['emis_code']);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            if ($user['status'] == 1) {
                $_SESSION['user'] = [
                    'username' => $user['emis_code'],
                    'emis_code' => $user['emis_code'],
                    'school_name' => $user['school_name'],
                    'cate_id' => $user['cate_id'],
                    'level_id' => $user['level_id']
                ];
                header("Location: dashboard_school.php");
                exit();
            }
        }
        $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>School Management System | Login</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3498db;
            --secondary: #2c3e50;
            --light: #ecf0f1;
            --dark: #34495e;
        }
        
        * {
            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.8), rgba(46, 204, 113, 0.8)),
                        url('https://images.unsplash.com/photo-1523050854058-8df90110c9f1') center/cover no-repeat fixed;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .login-container {
            width: 100%;
            max-width: 400px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            padding: 40px;
            text-align: center;
            animation: fadeIn 0.5s ease-out;
        }
        
        .logo {
            margin-bottom: 30px;
            color: var(--secondary);
        }
        
        .logo h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .logo p {
            font-size: 16px;
            color: #7f8c8d;
        }
        
        .input-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        .input-group input {
            width: 100%;
            padding: 12px 15px 12px 40px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .input-group input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .input-group i {
            position: absolute;
            left: 15px;
            top: 13px;
            color: #7f8c8d;
        }
        
        .options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .remember-me {
            display: flex;
            align-items: center;
        }
        
        .remember-me input {
            margin-right: 8px;
        }
        
        .forgot-password {
            color: var(--primary);
            text-decoration: none;
        }
        
        .btn {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-login {
            background: var(--primary);
            color: white;
            margin-bottom: 15px;
        }
        
        .btn-login:hover {
            background: #2980b9;
        }
        
        .register-link {
            margin-top: 20px;
            font-size: 14px;
        }
        
        .register-link a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        
        .notification {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 5px;
            background: #fdecea;
            color: #e74c3c;
            font-size: 14px;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @media (max-width: 480px) {
            .login-container {
                margin: 20px;
                padding: 30px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <h1>School Management</h1>
            <p>System Login</p>
        </div>
        
        <?php if (!empty($message)): ?>
            <div class="notification">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
      <form method="post">
            <div class="input-group">
                <i class="fas fa-school"></i>
                <input type="text" name="emis_code" placeholder="EMIS Code (11 digits)" 
       value="<?php echo isset($_COOKIE['remember']) ? htmlspecialchars(json_decode($_COOKIE['remember'], true)['emis_code'] ?? '') : ''; ?>"
       required pattern="\d{11}" maxlength="11" oninput="this.value=this.value.replace(/\D/g,'')">
                
            </div>
            
            <div class="input-group">
                <i class="fas fa-lock"></i>
                <input type="password" name="password" placeholder="Password" required>
                <i class="fas fa-eye toggle-password" onclick="togglePassword(this)"></i>
            </div>
            
        <div class="options">
                <label class="remember-me">
                    <input type="checkbox" name="remember" <?php echo $rememberMe ? 'checked' : ''; ?>> Remember me
          </label>
                <a href="forgot-password.php" class="forgot-password">Forgot Password?</a>
            </div>
            
            <button type="submit" class="btn btn-login">LOGIN</button>
            
            <div class="register-link">
                Don't have an account? <a href="register.php">Register</a>
            </div>
        </form>
    </div>

    <script>
        function togglePassword(icon) {
            const input = icon.previousElementSibling;
            if (input.type === "password") {
                input.type = "text";
                icon.classList.replace('fa-eye', 'fa-eye-slash');
            } else {
                input.type = "password";
                icon.classList.replace('fa-eye-slash', 'fa-eye');
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('input[name="emis_code"]').focus();
        });
    </script>
</body>
</html>