<?php

namespace App\Filters;

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

class MaintenanceFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Skip maintenance check for maintenance endpoints
        $uri = $request->getUri();
        $path = $uri->getPath();
        
        if (strpos($path, '/maintenance/') !== false) {
            return;
        }

        $db = \Config\Database::connect();
        
        // Check maintenance status
        $query = $db->query("SELECT status FROM system_maintenance WHERE id = 1");
        $result = $query->getRow();

        // If maintenance is 'off', show maintenance page
        if ($result && $result->status === 'off') {
            $response = service('response');
            $response->setStatusCode(503);
            $response->setBody(view('errors/maintenance'));
            return $response;
        }
    }

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

