<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/functions.php';
$GLOBALS['BASE'] = '';

if (is_logged_in()) redirect('index.php');

$err   = '';
$ident = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $ident = post('username');
    $pass  = post('password');

    $user = Db::one(
        'SELECT * FROM users WHERE (username = ? OR email = ?) AND is_active = 1',
        [$ident, $ident]
    );
    if ($user && password_verify($pass, $user['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['uid'] = (int)$user['id'];
        $_SESSION['bid'] = (int)$user['business_id'];
        Db::run('UPDATE users SET last_login = NOW() WHERE id = ?', [$user['id']]);
        redirect('index.php');
    }
    // אותה הודעה לשם משתמש שגוי ולסיסמה שגויה — לא מסגירים מי קיים
    usleep(random_int(150000, 350000));
    $err = 'שם המשתמש או הסיסמה שגויים.';
}
?>
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>כניסה · <?= h(APP_NAME) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Assistant:wght@400;500;600;700&family=Frank+Ruhl+Libre:wght@700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/app.css">
</head>
<body>
<div class="auth">
  <div class="auth-box">
    <h1>כניסה למערכת</h1>
    <p class="lead">ניהול מחירון והפקת הצעות מחיר</p>

    <?php if ($err): ?><div class="note note--err"><?= h($err) ?></div><?php endif; ?>

    <form method="post" autocomplete="on">
      <?= csrf_field() ?>
      <div class="field">
        <label for="username">שם משתמש</label>
        <input type="text" id="username" name="username" value="<?= h($ident) ?>" required autofocus>
      </div>
      <div class="field">
        <label for="password">סיסמה</label>
        <input type="password" id="password" name="password" required>
      </div>
      <button class="btn btn--primary" style="width:100%" type="submit">כניסה</button>
    </form>

    <div class="auth-alt">
      ההרשמה העצמית מושבתת. משתמשים נוספים נוצרים דרך <code>install/add-user.php</code>.
    </div>
  </div>
</div>
</body>
</html>
