<?php

if (session_status() === PHP_SESSION_NONE) {
    session_name('PIONEERS_PMS_SESSION');

    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/rooms/',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    session_start();
}
require_once __DIR__ . '/includes/database_connection.php';
require_once __DIR__ . '/includes/functions.php';

/**
 * Resolve the post-login landing page for a role.
 *
 * Reads roles.landing_page (set on the Role Permissions page). Returns a path
 * relative to the app root WITHOUT a leading slash, to match how this app's
 * redirects work (e.g. "modules/restaurant/planner.php"). Falls back to the
 * calendar when no valid landing page is configured.
 */
 /* Zimbabwe local time for PHP output, receipts and PrintNode payload text. */
date_default_timezone_set('Africa/Harare');
try {
    /* Zimbabwe is UTC+02:00 throughout the year. */
    $pdo->exec("SET time_zone = '+02:00'");
} catch (Throwable $e) {
    /* PHP date/time output still remains correctly set to Africa/Harare. */
}
if (!function_exists('login_landing_for_role')) {
    function login_landing_for_role(PDO $pdo, string $roleKey): string {
        $fallback = 'modules/calendar/calendar.php';
        $roleKey = strtolower(trim($roleKey));
        if ($roleKey === '') return $fallback;

        try {
            // Only query if the column exists (older DBs won't have it yet).
            $col = $pdo->query("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='roles' AND column_name='landing_page'")->fetchColumn();
            if ((int)$col === 0) return $fallback;

            $stmt = $pdo->prepare("SELECT landing_page FROM roles WHERE role_key=:k AND COALESCE(is_active,1)=1 LIMIT 1");
            $stmt->execute([':k' => $roleKey]);
            $path = (string)($stmt->fetchColumn() ?: '');
            $path = trim($path);
            if ($path === '') return $fallback;

            // Must be a site-relative path, no scheme, no protocol-relative "//".
            if (!preg_match('#^/?[A-Za-z0-9_\-/\.]+$#', $path) || strpos($path, '//') !== false) {
                return $fallback;
            }
            // Normalise to a root-relative path (strip a single leading slash).
            return ltrim($path, '/');
        } catch (Throwable $e) {
            return $fallback;
        }
    }
}

if (!empty($_SESSION['ss_user_id'])) {
    $existingRole = (string)($_SESSION['role_key'] ?? $_SESSION['role'] ?? '');
    header('Location: ' . login_landing_for_role($pdo, $existingRole));
    exit;
}

$error = '';
$appName = app_setting($pdo, 'name', 'RoomZ PMS');

$rememberedUsername = '';
if (!empty($_COOKIE['ss_remember_username'])) {
    $rememberedUsername = trim((string)$_COOKIE['ss_remember_username']);
}

/* Active users for the login dropdown, alphabetical by display name. */
$activeUsers = [];
try {
    $activeUsers = $pdo->query("
        SELECT username,
               TRIM(CONCAT(COALESCE(firstname,''), ' ', COALESCE(lastname,''))) AS full_name
        FROM users
        WHERE active = 1 AND username IS NOT NULL AND username <> ''
        ORDER BY full_name ASC, username ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $activeUsers = [];
}

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

    if ($username === '' || $password === '') {
        $error = 'Please enter both username and password.';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE (username = :username OR email = :email) LIMIT 1");
        $stmt->execute([
            ':username' => $username,
            ':email' => $username
        ]);
        $user = $stmt->fetch();

        if (!$user) {
            $error = 'Invalid login details.';
        } elseif ((int)$user['active'] !== 1) {
            $error = 'This account is not active.';
        } else {
            $stored = (string)$user['password'];
            $ok = false;

            if ($stored !== '' && strlen($stored) === 40 && ctype_xdigit($stored)) {
                $ok = (sha1($password) === strtolower($stored));

                if ($ok) {
                    $newHash = password_hash($password, PASSWORD_DEFAULT);
                    $upgrade = $pdo->prepare("UPDATE users SET password = :p WHERE id = :id");
                    $upgrade->execute([
                        ':p' => $newHash,
                        ':id' => (int)$user['id']
                    ]);
                }
            } else {
                $ok = password_verify($password, $stored);
            }

            if (!$ok) {
                $error = 'Invalid login details.';
            } else {
                session_regenerate_id(true);

                $_SESSION['ss_user_id'] = (int)$user['id'];
                $_SESSION['user_id'] = (int)$user['id'];
                $_SESSION['ss_username'] = trim(($user['firstname'] ?? '') . ' ' . ($user['lastname'] ?? ''));

                /*
                 * Role handling:
                 * - user_role remains as the old integer for legacy pages.
                 * - role_key / role / user_role_key store the new dynamic role from the roles table.
                 * This allows custom roles like barman to work with role_permissions and sidebar menus.
                 */
                $userRoleInt = (int)($user['user_role'] ?? 10);

                $legacyRoleMap = [
                    1 => 'super_admin',
                    2 => 'admin',
                    3 => 'manager',
                    4 => 'frontdesk',
                    5 => 'cashier',
                    6 => 'stores',
                    7 => 'accounts',
                    8 => 'housekeeping',
                    9 => 'owner',
                    10 => 'user',
                ];

                $roleKey = strtolower(trim((string)($user['role_key'] ?? '')));
                if ($roleKey === '') {
                    $roleKey = $legacyRoleMap[$userRoleInt] ?? 'user';
                }

                $roleKey = preg_replace('/[^a-z0-9_]/', '_', $roleKey);
                $roleKey = trim(preg_replace('/_+/', '_', $roleKey), '_');
                if ($roleKey === '') {
                    $roleKey = 'user';
                }

                $_SESSION['ss_role_id'] = $userRoleInt;
                $_SESSION['user_role'] = $userRoleInt;
                $_SESSION['type'] = $userRoleInt; // keep legacy integer behavior
                $_SESSION['role'] = $roleKey;
                $_SESSION['role_key'] = $roleKey;
                $_SESSION['user_role_key'] = $roleKey;
                $_SESSION['ss_role_key'] = $roleKey;
                if ($rememberMe) {
                    $expire = time() + (86400 * 30);

                    setcookie('ss_remember_username', $username, [
                        'expires' => $expire,
                        'path' => '/',
                        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
                        'httponly' => true,
                        'samesite' => 'Lax',
                    ]);

                    setcookie(session_name(), session_id(), [
                        'expires' => $expire,
                        'path' => '/',
                        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
                        'httponly' => true,
                        'samesite' => 'Lax',
                    ]);
                } else {
                    setcookie('ss_remember_username', '', [
                        'expires' => time() - 3600,
                        'path' => '/',
                        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
                        'httponly' => true,
                        'samesite' => 'Lax',
                    ]);
                }

                header('Location: ' . login_landing_for_role($pdo, $roleKey));
                exit;
            }
        }
    }

    $rememberedUsername = $username;
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Login | <?php echo e($appName); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

    <style>
        :root {
            --brand: #2563eb;
            --brand-2: #38bdf8;
            --ink: #0f172a;
            --muted: #64748b;
            --glass: rgba(255,255,255,.72);
            --glass-border: rgba(255,255,255,.56);
            --field-bg: rgba(255,255,255,.82);
        }

        body.dark-login {
            --ink: #e5e7eb;
            --muted: #94a3b8;
            --glass: rgba(15,23,42,.72);
            --glass-border: rgba(148,163,184,.26);
            --field-bg: rgba(15,23,42,.76);
        }

        * {
            box-sizing: border-box;
        }

        body.login-body {
            margin: 0;
            min-height: 100vh;
            font-family: 'Inter', system-ui, sans-serif;
            color: var(--ink);
            background: #020617;
            overflow-x: hidden;
        }

        .login-page {
            min-height: 100vh;
            display: grid;
            grid-template-columns: minmax(0, 1.18fr) minmax(420px, .82fr);
            position: relative;
        }

        .image-side {
            position: relative;
            min-height: 100vh;
            overflow: hidden;
            background-size: cover;
            background-position: center;
            animation: lodgeImages 24s infinite ease-in-out;
        }

        @keyframes lodgeImages {
            0%, 30% {
                background-image:
                    linear-gradient(135deg, rgba(2,6,23,.42), rgba(15,23,42,.72)),
                    url('assets/img/lodge-login-1.jpg');
            }
            35%, 65% {
                background-image:
                    linear-gradient(135deg, rgba(2,6,23,.42), rgba(15,23,42,.72)),
                    url('assets/img/lodge-login-2.jpeg');
            }
            70%, 100% {
                background-image:
                    linear-gradient(135deg, rgba(2,6,23,.42), rgba(15,23,42,.72)),
                    url('assets/img/lodge-login-3.jpeg');
            }
        }

        .image-side::before {
            content: "";
            position: absolute;
            inset: 0;
            background:
                radial-gradient(circle at 25% 18%, rgba(37,99,235,.32), transparent 28%),
                radial-gradient(circle at 75% 75%, rgba(56,189,248,.20), transparent 32%);
        }

        .image-content {
            position: relative;
            z-index: 2;
            min-height: 100vh;
            padding: 4rem;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            color: #fff;
        }

        .logo-glass {
            width: fit-content;
            min-width: 190px;
            max-width: 280px;
            padding: .9rem 1.1rem;
            border-radius: 26px;
            background: rgba(255,255,255,.90);
            border: 1px solid rgba(255,255,255,.55);
            box-shadow: 0 28px 80px rgba(0,0,0,.22);
            backdrop-filter: blur(18px);
        }

        .logo-glass img {
            max-width: 230px;
            max-height: 62px;
            object-fit: contain;
            display: block;
        }

        .hero-copy {
            max-width: 760px;
        }

        .hero-copy .pill {
            display: inline-flex;
            align-items: center;
            gap: .45rem;
            padding: .5rem .8rem;
            border-radius: 999px;
            background: rgba(255,255,255,.13);
            border: 1px solid rgba(255,255,255,.18);
            backdrop-filter: blur(16px);
            font-size: .78rem;
            font-weight: 800;
            letter-spacing: .08em;
            text-transform: uppercase;
            margin-bottom: 1.2rem;
        }

        .hero-copy h1 {
            font-size: clamp(3rem, 5.4vw, 5.8rem);
            line-height: .93;
            letter-spacing: -.07em;
            font-weight: 900;
            margin: 0 0 1.2rem;
        }

        .hero-copy p {
            max-width: 650px;
            color: rgba(255,255,255,.82);
            font-size: 1.1rem;
            line-height: 1.75;
        }

        .hero-stats {
            display: flex;
            flex-wrap: wrap;
            gap: .8rem;
            margin-top: 1.7rem;
        }

        .hero-stat {
            padding: .75rem .95rem;
            border-radius: 18px;
            background: rgba(255,255,255,.12);
            border: 1px solid rgba(255,255,255,.16);
            backdrop-filter: blur(16px);
            min-width: 145px;
        }

        .hero-stat strong {
            display: block;
            font-size: 1.05rem;
            font-weight: 900;
        }

        .hero-stat small {
            color: rgba(255,255,255,.68);
            font-weight: 600;
        }

        .form-side {
            position: relative;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
            background:
                radial-gradient(circle at top right, rgba(37,99,235,.17), transparent 34%),
                radial-gradient(circle at bottom left, rgba(56,189,248,.16), transparent 30%),
                linear-gradient(135deg, #f8fafc, #eef2f7);
        }

        body.dark-login .form-side {
            background:
                radial-gradient(circle at top right, rgba(37,99,235,.24), transparent 34%),
                radial-gradient(circle at bottom left, rgba(56,189,248,.14), transparent 30%),
                linear-gradient(135deg, #020617, #0f172a);
        }

        .theme-toggle {
            position: absolute;
            top: 1.4rem;
            right: 1.4rem;
            border: 1px solid rgba(148,163,184,.28);
            background: var(--glass);
            color: var(--ink);
            backdrop-filter: blur(18px);
            border-radius: 999px;
            padding: .55rem .85rem;
            font-weight: 800;
            font-size: .82rem;
            box-shadow: 0 18px 40px rgba(15,23,42,.12);
        }

        .login-card {
            width: 100%;
            max-width: 470px;
            border-radius: 34px;
            background: var(--glass);
            border: 1px solid var(--glass-border);
            backdrop-filter: blur(26px);
            -webkit-backdrop-filter: blur(26px);
            box-shadow: 0 35px 90px rgba(15,23,42,.20);
            overflow: hidden;
        }

        .login-card-inner {
            padding: 2.2rem;
        }

        .form-logo {
            width: fit-content;
            min-width: 145px;
            max-width: 210px;
            min-height: 62px;
            padding: .7rem .9rem;
            border-radius: 22px;
            background: rgba(255,255,255,.92);
            border: 1px solid rgba(226,232,240,.9);
            box-shadow: 0 18px 40px rgba(37,99,235,.14);
            margin-bottom: 1.25rem;
        }

        .form-logo img {
            max-width: 170px;
            max-height: 50px;
            object-fit: contain;
            display: block;
        }

        .login-card h2 {
            font-weight: 900;
            font-size: 2.1rem;
            letter-spacing: -.05em;
            margin-bottom: .35rem;
        }

        .login-card .subtitle {
            color: var(--muted);
            margin-bottom: 1.4rem;
            font-weight: 500;
        }

        .form-label {
            font-size: .78rem;
            font-weight: 900;
            color: var(--ink);
            margin-bottom: .45rem;
        }

        .input-group {
            border-radius: 18px;
            box-shadow: 0 12px 28px rgba(15,23,42,.06);
        }

        .input-group-text {
            border-radius: 18px 0 0 18px;
            border: 1px solid rgba(148,163,184,.26);
            border-right: 0;
            background: var(--field-bg);
            color: var(--muted);
        }

        .form-control {
            border: 1px solid rgba(148,163,184,.26);
            background: var(--field-bg);
            color: var(--ink);
            min-height: 54px;
            font-weight: 600;
        }

        .input-group .form-control {
            border-left: 0;
            border-radius: 0 18px 18px 0;
        }

        .input-group.password-group .form-control {
            border-radius: 0;
        }

        .password-toggle {
            border-radius: 0 18px 18px 0;
            border: 1px solid rgba(148,163,184,.26);
            border-left: 0;
            background: var(--field-bg);
            color: var(--muted);
            min-width: 54px;
        }

        .form-control:focus {
            background: var(--field-bg);
            color: var(--ink);
            border-color: rgba(37,99,235,.45);
            box-shadow: 0 0 0 .25rem rgba(37,99,235,.14);
        }

        .form-control::placeholder {
            color: #94a3b8;
            font-weight: 500;
        }

        .remember-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
            margin: 1.1rem 0 1.45rem;
        }

        .form-check-label {
            color: var(--muted);
            font-size: .86rem;
            font-weight: 700;
        }

        .form-check-input:checked {
            background-color: var(--brand);
            border-color: var(--brand);
        }

        .secure-text {
            color: var(--muted);
            font-size: .82rem;
            font-weight: 700;
        }

        .btn-login {
            min-height: 56px;
            border: 0;
            border-radius: 20px;
            background: linear-gradient(135deg, var(--brand), var(--brand-2));
            box-shadow: 0 22px 42px rgba(37,99,235,.30);
            font-weight: 900;
            letter-spacing: -.01em;
        }

        .btn-login:hover {
            transform: translateY(-1px);
            background: linear-gradient(135deg, #1d4ed8, #0ea5e9);
        }

        .footer-note {
            margin-top: 1.25rem;
            padding: .9rem 1rem;
            border-radius: 20px;
            background: rgba(148,163,184,.10);
            border: 1px solid rgba(148,163,184,.18);
            color: var(--muted);
            font-size: .8rem;
            font-weight: 600;
        }

        .alert {
            border-radius: 20px;
            border: 0;
        }

        @media (max-width: 991px) {
            .login-page {
                grid-template-columns: 1fr;
            }

            .image-side {
                min-height: 42vh;
            }

            .image-content {
                min-height: 42vh;
                padding: 2rem;
            }

            .hero-copy h1 {
                font-size: 2.7rem;
            }

            .hero-stats {
                display: none;
            }

            .form-side {
                min-height: 58vh;
                padding: 4.5rem 1.25rem 1.5rem;
            }
        }
    </style>
</head>

<body class="login-body">
<div class="login-page">
    <section class="image-side">
        <div class="image-content">
            <div class="logo-glass">
                <img src="assets/img/company-logo.png" alt="<?php echo e($appName); ?>">
            </div>

            <div class="hero-copy">
                <div class="pill">
                    <i class="bi bi-stars"></i> Lodge PMS
                </div>

                <h1>Run your lodge beautifully.</h1>

                <p>
                    Manage reservations, rooming, folios, payments, arrivals, departures, extras and daily lodge operations from one elegant dashboard.
                </p>

                <div class="hero-stats">
                    <div class="hero-stat">
                        <strong>Rooms</strong>
                        <small>Availability control</small>
                    </div>
                    <div class="hero-stat">
                        <strong>Folios</strong>
                        <small>Guest billing</small>
                    </div>
                    <div class="hero-stat">
                        <strong>Reports</strong>
                        <small>Daily operations</small>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="form-side">
        <button type="button" class="theme-toggle" id="themeToggle">
            <i class="bi bi-moon-stars me-1"></i><span>Dark</span>
        </button>

        <div class="login-card">
            <div class="login-card-inner">
                <div class="form-logo">
                    <img src="assets/img/company-logo.png" alt="<?php echo e($appName); ?>">
                </div>

                <h2>Welcome back</h2>
                <div class="subtitle">Sign in to continue to your dashboard.</div>

                <?php if ($error !== ''): ?>
                    <div class="alert alert-danger d-flex gap-2 align-items-start">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div><?php echo e($error); ?></div>
                    </div>
                <?php endif; ?>

                <form method="post" autocomplete="off">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <div class="input-group input-group-lg">
                            <span class="input-group-text"><i class="bi bi-person"></i></span>
                            <?php if (!empty($activeUsers)): ?>
                                <select class="form-select" name="username" required autofocus>
                                    <option value="">Select user…</option>
                                    <?php foreach ($activeUsers as $u): ?>
                                        <?php
                                            $uname = (string)$u['username'];
                                            $label = trim((string)($u['full_name'] ?? ''));
                                            $display = $label !== '' ? ($label . ' (' . $uname . ')') : $uname;
                                        ?>
                                        <option value="<?php echo e($uname); ?>" <?php echo ($rememberedUsername === $uname) ? 'selected' : ''; ?>>
                                            <?php echo e($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            <?php else: ?>
                                <input type="text"
                                       class="form-control"
                                       name="username"
                                       value="<?php echo e($rememberedUsername); ?>"
                                       placeholder="Enter username or email"
                                       required
                                       autofocus>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <div class="input-group input-group-lg password-group">
                            <span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
                            <input type="password"
                                   class="form-control"
                                   name="password"
                                   id="passwordInput"
                                   placeholder="Enter password"
                                   required>
                            <button class="password-toggle"
                                    type="button"
                                    id="togglePassword"
                                    aria-label="Show password"
                                    tabindex="-1">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>

                    <div class="remember-row">
                        <div class="form-check">
                            <input class="form-check-input"
                                   type="checkbox"
                                   name="remember_me"
                                   id="rememberMe"
                                   <?php echo $rememberedUsername !== '' ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="rememberMe">
                                Remember me
                            </label>
                        </div>

                        <span class="secure-text">
                            <i class="bi bi-lock me-1"></i>Secure login
                        </span>
                    </div>

                    <button type="submit" class="btn btn-primary btn-lg w-100 btn-login">
                        <i class="bi bi-box-arrow-in-right me-2"></i>Sign in
                    </button>
                </form>

                <div class="footer-note">
                    <i class="bi bi-info-circle me-1"></i>
                    Select your name from the list and enter your password. Remember me keeps your user selected on this device.
                </div>
            </div>
        </div>
    </section>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var toggleBtn = document.getElementById('togglePassword');
    var passwordInput = document.getElementById('passwordInput');
    var themeToggle = document.getElementById('themeToggle');

    function setTheme(mode) {
        var isDark = mode === 'dark';
        document.body.classList.toggle('dark-login', isDark);

        if (themeToggle) {
            var icon = themeToggle.querySelector('i');
            var text = themeToggle.querySelector('span');

            if (icon) {
                icon.classList.toggle('bi-moon-stars', !isDark);
                icon.classList.toggle('bi-sun', isDark);
            }

            if (text) {
                text.textContent = isDark ? 'Light' : 'Dark';
            }
        }

        localStorage.setItem('ss_login_theme', mode);
    }

    setTheme(localStorage.getItem('ss_login_theme') || 'light');

    if (themeToggle) {
        themeToggle.addEventListener('click', function () {
            setTheme(document.body.classList.contains('dark-login') ? 'light' : 'dark');
        });
    }

    if (toggleBtn && passwordInput) {
        toggleBtn.addEventListener('click', function () {
            var icon = this.querySelector('i');

            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                this.setAttribute('aria-label', 'Hide password');
                if (icon) {
                    icon.classList.remove('bi-eye');
                    icon.classList.add('bi-eye-slash');
                }
            } else {
                passwordInput.type = 'password';
                this.setAttribute('aria-label', 'Show password');
                if (icon) {
                    icon.classList.remove('bi-eye-slash');
                    icon.classList.add('bi-eye');
                }
            }
        });
    }
});
</script>
</body>
</html>