<?php
declare(strict_types=1);

require __DIR__ . '/../config/bootstrap.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

$lang = function_exists('current_lang') ? (string)current_lang() : 'ar';
$rtl = ($lang === 'ar');
$t = fn($ar,$en)=>($rtl ? $ar : $en);

if (function_exists('auth_id') && auth_id()) {
  header('Location: ' . base_path('dashboard'));
  exit;
}

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

  try {
    $db = \App\Core\Database::getInstance();

    $st = $db->prepare("SELECT * FROM users WHERE email=:e LIMIT 1");
    $st->execute([':e'=>$email]);
    $u = $st->fetch();

    $ok = false;
    if ($u) {
      $isActive = (int)($u['is_active'] ?? 1);
      $hash = (string)($u['password_hash'] ?? '');
      if ($isActive === 1 && $hash !== '' && password_verify($pass, $hash)) {
        $ok = true;
      }
    }

    if (!$ok) {
      if (function_exists('flash_set')) flash_set('danger', $t('بيانات الدخول غير صحيحة','Invalid credentials'));
      header('Location: ' . base_path('login.php'));
      exit;
    }

    // login success
    session_regenerate_id(true);
    $_SESSION['user_id'] = (int)$u['id'];

    // optional: update last_login_at
    try {
      $db->prepare("UPDATE users SET last_login_at=NOW() WHERE id=:id")->execute([':id'=>(int)$u['id']]);
    } catch (\Throwable $e) {}

    if (function_exists('flash_set')) flash_set('success', $t('تم تسجيل الدخول بنجاح','Logged in successfully'));
    header('Location: ' . base_path('dashboard'));
    exit;

  } catch (\Throwable $e) {
    if (function_exists('flash_set')) flash_set('danger', $t('حدث خطأ أثناء تسجيل الدخول','Login error'));
    header('Location: ' . base_path('login.php'));
    exit;
  }
}

require BASE_PATH . '/app/views/layouts/header.php';
?>
<div class="container py-5">
  <div class="row justify-content-center">
    <div class="col-lg-6">
      <div class="card border-0 shadow-sm overflow-hidden">
        <div class="card-body p-4">
          <div class="d-flex align-items-center justify-content-between mb-3">
            <h4 class="mb-0"><i class="fa-solid fa-right-to-bracket"></i> <?= e($t('تسجيل الدخول','Login')) ?></h4>
            <a class="btn btn-outline-primary btn-sm" href="<?= e(base_path('register.php')) ?>">
              <i class="fa-solid fa-user-plus"></i> <?= e($t('إنشاء حساب','Register')) ?>
            </a>
          </div>

          <form method="post" class="row g-3">
            <div class="col-12">
              <label class="form-label"><?= e($t('البريد الإلكتروني','Email')) ?></label>
              <input type="email" name="email" class="form-control" required autocomplete="username">
            </div>

            <div class="col-12">
              <label class="form-label"><?= e($t('كلمة المرور','Password')) ?></label>
              <input type="password" name="password" class="form-control" required autocomplete="current-password">
            </div>

            <div class="col-12 d-grid">
              <button class="btn btn-primary btn-lg">
                <i class="fa-solid fa-lock"></i> <?= e($t('دخول','Sign in')) ?>
              </button>
            </div>
          </form>

        </div>
      </div>
    </div>
  </div>
</div>
<?php require BASE_PATH . '/app/views/layouts/footer.php'; ?>
