<?php
session_start();

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

    if ($username === '' || $password === '') {
        $error = 'Please enter username and password.';
    } else {

        // جلب المستخدم
        $stmt = $pdo->prepare("
            SELECT u.user_id, u.username, u.password, u.role_id, r.role_name
            FROM users u
            JOIN roles r ON u.role_id = r.role_id
            WHERE u.username = ?
            LIMIT 1
        ");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {

            session_regenerate_id(true);

            $_SESSION['logged_in'] = true;
            $_SESSION['user_id']   = $user['user_id'];
            $_SESSION['username']  = $user['username'];
            $_SESSION['role']      = $user['role_name'];
            $_SESSION['role_id']   = $user['role_id'];

            /* =========================
               تحميل الصلاحيات من جدول permissions
               (بدون تعديل DB)
            ========================= */
            $permStmt = $pdo->prepare("
                SELECT page_name, can_view, can_add, can_edit, can_delete, can_print
                FROM permissions
                WHERE role_id = ?
            ");
            $permStmt->execute([$user['role_id']]);

            $permissions = [];
            foreach ($permStmt->fetchAll() as $row) {
                $permissions[$row['page_name']] = [
                    'view'   => (bool)$row['can_view'],
                    'add'    => (bool)$row['can_add'],
                    'edit'   => (bool)$row['can_edit'],
                    'delete' => (bool)$row['can_delete'],
                    'print'  => (bool)$row['can_print'],
                ];
            }

            $_SESSION['permissions'] = $permissions;

            header('Location: dashboard.php');
            exit;

        } else {
            $error = 'Invalid username or password.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login | Shipping System</title>
    <style>
        body { font-family: Arial; background:#f4f6f8; }
        .login-box {
            width:360px; margin:120px auto;
            background:#fff; padding:25px;
            border-radius:6px;
            box-shadow:0 0 10px rgba(0,0,0,.1);
        }
        input, button { width:100%; padding:10px; margin:10px 0; }
        button { background:#2563eb; color:#fff; border:none; }
        .error {
            background:#f8d7da; color:#721c24;
            padding:10px; border-radius:4px;
            text-align:center;
        }
    </style>
</head>
<body>

<div class="login-box">
    <h2>Login</h2>

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

    <form method="post">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>
</div>

</body>
</html>
