<?php
namespace App\Filters;

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

/**
 * AuthFilter — validates session authentication for all protected routes.
 * Also checks for account deactivation mid-session.
 */
class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Not logged in → redirect to login
        if (!session()->get('logged_in')) {
            return redirect()->to(base_url('login'))
                ->with('error', 'Please log in to access this page.');
        }

        // Verify user still exists and is active (mid-session deactivation check)
        $uid = session()->get('user_id');
        if ($uid) {
            $db   = \Config\Database::connect();
            $user = $db->table('users')->select('id, status')->where('id', $uid)->get()->getRowArray();
            if (!$user || $user['status'] !== 'active') {
                session()->destroy();
                return redirect()->to(base_url('login'))
                    ->with('error', 'Your account has been deactivated. Please contact your administrator.');
            }
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Add security headers to all authenticated responses
        $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');
    }
}
