<?php

namespace App\Helpers;

use App\Core\Database;

class PermissionHelper
{
    public static function has($permission)
    {
        if (!isset($_SESSION['user_id'])) {
            return false;
        }

        if (!isset($_SESSION['role_code'])) {
            return false;
        }

        $role = $_SESSION['role_code'];

        /*
         SUPERADMIN OVERRIDE
        */

        if ($role === 'superadmin') {
            return true;
        }

        $db = Database::getInstance();

        try {

            $stmt = $db->prepare("
                SELECT COUNT(*) c
                FROM role_permissions
                WHERE role_code = ?
                AND permission = ?
            ");

            $stmt->execute([
                $role,
                $permission
            ]);

            $row = $stmt->fetch();

            return ($row['c'] ?? 0) > 0;

        } catch (\Throwable $e) {

            error_log(
                'Permission check failed: '
                . $e->getMessage()
            );

            return false;

        }
    }
}
