<?php

namespace Config;

use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;

/*
 * --------------------------------------------------------------------
 * Application Events
 * --------------------------------------------------------------------
 */

// --- HEADER CORS UNTUK FLUTTER ---
Events::on('pre_system', function () {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "OPTIONS") {
        die();
    }
});

// --- DEBUG TOOLBAR (BAWAAN CI4) ---
if (CI_DEBUG && ! is_cli()) {
    Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
    service('toolbar')->respond();
    
    if (ENVIRONMENT === 'development') {
        service('routes')->get('__hot-reload', static function (): void {
            (new HotReloader())->run();
        });
    }
}