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

auth_start();

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = trim($_POST['username'] ?? '');
  $pass     = $_POST['password'] ?? '';

  $pdo = db();
  $st = $pdo->prepare("SELECT id, name, username, role, password_hash, is_active FROM users WHERE username = ? LIMIT 1");
  $st->execute([$username]);
  $u = $st->fetch();

  if (!$u || !(int)$u['is_active'] || !password_verify($pass, $u['password_hash'])) {
    $error = "بيانات الدخول غير صحيحة";
  } else {
    session_regenerate_id(true);
    $_SESSION['user'] = [
      'id' => (int)$u['id'],
      'name' => $u['name'],
      'role' => $u['role'],
    ];
    header("Location: dashboard.php");
    exit;
  }
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>تسجيل الدخول - نظام إدارة المجلات</title>
  <style>
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f4f7f6; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
    .login-box { background: #fff; padding: 2rem; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); width: 100%; max-width: 400px; }
    h3 { text-align: center; color: #333; }
    input { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
    button { width: 100%; padding: 10px; background: #2c3e50; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
    button:hover { background: #34495e; }
    .error { color: #e74c3c; text-align: center; margin-bottom: 1rem; }
  </style>
</head>
<body>
  <div class="login-box">
    <h3>تسجيل الدخول</h3>
    <?php if ($error): ?><div class="error"><?= h($error) ?></div><?php endif; ?>
    <form method="post">
      <label>اسم المستخدم</label>
      <input name="username" required autofocus>
      <label>كلمة المرور</label>
      <input name="password" type="password" required>
      <button type="submit">دخول</button>
    </form>
  </div>
</body>
</html>
