<?php

namespace App\Filters;

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

class AuthFilter implements FilterInterface
{
    /**
     * Check if user is logged in before accessing admin routes
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        // Check if user is logged in
        if (!$session->get('isLoggedIn')) {
            // Store intended URL for redirect after login
            $session->set('redirect_url', current_url());
            
            return redirect()->to('/admin/login')->with('error', 'Silakan login untuk mengakses halaman admin.');
        }

        // Check if session is still valid (optional: session timeout)
        $lastActivity = $session->get('last_activity');
        $timeout = 3600; // 1 hour
        
        if ($lastActivity && (time() - $lastActivity > $timeout)) {
            $session->destroy();
            return redirect()->to('/admin/login')->with('error', 'Sesi Anda telah berakhir. Silakan login kembali.');
        }

        // Update last activity
        $session->set('last_activity', time());
    }

    /**
     * Do nothing after the controller method is called
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Nothing to do here
    }
}
