<?php

declare(strict_types=1);

require '../vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;

require "../controllers/cloudinary-api.php";

//POS TRANSLATE
function getPosLanguage($lang)
{
    if ($lang == "es") {
        $getPosLanguage = file_get_contents("../lang/pos_es.json");
    } else if ($lang == "fr") {
        $getPosLanguage = file_get_contents("../lang/pos_fr.json");
    } else {
        $getPosLanguage = file_get_contents("../lang/pos_en.json");
    }

    $posTranslate = json_decode($getPosLanguage, true);

    return $posTranslate;
}

function SendWhatsAppText($phone, $message)
{
    try {

        $client = new Client([
            'base_uri' => 'http://144.126.149.203:3001/',
            'timeout'  => 30,
        ]);

        $payload = [
            "phone"   => preg_replace('/\D+/', '', $phone),
            "body"    => $message,
        ];
        $response = $client->get('', [
            'query' => [
                'type' => 'text',
                'data' => json_encode($payload)
            ]
        ]);

        return [
            "status"   => "success",
            "response" => json_decode((string) $response->getBody(), true)
        ];
    } catch (ConnectException $e) {

        return [
            "status"  => "error",
            "message" => "Connection error cannot connect to WhatsApp server on port 3001. ERROR: " . $e->getMessage()
        ];
    } catch (RequestException $e) {

        return [
            "status"  => "error",
            "message" => $e->getMessage()
        ];
    }
}

function sendWhatsAppImage(string $phone, string $url, string $caption = ""): array
{
    try {

        $client = new Client([
            'base_uri' => 'http://144.126.149.203:3001/',
            'timeout'  => 30,
        ]);

        $payload = [
            "phone"   => preg_replace('/\D+/', '', $phone),
            "body"    => $url,
            "caption" => $caption,
        ];
        $response = $client->get('', [
            'query' => [
                'type' => 'media',
                'data' => json_encode($payload)
            ]
        ]);

        return [
            "status"   => "success",
            "response" => json_decode((string) $response->getBody(), true)
        ];
    } catch (ConnectException $e) {

        return [
            "status"  => "error",
            "message" => "Connection error cannot connect to WhatsApp server on port 3001. ERROR: " . $e->getMessage()
        ];
    } catch (RequestException $e) {

        return [
            "status"  => "error",
            "message" => $e->getMessage()
        ];
    }
}


switch ($_GET["op"]) {

    case 'sendWhatsAppTextMessage':

        $toPhone = $_POST["toPhone"];
        $entName = $_POST["entName"];
        $replyTo = $_POST["replyTo"];
        $pos_lang = $_POST["pos_lang"];
        $message = $_POST["message"];

        $posTranslate = getPosLanguage($pos_lang);

        $finalMsg = "*{$entName}* \n\n";
        $finalMsg .= $message . "\n\n";
        $finalMsg .= "{$posTranslate['please_reply_to']}: {$replyTo}";

        $response = SendWhatsAppText($toPhone, $finalMsg);
        // echo $response;
        echo json_encode($response);

        break;


    case 'sendTicketWhatsApp':

        $imageData = $_POST["image"]; // Base64: data:image/png;base64
        $sale_id = $_POST["sale_id"];
        $toPhone = $_POST["toPhone"];
        $entName = $_POST["entName"];
        $replyTo = $_POST["replyTo"];
        $pos_lang = $_POST["pos_lang"];

        $caption = "*{$entName}* \n";

        $posTranslate = getPosLanguage($pos_lang);

        if (!empty($replyTo)) {
            $caption .= "{$posTranslate['for_questions_or_complaints_contact_this_number']}: {$replyTo}";
        }

        $sourceFilePath = $imageData;
        $saveToFolder = "evosyspos/tickets";
        $resourceType = "image";
        $fileName = "ticket_{$sale_id}";
        $oldFileToDelete = "";

        $resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, $resourceType, $fileName, $oldFileToDelete);
        $imageUrl = $resCloudUpload['secure_url'];

        $response = sendWhatsAppImage($toPhone, $imageUrl, $caption);
        echo json_encode($response);

        break;
}
