<?php
session_start();
require 'db.php';

$error = '';

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

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username=? AND status=1 LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['role']    = $user['role'];
        $_SESSION['name']    = $user['name'];

        header("Location: dashboard.php");
        exit;
    } else {
        $error = "بيانات الدخول غير صحيحة";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<style>
body{font-family:Arial;background:#f1f1f1}
.box{width:300px;margin:120px auto;background:#fff;padding:20px}
input,button{width:100%;padding:8px;margin:5px 0}
.error{color:red}
</style>
</head>
<body>

<div class="box">
<h3>تسجيل الدخول</h3>

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

<form method="post">
<input name="username" placeholder="اسم المستخدم" required>
<input type="password" name="password" placeholder="كلمة المرور" required>
<button>دخول</button>
</form>
</div>

</body>
</html>
