<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/session.php';

function sanitizeLoginRedirect(string $redirect): string
{
    $redirect = trim($redirect);
    if ($redirect === '') {
        return 'staff-dashboard.php';
    }
    if (preg_match('/^[A-Za-z0-9._\/-]+(\?[A-Za-z0-9._~=&%-]*)?$/', $redirect) !== 1) {
        return 'staff-dashboard.php';
    }
    if (strpos($redirect, '://') !== false || strpos($redirect, '..') !== false) {
        return 'staff-dashboard.php';
    }
    return $redirect;
}

$authError = '';
$authSuccess = '';
$redirectAfterLogin = sanitizeLoginRedirect((string)($_REQUEST['redirect'] ?? 'staff-dashboard.php'));

if (isLoggedIn()) {
    $currentUser = getCurrentUser();
    if (isset($currentUser['user_type']) && $currentUser['user_type'] === 'staff') {
        header('Location: ' . $redirectAfterLogin);
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string)($_POST['staff_login_email'] ?? ''));
    $password = (string)($_POST['staff_login_password'] ?? '');

    if ($email === '' || $password === '') {
        $authError = 'Please enter both email and password.';
    } else {
        $stmt = $conn->prepare("SELECT id, first_name, last_name, email, password, user_type, is_active FROM users WHERE email = ? AND user_type = 'staff' LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result ? $result->fetch_assoc() : null;
            $stmt->close();

            if ($user && (int)$user['is_active'] === 1 && password_verify($password, $user['password'])) {
                loginUser((int)$user['id'], $user['email'], $user['first_name'], $user['last_name'], $user['user_type']);

                $updateLogin = $conn->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                if ($updateLogin) {
                    $userId = (int)$user['id'];
                    $updateLogin->bind_param('i', $userId);
                    $updateLogin->execute();
                    $updateLogin->close();
                }

                header('Location: ' . $redirectAfterLogin);
                exit();
            } else {
                $authError = 'Invalid email or password. Staff access only.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Staff Login | zemaraim Hotel Management</title>
    <link rel="icon" href="images/icon.webp" type="image/gif" sizes="16x16">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Staff login for zemaraim hotel management system.">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="css/plugins.css" rel="stylesheet" type="text/css">
    <link href="css/style.css" rel="stylesheet" type="text/css">
    <link href="css/coloring.css" rel="stylesheet" type="text/css">
    <link href="css/staff-login.css" rel="stylesheet" type="text/css">
    <link id="colors" href="css/colors/scheme-01.css" rel="stylesheet" type="text/css">
</head>

<body class="light">
    <div class="staff-login-section">
        <div class="staff-login-background"></div>

        <div class="container">
            <div class="row justify-content-center align-items-center min-vh-100">
                <div class="col-12 col-sm-10 col-md-8 col-lg-5">
                    <div class="staff-login-card">
                        <!-- Logo and Title -->
                        <div class="staff-login-header text-center mb-4">
                            <div class="login-logo-wrapper mb-3">
                                <img src="images/icon.webp" alt="zemaraim Logo" class="staff-login-logo">
                            </div>
                            <h1 class="staff-login-title">Staff Portal</h1>
                            <p class="staff-login-subtitle">zemaraim Hotel Management</p>
                        </div>

                        <!-- Error Message -->
                        <?php if ($authError): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="icofont-close-circled"></i> <?php echo htmlspecialchars($authError); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php endif; ?>

                        <!-- Login Form -->
                        <form method="POST" action="" class="staff-login-form">
                            <div class="form-group mb-4">
                                <label for="staff_login_email" class="form-label">
                                    <i class="icofont-envelope"></i> Email Address
                                </label>
                                <input type="email" id="staff_login_email" name="staff_login_email" class="form-control form-control-lg" placeholder="Enter your email" required autofocus>
                            </div>

                            <div class="form-group mb-4">
                                <label for="staff_login_password" class="form-label">
                                    <i class="icofont-lock"></i> Password
                                </label>
                                <input type="password" id="staff_login_password" name="staff_login_password" class="form-control form-control-lg" placeholder="Enter your password" required>
                            </div>

                            <button type="submit" class="btn btn-staff-primary btn-lg w-100 mb-3">
                                <i class="icofont-login"></i> Sign In
                            </button>
                        </form>

                        <!-- Footer Links -->
                        <div class="staff-login-footer text-center">
                            <p class="mb-2">
                                <a href="forgot-password.php" class="staff-link">Forgot Password?</a>
                            </p>
                            <hr class="my-3">
                            <p class="mb-0">
                                <small>Guest Account?</small><br>
                                <a href="login.php" class="staff-link-secondary">Go to Guest Login</a>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script>
        // Auto-focus on email field
        document.getElementById('staff_login_email').focus();

        // Smooth fade-in animation
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('.staff-login-card').style.animation = 'fadeInUp 0.6s ease-out';
        });
    </script>
</body>

</html>
