<?php
namespace App\Controllers;

/**
 * Base API Controller
 */
abstract class ApiController
{
    /**
     * Check an opt-in RBAC delegation capability without letting admin/system
     * bypasses turn into behavior changes for legacy hard role gates.
     */
    protected function hasDelegatedCapability(string $capabilityKey): bool
    {
        $role = strtolower(trim((string)($_SESSION['role'] ?? '')));
        if (in_array($role, ['admin', 'system', 'super_admin'], true)) {
            return false;
        }

        global $app;
        if (!isset($app->services->rbac) || !$app->services->rbac) {
            return false;
        }

        return (bool)$app->services->rbac->can($capabilityKey);
    }

    protected function jsonResponse($data, $statusCode = 200)
    {
        header('Content-Type: application/json; charset=utf-8');
        http_response_code($statusCode);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    protected function successResponse($data = [], $message = '')
    {
        $response = ['status' => 'success'];
        if (!empty($message)) {
            $response['message'] = $message;
        }
        if (!empty($data)) {
            $response = array_merge($response, $data);
        }
        $this->jsonResponse($response);
    }

    protected function errorResponse($message, $statusCode = 400)
    {
        $this->jsonResponse(['status' => 'error', 'message' => $message], $statusCode);
    }
}

