<?php

namespace App\Filters;

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

class AdminAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $path = $request->getUri()->getPath();
        if (strpos($path, 'admin/login') !== false) {
            return null;
        }
        $adminId = session()->get('admin_user_id');
        if (! $adminId) {
            return redirect()->to(base_url('admin/login'));
        }
        $db  = \Config\Database::connect();
        $row = $db->table('users')->where('id', $adminId)->get()->getRow();
        if (! $row || ($row->role ?? '') !== 'admin') {
            session()->remove('admin_user_id');
            return redirect()->to(base_url('admin/login'));
        }
        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        return $response;
    }
}
