<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use App\Models\Auth\UsersModel;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = Services::session();
        $uri = service('uri');
        $currentPath = $uri->getPath();

        // Skip auth filter for login/logout routes
        $excludedPaths = ['login', 'logout'];
        if (in_array($currentPath, $excludedPaths)) {
            return;
        }

        // Check if user is logged in
        if (!$session->get('isLoggedIn')) {
            // Check for remember token
            $rememberToken = $_COOKIE['remember_token'] ?? null;
            if ($rememberToken) {
                $usersModel = new UsersModel();
                $user = $usersModel->findByRememberToken($rememberToken);

                if ($user) {
                    // Auto-login with remember token
                    $session->set([
                        'isLoggedIn' => true,
                        'userId' => $user['user_id'],
                        'username' => $user['username']
                    ]);
                    return;
                }
            }

            return redirect()->to('/login');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do nothing
    }
}
