<?php

if (!isset($_GET['numero']) || !isset($_GET['instancia'])) {
    http_response_code(400);
    echo json_encode(["erro" => "Parâmetros 'numero' e 'instancia' são obrigatórios."]);
    exit;
}

$numero = $_GET['numero'];
$instancia = $_GET['instancia'];

$partesNumero = explode('@', $numero);
$numeroFormatado = $partesNumero[0] . '@s.whatsapp.net';

if (!preg_match('/^\d{10,13}$/', $partesNumero[0])) {
    http_response_code(400);
    echo json_encode(["erro" => "Formato inválido para o número."]);
    exit;
}

$url = "https://storage.essencialapi.app.br/typebot/changeStatus/$instancia";

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode([
        "remoteJid" => $numeroFormatado,
        "status" => "closed"
    ]),
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        'apikey: zYzP7ocstxh3Sscefew4FZTCu4ehnM8v436'
    ),
));

$resposta = curl_exec($curl);

if (curl_errno($curl)) {
    http_response_code(500);
    echo json_encode(["erro" => "Erro na requisição cURL.", "detalhes" => curl_error($curl)]);
    curl_close($curl);
    exit;
}

curl_close($curl);

header('Content-Type: application/json');
echo $resposta;
?>
