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

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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string)($_POST['admin_login_email'] ?? ''));
    $password = (string)($_POST['admin_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 IN ('admin', '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. Admin access only.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Admin 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="Admin 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 id="colors" href="css/colors/scheme-01.css" rel="stylesheet" type="text/css">
    <link href="css/admin-login.css" rel="stylesheet" type="text/css">
</head>

<body>
    <div id="wrapper">
        <a href="#" id="back-to-top"></a>
        <div id="de-loader"></div>

        <section class="admin-login-section">
            <div class="admin-login-background">
                <div class="admin-login-overlay"></div>
            </div>
            
            <div class="admin-login-container">
                <div class="admin-login-box">
                    <!-- Admin Logo Section -->
                    <div class="admin-login-header">
                        <div class="admin-logo-badge">
                            <i class="fa fa-shield"></i>
                        </div>
                        <h1 class="admin-login-title">Admin Portal</h1>
                        <p class="admin-login-subtitle">Zemaraim Hotel Management System</p>
                    </div>

                    <!-- Error/Success Messages -->
                    <?php if ($authError !== ''): ?>
                        <div class="admin-alert alert-danger">
                            <i class="fa fa-exclamation-circle"></i>
                            <?php echo htmlspecialchars($authError, ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                    <?php endif; ?>
                    <?php if ($authSuccess !== ''): ?>
                        <div class="admin-alert alert-success">
                            <i class="fa fa-check-circle"></i>
                            <?php echo htmlspecialchars($authSuccess, ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                    <?php endif; ?>

                    <!-- Login Form -->
                    <form class="admin-login-form" action="" method="post">
                        <div class="form-group">
                            <label for="admin_email" class="form-label">
                                <i class="fa fa-envelope"></i> Email Address
                            </label>
                            <input 
                                type="email" 
                                id="admin_email"
                                name="admin_login_email" 
                                class="form-control" 
                                placeholder="Enter your admin email"
                                required
                                autofocus
                            >
                        </div>

                        <div class="form-group">
                            <label for="admin_password" class="form-label">
                                <i class="fa fa-lock"></i> Password
                            </label>
                            <input 
                                type="password" 
                                id="admin_password"
                                name="admin_login_password" 
                                class="form-control" 
                                placeholder="Enter your password"
                                required
                            >
                        </div>

                        <div class="form-group admin-form-meta">
                            <label class="form-checkbox">
                                <input type="checkbox" name="remember_me">
                                <span>Remember me</span>
                            </label>
                            <a href="forgot-password.php" class="forgot-link">Forgot password?</a>
                        </div>

                        <button type="submit" class="admin-login-btn">
                            <span>Sign In to Admin Panel</span>
                            <i class="fa fa-arrow-right"></i>
                        </button>
                    </form>

                    <!-- Support Section -->
                    <div class="admin-login-footer">
                        <p>Need help? <a href="contact.php">Contact Support</a></p>
                        <p>Return to <a href="index.php">Main Website</a></p>
                    </div>
                </div>

                <!-- Side Info -->
                <div class="admin-login-info">
                    <div class="info-card">
                        <div class="info-icon"><i class="fa fa-chart-bar"></i></div>
                        <h3>Real-time Analytics</h3>
                        <p>Monitor bookings and revenue in real-time</p>
                    </div>
                    <div class="info-card">
                        <div class="info-icon"><i class="fa fa-users"></i></div>
                        <h3>Guest Management</h3>
                        <p>Manage guests and their reservations</p>
                    </div>
                    <div class="info-card">
                        <div class="info-icon"><i class="fa fa-building"></i></div>
                        <h3>Room Control</h3>
                        <p>Manage rooms and availability</p>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <script src="js/plugins.js"></script>
    <script src="js/designesia.js"></script>
    <script src="js/admin-login.js"></script>
</body>

</html>
