<?php

namespace App\Filters;

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

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();
        
        if (!$session->get('isLoggedIn') || $session->get('isLoggedIn')==null) {
            // Si es API (fetch)
            if ($request->isAJAX() || $request->getHeaderLine('Accept') === 'application/json') {
                return service('response')->setJSON([
                    'success' => false,
                    'message' => 'No autorizado.',
                ])->setStatusCode(401);
            }

            // Si es navegador normal
            return redirect()->to('/login');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Nada que hacer después
    }
}
