<?php
session_start();
require_once __DIR__ . '/config/db.php';

if (isset($_SESSION['user_id']) && isset($_SESSION['user_role'])) {
    if (in_array($_SESSION['user_role'], ['staff', 'admin'], true)) {
        header('Location: staff-dashboard.php');
        exit;
    }
}

$error = '';
$demoEmail = 'staff@demo.com';
$demoPassword = 'Staff@123';

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

    if ($email === '' || $password === '') {
        $error = 'Email and password are required.';
    } else {
        $loggedIn = false;

        // 1) Real staff/admin login from database
        $stmt = $connection->prepare("SELECT id, name, email, role, password FROM users WHERE email = ? AND role IN ('staff', 'admin') LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result && $result->num_rows === 1) {
                $user = $result->fetch_assoc();
                $hash = (string)($user['password'] ?? '');

                if ($hash !== '' && password_verify($password, $hash)) {
                    $_SESSION['user_id'] = (int)$user['id'];
                    $_SESSION['user_name'] = (string)$user['name'];
                    $_SESSION['name'] = (string)$user['name'];
                    $_SESSION['user_email'] = (string)$user['email'];
                    $_SESSION['user_role'] = (string)$user['role'];
                    $loggedIn = true;
                }
            }
            $stmt->close();
        }

        // 2) Demo login fallback
        if (!$loggedIn && strcasecmp($email, $demoEmail) === 0 && $password === $demoPassword) {
            $demoId = 1;
            $demoName = 'Demo Staff';
            $demoUserRole = 'staff';

            // Prefer a real staff/admin account ID to avoid FK issues in action logs/notifications
            $demoStmt = $connection->prepare("SELECT id, name, email, role FROM users WHERE role IN ('staff', 'admin') ORDER BY CASE WHEN role='staff' THEN 0 ELSE 1 END, id ASC LIMIT 1");
            if ($demoStmt) {
                $demoStmt->execute();
                $demoResult = $demoStmt->get_result();
                if ($demoResult && $demoResult->num_rows === 1) {
                    $demoUser = $demoResult->fetch_assoc();
                    $demoId = (int)($demoUser['id'] ?? $demoId);
                    $demoName = (string)($demoUser['name'] ?? $demoName);
                    $demoUserRole = (string)($demoUser['role'] ?? $demoUserRole);
                }
                $demoStmt->close();
            }

            $_SESSION['user_id'] = $demoId;
            $_SESSION['user_name'] = $demoName;
            $_SESSION['name'] = $demoName;
            $_SESSION['user_email'] = $demoEmail;
            $_SESSION['user_role'] = $demoUserRole === 'admin' ? 'admin' : 'staff';
            $loggedIn = true;
        }

        if ($loggedIn) {
            header('Location: staff-dashboard.php');
            exit;
        }

        $error = 'Invalid credentials. Use staff account or demo login.';
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Staff Login | Faren Interior Design</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        :root {
            --s-bg: #f3ece2;
            --s-surface: #ffffff;
            --s-border: #eadfce;
            --s-ink: #231d18;
            --s-muted: #71675d;
            --s-accent: #b78d5e;
            --s-accent-dark: #8f6845;
            --s-danger: #b44747;
        }

        .staff-login-page {
            min-height: 100vh;
            display: grid;
            place-items: center;
            padding: 24px 12px;
            background:
                radial-gradient(circle at 12% 10%, rgba(183, 141, 94, 0.15), transparent 34%),
                radial-gradient(circle at 86% 88%, rgba(143, 104, 69, 0.12), transparent 36%),
                linear-gradient(180deg, #f8f4ed 0%, var(--s-bg) 100%);
        }

        .staff-login-card {
            width: min(520px, 100%);
            background: var(--s-surface);
            border: 1px solid var(--s-border);
            border-radius: 18px;
            box-shadow: 0 18px 42px rgba(32, 23, 14, 0.14);
            overflow: hidden;
        }

        .card-top {
            padding: 24px 24px 18px;
            background: linear-gradient(130deg, #201811 0%, #3a2c20 58%, #4f3b2b 100%);
            color: #fff;
        }

        .card-top h1 {
            margin: 0;
            font-size: clamp(24px, 4vw, 34px);
            line-height: 1.1;
            font-weight: 800;
        }

        .card-top p {
            margin: 8px 0 0;
            color: rgba(255, 255, 255, 0.86);
            font-size: 14px;
        }

        .card-body {
            padding: 22px;
        }

        .field {
            margin-bottom: 14px;
        }

        .field label {
            display: block;
            margin-bottom: 6px;
            color: #3a2f25;
            font-weight: 700;
            font-size: 13px;
            letter-spacing: .04em;
            text-transform: uppercase;
        }

        .field input {
            width: 100%;
            border: 1px solid var(--s-border);
            border-radius: 10px;
            padding: 12px 12px;
            color: var(--s-ink);
            font-size: 15px;
            font-weight: 600;
            outline: none;
            transition: all .2s ease;
        }

        .field input:focus {
            border-color: #d5b290;
            box-shadow: 0 0 0 3px rgba(183, 141, 94, .16);
        }

        .login-btn {
            width: 100%;
            border: 0;
            border-radius: 11px;
            padding: 12px 14px;
            background: linear-gradient(135deg, var(--s-accent), var(--s-accent-dark));
            color: #fff;
            font-size: 15px;
            font-weight: 800;
            letter-spacing: .03em;
            cursor: pointer;
            transition: transform .2s ease, box-shadow .2s ease;
        }

        .login-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 10px 22px rgba(143, 104, 69, .28);
        }

        .error-box {
            margin-bottom: 12px;
            border-radius: 10px;
            border: 1px solid #efcaca;
            background: #fdeeee;
            color: var(--s-danger);
            padding: 10px 12px;
            font-size: 13px;
            font-weight: 700;
        }

        .demo-box {
            margin-top: 14px;
            border: 1px dashed #dcc5a7;
            border-radius: 10px;
            background: #fcf7f0;
            padding: 12px;
        }

        .demo-box strong {
            display: block;
            color: #3e3126;
            font-size: 13px;
            margin-bottom: 6px;
        }

        .demo-box p {
            margin: 0;
            color: var(--s-muted);
            font-size: 13px;
            line-height: 1.5;
        }

        .login-links {
            margin-top: 14px;
            display: flex;
            justify-content: space-between;
            gap: 10px;
            flex-wrap: wrap;
        }

        .login-links a {
            color: #7b5a3c;
            font-size: 13px;
            font-weight: 700;
            text-decoration: none;
        }

        .login-links a:hover {
            color: #5f442b;
            text-decoration: underline;
        }

        @media (max-width: 575.98px) {
            .staff-login-card {
                border-radius: 12px;
            }

            .card-top,
            .card-body {
                padding: 16px;
            }
        }
    </style>
</head>
<body>
    <main class="staff-login-page">
        <section class="staff-login-card" aria-label="Staff login form">
            <header class="card-top">
                <h1>Staff Login</h1>
                <p>Sign in to manage consultation verification and staff operations.</p>
            </header>

            <div class="card-body">
                <?php if ($error !== ''): ?>
                    <div class="error-box"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>

                <form method="POST" action="staff-login.php" novalidate>
                    <div class="field">
                        <label for="staffEmail">Email</label>
                        <input id="staffEmail" name="email" type="email" placeholder="Enter staff email" required>
                    </div>

                    <div class="field">
                        <label for="staffPassword">Password</label>
                        <input id="staffPassword" name="password" type="password" placeholder="Enter password" required>
                    </div>

                    <button class="login-btn" type="submit">Login To Dashboard</button>
                </form>

                <div class="demo-box">
                    <strong>Demo Login</strong>
                    <p>Email: <code><?php echo htmlspecialchars($demoEmail); ?></code></p>
                    <p>Password: <code><?php echo htmlspecialchars($demoPassword); ?></code></p>
                </div>

                <div class="login-links">
                    <a href="index.php">Back To Home</a>
                    <a href="auth-system/admin-login.php">Admin Login</a>
                </div>
            </div>
        </section>
    </main>
</body>
</html>
