<?php
namespace App\Models;

use Core\Model;

class UserModel extends Model
{
    protected string $table = 'users';

    public function findByEmail(string $email): array|false
    {
        return $this->db->fetch(
            "SELECT u.*, r.name AS role_name FROM users u 
             JOIN roles r ON r.id = u.role_id 
             WHERE u.email = ? LIMIT 1",
            [$email]
        );
    }

    public function allWithRoles(): array
    {
        return $this->db->fetchAll(
            "SELECT u.*, r.display_name AS role_display FROM users u 
             JOIN roles r ON r.id = u.role_id 
             ORDER BY u.created_at DESC"
        );
    }

    public function getPermissions(int $roleId): array
    {
        return $this->db->fetchAll(
            "SELECT p.name FROM permissions p 
             JOIN role_permissions rp ON rp.permission_id = p.id 
             WHERE rp.role_id = ?",
            [$roleId]
        );
    }

    public function hasPermission(int $roleId, string $permission): bool
    {
        $perms = $this->getPermissions($roleId);
        return in_array($permission, array_column($perms, 'name'));
    }
}
