<?php
session_save_path(__DIR__ . '/tmp');
if (!is_dir(__DIR__ . '/tmp')) mkdir(__DIR__ . '/tmp', 0777, true);
session_start();
require __DIR__ . '/includes/db.php';


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

    if ($username && $password) {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username=? LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && $user['password'] === md5($password)) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            header("Location: /wood-system/index.php");
            exit;
        } else {
            $error = "اسم المستخدم أو كلمة المرور غير صحيحة.";
        }
    } else {
        $error = "الرجاء إدخال اسم المستخدم وكلمة المرور.";
    }
}
?>

<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>تسجيل الدخول - Wood System</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
  background: linear-gradient(135deg,#003366,#0d6efd);
  font-family: "Tajawal", sans-serif;
}
.login-box {
  max-width: 400px;
  margin: 8% auto;
  background: #fff;
  padding: 2rem;
  border-radius: 1rem;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.btn-primary {
  background-color:#0d6efd;
  border:none;
  border-radius:.75rem;
}
</style>
</head>
<body>
<div class="login-box text-center">
  <h3 class="text-primary fw-bold mb-4">🔐 تسجيل الدخول</h3>
  <?php if ($error): ?>
    <div class="alert alert-danger"><?= $error ?></div>
  <?php endif; ?>
  <form method="post">
    <div class="mb-3 text-start">
      <label class="form-label">اسم المستخدم</label>
      <input type="text" name="username" class="form-control" required autofocus>
    </div>
    <div class="mb-3 text-start">
      <label class="form-label">كلمة المرور</label>
      <input type="password" name="password" class="form-control" required>
    </div>
    <button type="submit" class="btn btn-primary w-100 py-2">دخول</button>
  </form>
</div>
</body>
</html>
