<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class PermissionFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! auth()->loggedIn()) {
            return redirect()->to('/login');
        }

        if (! empty($arguments)) {
            if (is_string($arguments)) {
                $arguments = $arguments === '' ? [] : array_map('trim', explode(',', $arguments));
            }

            foreach ($arguments as $permission) {
                if (has_permission($permission)) {
                    return;
                }
            }

            $path = method_exists($request, 'getUri') && $request->getUri() ? $request->getUri()->getPath() : '';
            if (is_string($path) && str_starts_with(ltrim($path, '/'), 'admin/alertes-catalog')) {
                $user = auth()->user();
                $checks = [];
                foreach ((array) $arguments as $permission) {
                    $checks[$permission] = has_permission($permission);
                }

                $payload = [
                    'filter' => 'permission',
                    'path' => $path,
                    'user_id' => $user?->id,
                    'groups' => $user ? $user->getGroups() : [],
                    'arguments' => $arguments,
                    'checks' => $checks,
                ];

                error_log('[PermissionFilter][debug] ' . json_encode($payload));

                return service('response')
                    ->setStatusCode(403)
                    ->setJSON($payload);
            }

            $user = auth()->user();
            log_message('error', '[PermissionFilter] denied uri={uri} user_id={user_id} groups={groups} args={args}', [
                'uri'     => (string) ($request->getUri() ?? ''),
                'user_id' => $user?->id,
                'groups'  => $user ? implode(',', $user->getGroups()) : '',
                'args'    => implode(',', (array) $arguments),
            ]);

            return redirect()->to('/dashboard')->with('error', 'Vous n\'avez pas la permission requise.');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Nothing to do here
    }
}
