<?php
require 'conf.php';

$OpenAI = new OpenAI;
$BD = new Database;

header("Content-type: application/json; charset=utf-8");

$request_data = json_decode(file_get_contents("php://input"), true);

$log_data = "Request Data:\n" . print_r($request_data, true) . "\n\n";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ($request_data['event'] == "automation_event.message_created") {

        $remoteJid = $request_data['messages'][0]['sender']['identifier'];
        $conversation_id = $request_data['messages'][0]['conversation_id'];

        $account_id = $request_data['messages'][0]['account_id'];
        $contact_id = $request_data['messages'][0]['sender_id'];

        $Typebot = new Typebot($account_id);

        $mensagem = null;
        if (!isset($request_data['messages'][0]['attachments'])) {
            $mensagem = $request_data['messages'][0]['content'];
        } elseif (isset($request_data['messages'][0]['attachments']) and $request_data['messages'][0]['attachments'][0]['file_type'] == "audio") {

                $SpeechToText = $OpenAI->SpeechToText($request_data['messages'][0]['attachments'][0]['data_url']);
                if ($SpeechToText['http'] == 200 or $SpeechToText['http'] == 201) {
                    $mensagem = json_decode($SpeechToText['response'], true)['text'];
                }
                $log_data .= "Transcrição:\n" . print_r($SpeechToText, true) . "\n\n";
                
        } else {
            $retorno_typebot = $Typebot->MensagemDeTipoDesconhecido($conversation_id);
            $log_data .= "Tipo de mensagem não identificado\n" . print_r($retorno_typebot, true) . "\n\n";
        }

        if (!is_null($mensagem)) {
            $mensagem = LimparStringBD($mensagem);
            $log_data .= "Mensagem recebida:\n" . print_r($mensagem, true) . "\n\n";
            $BD->executarConsulta("INSERT INTO `mensagens_recebidas`(`mensagem`, `conversation_id`, `account_id`, `datetime`, `id`) VALUES ('$mensagem','$conversation_id','$account_id','" . date('Y-m-d H:i:s') . "',null)");

            $id_inserido = $BD->conn->insert_id;
            $tempo_anterior = date('Y-m-d H:i:s');
            sleep(SEGUNDOS_AGUARDANDO_NOVAS_MENSAGENS);
            if ($Exec = $BD->executarConsulta("SELECT `mensagem` FROM `mensagens_recebidas` WHERE account_id='$account_id' AND `datetime`>'$tempo_anterior' AND id<>'$id_inserido' AND conversation_id='$conversation_id'")) {
                if ($Exec->num_rows > 0) {
                    $log_data .= "Há mais mensagens recebidas (coletanto mensagens)\n\n";
                } else {
                    if ($Exec = $BD->executarConsulta("SELECT `mensagem`,`datetime` FROM `mensagens_recebidas` WHERE account_id='$account_id' AND conversation_id='$conversation_id' ORDER BY id DESC")) {
                        $mensagens = array();
                        $mensagens_conteudo = array();
                        while ($Dados = $Exec->fetch_assoc()) {
                            if (count($mensagens) == 0) {
                                $ultimo_datetime = $Dados['datetime'];
                            } else {
                                $ultimo_datetime = end($mensagens)['datetime'];
                                if ((strtotime($ultimo_datetime) - strtotime($Dados['datetime'])) >= 8) {
                                    break;
                                }
                            }
                            $mensagens[] = ['datetime' => $Dados['datetime'], 'mensagem' => $Dados['mensagem']];
                            $mensagens_conteudo[] = $Dados['mensagem'];
                        }

                        $mensagem = implode(' ', array_reverse($mensagens_conteudo));

                        $log_data .= "Mensagem para o fluxo:\n" . print_r($mensagem, true) . "\n\n";
                        $retorno_typebot = $Typebot->Fluxo($conversation_id, $mensagem, $prefilledVariables = '{"account_id":"' . $account_id . '","remoteJid":"' . $remoteJid . '","pushName":"' . $request_data['messages'][0]['sender']['name'] . '"}');
                        
                        $BD->executarConsulta("DELETE FROM `mensagens_recebidas` WHERE account_id='$account_id' AND `datetime`<'".date('Y-m-d H:i:s')."' AND id<>'$id_inserido' AND conversation_id='$conversation_id'");
                        
                        $log_data .= "Retorno do typebot e envios do fluxo:\n" . print_r($retorno_typebot, true) . "\n\n";
                    }
                }
            }
        }
    }
}elseif(isset($_GET['conversation_id']) and isset($_GET['account_id']) and isset($_GET['condicao']) and isset($_GET['pausar_despausar'])){
    if($_GET['condicao']==1 or $_GET['condicao']==0){
        $Typebot = new Typebot($_GET['account_id']);
        $retorno_typebot = $Typebot->Pausar_Despausar(removerNaoNumericos($_GET['conversation_id']), $_GET['condicao']);
        $retorno_typebot = "Retorno da tentativa de modificação de estado: ".print_r($retorno_typebot, true);
        http_response_code(200);
    }else{
        $retorno_typebot = "Condição inválida. 0 para despausar e 1 para pausar.\n\n";
        http_response_code(400);
    }
    $log_data .= "\n" . print_r($retorno_typebot, true) . "\n".print_r($_GET, true)."\n\n";
}elseif(isset($_GET['conversation_id']) and isset($_GET['account_id']) and isset($_GET['deletar'])){
    http_response_code(200);
        $Typebot = new Typebot($_GET['account_id']);
        $retorno_typebot = $Typebot->Deletar(removerNaoNumericos($_GET['conversation_id']));
        $retorno_typebot = "Retorno da tentativa de modificação de deletar a sessão: ".print_r($retorno_typebot, true);
    $log_data .= "\n" . print_r($retorno_typebot, true) . "\n".print_r($_GET, true)."\n\n";
}else{
    http_response_code(400);
}

$log_data .= "\n\n==============================\n\n";
file_put_contents('log.txt', $log_data, FILE_APPEND);
