<?php

namespace App\Filters;

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

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

    public function before(RequestInterface $request, $arguments = null)
    {
        log_message('debug', 'Cors Filter Triggered First');
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        $response = service('response');

        // Allow same-origin requests (when no Origin header is present)
        if (empty($origin)) {
            return null;
        }

        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');
            // $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)
    {
        log_message('debug', 'Cors Filter Triggered Thrid');
        return $response;
    }
}
