<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (!session()->get('user_id')) {
            if ($request->isAJAX()) {
                return service('response')->setStatusCode(401)->setJSON(['success'=>false,'message'=>'Unauthenticated']);
            }
            return redirect()->to('/fieldly/public/index.php/login');
        }

        // Check session hasn't expired
        $lastActivity = session()->get('last_activity');
        $timeout = config('Fieldly')->sessionTimeout;
        if ($lastActivity && (time() - $lastActivity) > $timeout) {
            session()->destroy();
            return redirect()->to('/fieldly/public/index.php/login')->with('error', 'Your session has expired. Please log in again.');
        }
        session()->set('last_activity', time());
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Security headers
        $response->setHeader('X-Frame-Options', 'SAMEORIGIN');
        $response->setHeader('X-Content-Type-Options', 'nosniff');
        $response->setHeader('X-XSS-Protection', '1; mode=block');
        $response->setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
        return $response;
    }
}
