<?php
declare(strict_types=1);

namespace App\Core;

/**
 * Base Controller with response helpers
 */
abstract class Controller
{
    /**
     * Parse JSON body
     */
    protected function getJsonBody(): array
    {
        $body = file_get_contents('php://input');
        return json_decode($body, true) ?? [];
    }

    /**
     * Validate data or throw error
     */
    protected function validate(array $data, array $rules): array
    {
        $validator = new Validator();
        $result = $validator->validate($data, $rules);
        if (!$result['valid']) {
            Response::error('Validation Failed', $result['errors'], 422);
        }
        return $data;
    }
    /**
     * Check if user has permission
     */
    protected function hasPermission(string $permission): bool
    {
        $payload = $_REQUEST['user'] ?? null;
        if (!$payload) return false;
        
        $permissions = $payload['permissions'] ?? [];
        if (in_array('*.*', $permissions)) return true;
        
        return in_array($permission, $permissions);
    }

    /**
     * Require permission or 403
     */
    protected function requirePermission(string $permission): void
    {
        if (!$this->hasPermission($permission)) {
            Response::error('Forbidden: You do not have permission for this action', [], 403);
        }
    }
}

