<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';

if (current_user()) {
    redirect('dashboard.php');
}

$error = '';

if (is_post()) {
    verify_csrf();

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username && $password) {
        try {
            $stmt = db()->prepare("
                SELECT *
                FROM users
                WHERE username = :username AND is_active = 1
                LIMIT 1
            ");
            $stmt->execute(['username' => $username]);
            $row = $stmt->fetch();

            if ($row && password_verify($password, $row['password_hash'])) {
                login_user($row);
                redirect('dashboard.php');
            }

            $error = 'Kullanıcı adı veya şifre hatalı.';
        } catch (Throwable $e) {
            $error = 'Bağlantı hatası. Lütfen tekrar deneyin.';
        }
    } else {
        $error = 'Kullanıcı adı ve şifre gereklidir.';
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Giriş — Arti Atolye ERP</title>
<link rel="stylesheet" href="assets/css/erp.css">
</head>
<body>
<div class="login-page">
  <div class="login-card">
    <div class="login-brand">
      <div class="login-name">Arti <span>Atolye</span></div>
      <div class="login-div"></div>
      <div class="login-sub">Üretim Takip Paneli</div>
    </div>

    <?php if ($error): ?>
      <div class="flash flash-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" action="login.php" autocomplete="off">
      <?= csrf_field() ?>

      <div class="form-group">
        <label class="form-label">Kullanıcı Adı</label>
        <input type="text" name="username" class="form-control"
               value="<?= htmlspecialchars($_POST['username'] ?? '') ?>"
               placeholder="kullanici_adi" autofocus autocomplete="username" required>
      </div>

      <div class="form-group">
        <label class="form-label">Şifre</label>
        <input type="password" name="password" class="form-control"
               placeholder="••••••••" autocomplete="current-password" required>
      </div>

      <button type="submit" class="btn btn-primary btn-block btn-lg" style="margin-top:6px;">
        Giriş Yap
      </button>
    </form>
  </div>
</div>
</body>
</html>
