<?php

namespace App\Filters;

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

class AuthFilter implements FilterInterface
{
    /**
     * Checks if the user is logged in as admin.
     * Allows public access to login/logout routes.
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        // Get current URI path (e.g., 'admin/login')
        $uriPath = $request->uri->getPath();

        // Allow access to login and logout without auth
        if (in_array($uriPath, ['admin/login', 'admin/logout'], true)) {
            return;
        }

        // Redirect to login if not authenticated
        if (!session()->has('admin_id')) {
            return redirect()->to('/admin/login');
        }
    }

    /**
     * We don't need any after logic for auth.
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do nothing
    }
}