<?php
/* ============================================================================
   WBMCZ — STAFF SIGN IN
   ----------------------------------------------------------------------------
   The way in for the people who run the place. It is one door, not three: an
   employee, an admin and a super admin all sign in with the same credentials,
   and the door works out which of the three they are — from their own
   staff_level if one is set, otherwise from their role, and the owner account
   (the one with no role at all) is always a super admin.

   Three separate login forms would have been three ways of typing the same
   password into the same table, and somebody would sooner or later pick the
   wrong one and think their account was broken. So the page tells them what
   they came in as instead of asking them to declare it.

   Members do not belong here. A customer or seller who lands on this page is
   sent to their own sign-in rather than shown "wrong password", because their
   password is not wrong — the door is.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
@require_once __DIR__ . '/../includes/acl.php';

$company_name = getSetting('company_name', getSetting('site_name', 'WBMCZ'));
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : '../' . ltrim($company_logo, '/');

/* already signed in as staff — no reason to ask again */
if (isset($_SESSION['user_id']) && (($_SESSION['user_type'] ?? '') === 'admin')) {
    redirect('index.php');
}

$levels = [
    'superadmin' => ['Super Admin', 'fa-crown',          'from-amber-400 to-orange-500', 'The whole console, and who else may see what'],
    'admin'      => ['Admin',       'fa-shield-halved',  'from-indigo-500 to-violet-600', 'Everything their role has been given'],
    'employee'   => ['Employee',    'fa-user-tie',       'from-sky-500 to-blue-600',     'The work handed to them, and nothing else'],
];

$error = '';
$who   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['staff_login'])) {
    $login = trim((string)($_POST['login'] ?? ''));
    $pass  = (string)($_POST['password'] ?? '');

    if ($login === '' || $pass === '') {
        $error = 'Fill in both boxes.';
    } else {
        /* they may know themselves by mobile, by e-mail, or by staff code */
        $u = [];
        try {
            $u = $db->select(
                "SELECT * FROM users
                  WHERE mobile = ? OR email = ? OR employee_code = ?
                  ORDER BY (user_type = 'admin') DESC LIMIT 1",
                [$login, $login, $login]);
        } catch (\Throwable $e) {
            try { $u = $db->select("SELECT * FROM users WHERE mobile = ? OR email = ? LIMIT 1", [$login, $login]); }
            catch (\Throwable $e2) { $u = []; }
        }

        if (empty($u)) {
            $error = 'No account here answers to that.';
        } else {
            $u = $u[0];

            if (array_key_exists('deleted_at', $u) && !empty($u['deleted_at'])) {
                $error = 'That account has been closed.';
            } elseif ((int)($u['status'] ?? 1) === 0) {
                $error = 'That account is switched off. Ask a super admin to turn it back on.';
            } elseif (!password_verify($pass, (string)$u['password'])) {
                $error = 'That password does not match.';
            } elseif (($u['user_type'] ?? '') !== 'admin') {
                /* a member at the staff door — send them to their own */
                $_SESSION['flash_error'] = 'That is a member account. Please sign in here instead.';
                redirect('../login.php');
            } else {
                $_SESSION['user_id']     = $u['id'];
                $_SESSION['user_name']   = $u['name'];
                $_SESSION['user_mobile'] = $u['mobile'];
                $_SESSION['user_type']   = $u['user_type'];

                if (function_exists('activity_log')) {
                    @require_once __DIR__ . '/../includes/activity.php';
                    try { activity_log($db, 'login', 'Staff', 'Signed in at the staff door'); } catch (\Throwable $e) {}
                }
                redirect('index.php');
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Staff sign in — <?php echo esc($company_name); ?></title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
  body { font-family:'Inter',sans-serif; }
  .fld { width:100%; border:1.5px solid #e2e8f0; border-radius:12px; padding:12px 14px 12px 42px;
         font-size:14px; background:#fff; }
  .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.15); }
  .ico { position:absolute; left:14px; top:50%; transform:translateY(-50%); color:#94a3b8; font-size:14px; }
</style>
</head>
<body class="min-h-screen bg-slate-900 flex items-center justify-center p-4">

<div class="w-full max-w-4xl grid md:grid-cols-2 gap-0 rounded-3xl overflow-hidden shadow-2xl">

  <!-- who comes through this door -->
  <div class="bg-gradient-to-br from-slate-900 via-indigo-950 to-slate-900 p-8 sm:p-10 text-white hidden md:block">
    <div class="flex items-center gap-3 mb-8">
      <img src="<?php echo esc($company_logo); ?>" alt="" class="w-11 h-11 rounded-xl bg-white/10 object-contain p-1">
      <div>
        <p class="font-black tracking-wide text-lg leading-none"><?php echo esc($company_name); ?></p>
        <p class="text-[11px] uppercase tracking-[.18em] text-indigo-300 mt-1">Admin Console</p>
      </div>
    </div>

    <h1 class="text-2xl font-extrabold leading-tight mb-2">The staff entrance</h1>
    <p class="text-[13px] text-slate-400 leading-relaxed mb-7">
      One door for all three. Sign in and the console opens at whatever your role
      has been given — nothing more, and nothing you have to pick from a list.
    </p>

    <div class="space-y-3">
      <?php foreach ($levels as $lk => $lv): ?>
        <div class="flex items-start gap-3 rounded-2xl bg-white/5 border border-white/10 px-4 py-3">
          <span class="w-9 h-9 rounded-xl bg-gradient-to-br <?php echo $lv[2]; ?> flex items-center justify-center flex-shrink-0">
            <i class="fas <?php echo $lv[1]; ?> text-[13px] text-white"></i></span>
          <span class="min-w-0">
            <span class="block font-bold text-[13.5px]"><?php echo $lv[0]; ?></span>
            <span class="block text-[11.5px] text-slate-400 leading-snug"><?php echo $lv[3]; ?></span>
          </span>
        </div>
      <?php endforeach; ?>
    </div>

    <p class="text-[11.5px] text-slate-500 mt-8 leading-relaxed">
      <i class="fas fa-circle-info mr-1"></i>
      Not staff? Members and sellers sign in at
      <a href="../login.php" class="text-indigo-300 font-semibold hover:underline">the main login</a>.
    </p>
  </div>

  <!-- the form -->
  <div class="bg-white p-8 sm:p-10">
    <div class="md:hidden flex items-center gap-3 mb-6">
      <img src="<?php echo esc($company_logo); ?>" alt="" class="w-10 h-10 rounded-xl bg-slate-100 object-contain p-1">
      <div>
        <p class="font-black text-slate-900 leading-none"><?php echo esc($company_name); ?></p>
        <p class="text-[10.5px] uppercase tracking-[.18em] text-slate-400 mt-1">Admin Console</p>
      </div>
    </div>

    <h2 class="text-xl font-extrabold text-slate-900">Sign in</h2>
    <p class="text-[13px] text-slate-500 mt-1 mb-6">Use the mobile, e-mail or staff code your account was made with.</p>

    <?php if ($error): ?>
      <div class="mb-5 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 text-[13px] font-semibold">
        <i class="fas fa-circle-exclamation mr-1.5"></i><?php echo esc($error); ?>
      </div>
    <?php endif; ?>

    <form method="POST" class="space-y-4">
      <input type="hidden" name="staff_login" value="1">

      <div>
        <label class="block text-[11px] font-black uppercase tracking-wide text-slate-500 mb-1.5">Mobile, e-mail or staff code</label>
        <div class="relative">
          <i class="fas fa-user ico"></i>
          <input name="login" class="fld" autocomplete="username" autofocus
                 value="<?php echo esc((string)($_POST['login'] ?? '')); ?>" placeholder="9876543210">
        </div>
      </div>

      <div>
        <label class="block text-[11px] font-black uppercase tracking-wide text-slate-500 mb-1.5">Password</label>
        <div class="relative">
          <i class="fas fa-lock ico"></i>
          <input type="password" name="password" class="fld" autocomplete="current-password" placeholder="••••••••">
        </div>
      </div>

      <button class="w-full py-3.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-white font-bold text-sm shadow-lg hover:shadow-xl transition-shadow">
        <i class="fas fa-right-to-bracket mr-1.5"></i> Sign in
      </button>
    </form>

    <div class="mt-6 pt-5 border-t border-slate-100 flex items-center justify-between text-[12.5px]">
      <a href="../forgot-password.php" class="font-semibold text-slate-500 hover:text-indigo-600">Forgotten your password?</a>
      <a href="../index.php" class="font-semibold text-slate-400 hover:text-slate-700">Back to the site</a>
    </div>
  </div>

</div>
</body>
</html>
