<?php

require_once '../../vendor/autoload.php';
require_once '../../cors/index.php';
require_once '../../cors/verifica-token.php';


switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        localizarGeral();
        break;

    case 'POST':
        salvarGeral();
        break;

    case 'PUT':
        atualizarGeral ();
        break;

    default:
        echo json_encode(['error' => 'Método não suportado.']);
        http_response_code(405);
        break;
}

function salvarGeral()
{
    try {
        $data = json_decode(file_get_contents('php://input'), true);

        $geral = new \src\Model\geralModel();
        $geral->setUrlConexaoWhatsApp($data['urlConexaoWhatsApp'] ?? '');
        $geral->setLicenca($data['licenca'] ?? '');
        $geral->setIdInstancia($data['idInstancia'] ?? '');

        if (empty($geral->getUrlConexaoWhatsApp()) || empty($geral->getLicenca()) || empty($geral->getIdInstancia())) {
            throw new Exception('Todos os campos são obrigatórios');
        }

        $geralController = new \src\Controller\geralController();
        $geralController->salvar($geral);

        http_response_code(200);
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
        http_response_code(500);
    }
}

function atualizarGeral()
{
    try {
        $data = json_decode(file_get_contents('php://input'), true);

        $geral = new \src\Model\geralModel();
        $geral->setId($data['id'] ?? '');
        $geral->setUrlConexaoWhatsApp($data['urlConexaoWhatsApp'] ?? '');
        $geral->setLicenca($data['licenca'] ?? '');
        $geral->setIdInstancia($data['idInstancia'] ?? '');

        if (empty($geral->getId()) || empty($geral->getUrlConexaoWhatsApp()) || empty($geral->getLicenca()) || empty($geral->getIdInstancia())) {
            throw new Exception('Todos os campos são obrigatórios');
        }

        $geralController = new \src\Controller\geralController();
        $geralController->atualizar($geral);

        http_response_code(200);
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
        http_response_code(500);
    }
}

function localizarGeral()
{
    try {
        if (!isset($_GET['id'])) {
            throw new Exception('Informe o ID do geral');
        }

        $geralController = new \src\Controller\geralController();
        $geral = $geralController->localizar($_GET['id']);

        echo json_encode($geral);
        http_response_code(200);
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
        http_response_code(500);
    }
}
