<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require 'config.php';

$message = '';

// Release the session lock on plain page views (just showing the login form);
// the POST branch below still needs to write session data on successful auth,
// so it keeps the session open for itself.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username === '' || $password === '') {
        $message = "Please fill all fields!";
    } else {
        $stmt = $conn->prepare("
            SELECT id, username, password, role, department_id, must_change_password, can_add_staff
            FROM users
            WHERE username=?
            LIMIT 1
        ");

        $stmt->bind_param("s", $username);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows === 1) {
            $user = $res->fetch_assoc();

            if (password_verify($password, $user['password'])) {
                session_regenerate_id(true);

                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = strtolower(trim($user['role']));
                $_SESSION['department_id'] = $user['department_id'];
                $_SESSION['can_add_staff'] = $user['can_add_staff'];

                if (!empty($user['must_change_password']) && $user['must_change_password'] == 1) {
                    $_SESSION['force_change'] = true;
                    header("Location: change_password.php");
                    exit;
                }

                $role = $_SESSION['role'];
                $redirectMap = [
                    'staff'      => 'ess/dashboard.php',
                    'manager'    => 'ess/dashboard.php',
                    'hr'         => 'dashboard.php',
                    'admin'      => 'dashboard.php',
                    'supervisor' => 'ess/dashboard.php',
                ];

                if (isset($redirectMap[$role])) {
                    header("Location: " . $redirectMap[$role]);
                } else {
                    header("Location: dashboard.php");
                }
                exit;

            } else {
                $message = "Oops! That's an incorrect password. Please try again.";
            }
        } else {
            $message = "We couldn't find a user with that username.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome Back - HR System</title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,400&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: 'Mulish', sans-serif;
        }

        /* 80% Zoom Simulation Engine */
        .zoom-wrapper {
            transform: scale(0.8);
            transform-origin: center center;
            width: 125%;  /* Compensates width (100 / 0.8) */
            height: 125%; /* Compensates height (100 / 0.8) */
        }

        @keyframes pulse-slow {
            0%, 100% { transform: scale(1) translate(0px, 0px); }
            50% { transform: scale(1.08) translate(10px, -15px); }
        }

        .ambient-blur {
            animation: pulse-slow 8s ease-in-out infinite;
        }
    </style>
</head>
<body class="h-screen bg-slate-950 overflow-hidden relative selection:bg-indigo-500 selection:text-white flex items-center justify-center">

    <div class="absolute inset-0 overflow-hidden pointer-events-none">
        <div class="ambient-blur absolute top-[-10%] left-[-10%] w-[40vw] h-[40vw] min-w-[350px] bg-gradient-to-br from-indigo-600/35 to-purple-600/0 rounded-full blur-[120px]"></div>
        <div class="ambient-blur absolute bottom-[-15%] right-[-5%] w-[45vw] h-[45vw] min-w-[400px] bg-gradient-to-tr from-emerald-500/20 to-blue-600/0 rounded-full blur-[140px]" style="animation-delay: 3s;"></div>
    </div>

    <div class="zoom-wrapper flex items-center justify-center p-4 sm:p-6">
        
        <div class="w-full max-w-[440px] bg-slate-900/40 backdrop-blur-xl border border-slate-800/80 rounded-[32px] shadow-[0_25px_70px_-15px_rgba(0,0,0,0.7)] overflow-hidden transition-all duration-300">
            
            <div class="p-8 sm:p-10">
                
                <div class="mb-8">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-tr from-indigo-600 to-violet-500 flex items-center justify-center text-white shadow-xl shadow-indigo-600/20">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                        </svg>
                    </div>
                </div>

                <div class="space-y-2 mb-8">
                    <h1 class="text-2xl sm:text-3xl font-black tracking-tight text-white">
                        Welcome back
                    </h1>
                    <p class="text-slate-400 text-sm font-medium tracking-wide">
                        Enter your credentials to manage workforce platforms.
                    </p>
                </div>

                <?php if ($message): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-300 p-4 rounded-2xl mb-6 text-xs flex items-center gap-3">
                    <svg class="w-4 h-4 text-rose-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                    </svg>
                    <span class="font-semibold tracking-wide"><?= htmlspecialchars($message); ?></span>
                </div>
                <?php endif; ?>

                <form method="POST" class="space-y-5">
                    
                    <div class="space-y-2">
                        <label class="block text-xs font-bold uppercase tracking-widest text-slate-400 pl-0.5">
                            Username
                        </label>
                        <div class="relative">
                            <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                </svg>
                            </span>
                            <input
                                type="text"
                                name="username"
                                placeholder="e.g., alex_smith"
                                required
                                class="w-full pl-12 pr-4 py-3.5 rounded-2xl border border-slate-800 bg-slate-950/40 focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/80 focus:bg-slate-950 outline-none transition duration-150 text-sm text-slate-200 placeholder-slate-600 shadow-inner">
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="block text-xs font-bold uppercase tracking-widest text-slate-400 pl-0.5">
                            Password
                        </label>
                        <div class="relative">
                            <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                                </svg>
                            </span>
                            <input
                                type="password"
                                name="password"
                                placeholder="••••••••••••"
                                required
                                class="w-full pl-12 pr-4 py-3.5 rounded-2xl border border-slate-800 bg-slate-950/40 focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/80 focus:bg-slate-950 outline-none transition duration-150 text-sm text-slate-200 placeholder-slate-700 shadow-inner">
                        </div>
                    </div>

                    <div class="pt-2">
                        <button
                            type="submit"
                            class="w-full bg-indigo-600 hover:bg-indigo-500 text-white py-4 rounded-2xl font-bold text-sm tracking-wide shadow-xl shadow-indigo-600/10 active:scale-[0.99] transform transition duration-150 focus:outline-none focus:ring-4 focus:ring-indigo-500/20">
                            Sign In
                        </button>
                    </div>

                </form>

                <div class="mt-8 pt-6 border-t border-slate-800/60 text-center text-[11px] font-bold tracking-widest uppercase text-slate-500 flex items-center justify-center gap-2">
                    <svg class="w-3.5 h-3.5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                    </svg>
                    Secure HR Attendance Platform
                </div>

            </div>

        </div>
    </div>

</body>
</html>