<?php namespace App\Filters;

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

class Cors implements FilterInterface
{
    // CORS BARU
    // protected $allowedOrigins = [
    //     'http://localhost:5173',
    //     'https://clqms01.services-summit.my.id',
    // ];

    public function before(RequestInterface $request, $arguments = null)
    {
        // CORS LAMA
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-CSRF-TOKEN');
        // Handle preflight requests
        // if ($request->getMethod() === 'options') {
        //     header('HTTP/1.1 200 OK');
        //     exit();
        // }

        // CORS BARU
        // log_message('debug', 'Cors Filter Triggered First');
        // $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        // $response = service('response');

        // if (in_array($origin, $this->allowedOrigins)) {
        //     $response->setHeader('Access-Control-Allow-Origin', $origin);
        //     $response->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
        //     $response->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin, Cache-Control, Pragma, X-CSRF-TOKEN');
        //     // $response->setHeader('Access-Control-Allow-Headers', '*');
        //     $response->setHeader('Access-Control-Allow-Credentials', 'true');
        // }

        // Tangani preflight OPTIONS dengan return response
        // if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        //     // log_message('debug', 'Cors Filter Triggered OK');
        //     return $response->setStatusCode(200)->setBody('OK');
        // }
        // log_message('debug', 'Cors Filter Triggered Second');
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No actions required after the request
        // return $response;
    }
}
