<?php
session_start();

if (isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

$error = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include 'db.php';
    $username = trim($_POST['username']);
    $password = md5($_POST['password']);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :u AND password = :p");
    $stmt->execute([':u' => $username, ':p' => $password]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $_SESSION['user']     = $user['username'];
        $_SESSION['userId']   = $user['id'];
        $_SESSION['userRole'] = $user['role'];

        if ($user['role'] == 'admin') {
            header('Location: admin.php');
        } else {
            header('Location: index.php');
        }
        exit;
    } else {
        $error = "نام کاربری یا رمز عبور اشتباه است.";
    }
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>ورود</title>
    <style>
        body { font-family: Tahoma, sans-serif; background: #f0f0f0; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        .box { background: white; padding: 35px 40px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); width: 300px; }
        .box h2 { text-align: center; color: #2c3e50; margin-top: 0; font-size: 18px; }
        label { font-size: 13px; color: #555; }
        input[type=text], input[type=password] {
            width: 100%; padding: 9px 12px; margin: 5px 0 15px 0;
            border: 1px solid #ccc; border-radius: 5px;
            font-size: 14px; font-family: Tahoma, sans-serif; box-sizing: border-box;
        }
        button { width: 100%; padding: 10px; background: #2980b9; color: white; border: none; border-radius: 5px; font-size: 14px; font-family: Tahoma, sans-serif; cursor: pointer; }
        button:hover { background: #1a6fa0; }
        .error { background: #fadbd8; color: #c0392b; padding: 9px 12px; border-radius: 5px; font-size: 13px; margin-bottom: 15px; }
        .links { text-align: center; margin-top: 15px; font-size: 13px; }
        .links a { color: #2980b9; text-decoration: none; }
    </style>
</head>
<body>
<div class="box">
    <h2>🔐 ورود به حساب</h2>
    <?php if ($error): ?><div class="error"><?php echo $error; ?></div><?php endif; ?>
    <form method="POST">
        <label>نام کاربری:</label>
        <input type="text" name="username">
        <label>رمز عبور:</label>
        <input type="password" name="password">
        <button type="submit">ورود</button>
    </form>
    <div class="links">حساب نداری؟ <a href="register.php">ثبت‌نام</a></div>
</div>
</body>
</html>
