<?php
session_start();
require_once 'db/config.php';

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

    try {
        $pdo = db();
        $stmt = $pdo->prepare("SELECT u.id, u.username, u.password, r.name as role_name 
                               FROM users u 
                               JOIN roles r ON u.role_id = r.id 
                               WHERE u.username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            // Authentication successful
            $stmt = $pdo->prepare("SELECT p.name 
                                   FROM permissions p
                                   JOIN role_permissions rp ON p.id = rp.permission_id
                                   WHERE rp.role_id = (SELECT id FROM roles WHERE name = ?)");
            $stmt->execute([$user['role_name']]);
            $permissions = $stmt->fetchAll(PDO::FETCH_COLUMN);

            $_SESSION['user'] = [
                'id' => $user['id'],
                'username' => $user['username'],
                'role' => $user['role_name'],
                'permissions' => $permissions
            ];
            unset($_SESSION['error']);
            header('Location: index.php');
            exit();
        } else {
            // Authentication failed
            $_SESSION['error'] = 'Invalid username or password.';
            header('Location: login.php');
            exit();
        }
    } catch (PDOException $e) {
        $_SESSION['error'] = 'Database error: ' . $e->getMessage();
        header('Location: login.php');
        exit();
    }
} else {
    // Redirect if accessed directly
    header('Location: login.php');
    exit();
}