<?php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/mobile_detect.php';

if (isLoggedIn()) {
    // Already logged in — send to right UI
    if (isMobileDevice() && !($_SESSION['force_desktop'] ?? false)) {
        header('Location: ' . BASE_URL . '/mobile/index.php');
    } else {
        header('Location: ' . BASE_URL . '/dashboard.php');
    }
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    if ($username && $password) {
        $db   = getDB();
        $stmt = $db->prepare("SELECT * FROM users WHERE username = ? AND status = 'active'");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id']   = $user['id'];
            $_SESSION['username']  = $user['username'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['role']      = $user['role'];

            // Detect device and send to correct UI
            if (isMobileDevice() && !isset($_POST['force_desktop'])) {
                header('Location: ' . BASE_URL . '/mobile/index.php');
            } else {
                header('Location: ' . BASE_URL . '/dashboard.php');
            }
            exit;
        }
        $error = 'Invalid username or password.';
    } else {
        $error = 'Please fill in all fields.';
    }
}
$storeName = 'Rewards System';
try { $storeName = getSetting('store_name', 'Rewards System'); } catch(Exception $e){}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login — <?= e($storeName) ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link href="<?= BASE_URL ?>/assets/css/style.css" rel="stylesheet">
</head>
<body class="login-page">

<div class="login-bg min-vh-100 d-flex align-items-center justify-content-center">
  <!-- Decorative blobs -->
  <div class="blob blob-1"></div>
  <div class="blob blob-2"></div>

  <div class="card login-card shadow-xl">
    <div class="card-header text-center py-4 login-header">
      <div class="brand-icon mb-2">
        <i class="bi bi-star-fill text-warning fs-1"></i>
      </div>
      <h4 class="fw-bold mb-0 text-white"><?= e($storeName) ?></h4>
      <p class="mb-0 small text-white-50">Loyalty Rewards Management</p>
    </div>

    <div class="card-body p-4">
      <?php if ($error): ?>
      <div class="alert alert-danger d-flex align-items-center gap-2 py-2">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <?= e($error) ?>
      </div>
      <?php endif; ?>

      <form method="POST" autocomplete="on">
        <div class="mb-3">
          <label class="form-label fw-semibold small">Username</label>
          <div class="input-group input-group-lg">
            <span class="input-group-text bg-light border-end-0">
              <i class="bi bi-person text-muted"></i>
            </span>
            <input type="text" name="username" class="form-control border-start-0 ps-0"
                   placeholder="Enter username"
                   value="<?= e($_POST['username'] ?? '') ?>"
                   autofocus required>
          </div>
        </div>

        <div class="mb-4">
          <label class="form-label fw-semibold small">Password</label>
          <div class="input-group input-group-lg">
            <span class="input-group-text bg-light border-end-0">
              <i class="bi bi-lock text-muted"></i>
            </span>
            <input type="password" name="password" id="pwdInput"
                   class="form-control border-start-0 border-end-0 ps-0"
                   placeholder="Enter password" required>
            <button class="btn btn-light border" type="button" id="togglePwd">
              <i class="bi bi-eye" id="eyeIcon"></i>
            </button>
          </div>
        </div>

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

    <div class="card-footer text-center py-3 small text-muted bg-light">
      <i class="bi bi-shield-check me-1 text-success"></i>Secure login &mdash; <?= e($storeName) ?>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('togglePwd').addEventListener('click', function () {
    const el   = document.getElementById('pwdInput');
    const icon = document.getElementById('eyeIcon');
    if (el.type === 'password') {
        el.type        = 'text';
        icon.className = 'bi bi-eye-slash';
    } else {
        el.type        = 'password';
        icon.className = 'bi bi-eye';
    }
});
</script>
</body>
</html>
