<?php

    include_once 'connection.php'; 
    include_once 'core/Core.php';
    include_once 'core/email/SendEmail.php';
    include_once 'core/QueueCampaign.php';

    try {

        $action = $_GET['action'];
        $method = strtolower($_SERVER['REQUEST_METHOD']);
        
        /*header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, X-Token-Auth, Authorization, x-store-code, x-xsrf-token");*/

        if($method === 'options' )
            exit;
        
        $resources = include_once './actions.php';

        if(!array_key_exists($action, $resources))
            throw new \Exception('Recurso não encontrado');

        $actions = $resources[$action];

        if(!array_key_exists($method, $actions))
            throw new \Exception('Ação não encontrada');

        $collection = $actions[$method];
        
        $class_name = array_keys($collection)[0];
        $function = $collection[$class_name];
        include "./controllers/{$class_name}.php";
        $controller = new $class_name(new Connection());
        $result = $controller->$function();
        $controller = null;
        
        // $result = mb_convert_encoding($result, 'UTF-8', 'UTF-8');
        // $result = iconv('UTF-8', 'UTF-8//IGNORE', $result);
        
        header("Content-Type: application/json; charset=UTF-8");
        $json = json_encode($result, JSON_UNESCAPED_UNICODE);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            
            echo json_encode(["error" => "Erro durante a codificação JSON: " . json_last_error_msg()]);
        } else {
            echo $json;
        }

    } catch(\Exception $err) {
        $code = $err->getCode() || 500;
        http_response_code($code);
        echo $err->getMessage();
    }