<?php

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

use Dotenv\Dotenv;

// Load the .env file
$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

// 📧 Function to send email using Resend API
function sendEmailTicket($send_to, $subject, $htmlBody = "", $reply_to = "", $cc = [], $bcc = [], $fileAttachment = null)
{
    $resend = Resend::client($_ENV['RESEND_ACCESS_KEY']);

    try {
        // Prepare the basic email data
        $emailData = [
            'from' => "no-reply@{$_ENV['PRODUCT_DOMAIN']}", // Get domain from environment variables
            'to' => $send_to, // Array of recipients
            'reply_to' => $reply_to, // Reply-to address
            'subject' => $subject, // Subject of the email
            'html' => $htmlBody, // HTML body content
        ];

        // Add CC if provided
        if (!empty($cc)) {
            $emailData['cc'] = $cc;  // CC recipients
        }

        // Add BCC if provided
        if (!empty($bcc)) {
            $emailData['bcc'] = $bcc;  // BCC recipients
        }

        // ✅ Handle STRING (no file saved) Base64 attachment directly
        if (!empty($fileAttachment) && is_array($fileAttachment)) {

            if (empty($fileAttachment['filename']) || empty($fileAttachment['content'])) {
                throw new \Exception("Invalid attachment format.");
            }

            $emailData['attachments'] = [
                [
                    'filename' => $fileAttachment['filename'],
                    'content'  => $fileAttachment['content'], // already base64
                    'type'     => $fileAttachment['type'] ?? 'application/pdf',
                ]
            ];
        }

        // Send email via Resend API
        $result = $resend->emails->send($emailData);

        $response = array("emailId" => $result, "status" => "success", "title" => "Success", "message" => "Email sent successfully");
        return $response;  // Return result if successful

    } catch (\Exception $e) {
        // Handle exceptions and errors
        $response = array("status" => "error", "title" => "Error", "message" => "Email could not be sent", "error" => "Error: " . $e->getMessage() . "");
        return $response;
    }
}


//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;
}

switch ($_GET["op"]) {

    case 'sendTicketEmail':

        $htmlBody = $_POST["htmlContent"];
        $send_to = $_POST["toEmail"];
        $saleId = $_POST["saleId"];
        $entName = $_POST["entName"];
        $reply_to = $_POST["replyTo"];
        $replyToPhone = $_POST["replyToPhone"];
        $pos_lang = $_POST["pos_lang"];

        // POS TRANSLATE
        $posTranslate = getPosLanguage($pos_lang);

        $subject = "{$entName} - Sale Ticket - {$saleId}";

        if (!empty($reply_to)) {
            $htmlBody .= "<p>{$posTranslate['for_questions_or_complaints_send_an_email_to_this_address']}: <a href='mailto:{$reply_to}'>{$reply_to}</a></p>";
        } else {
            $htmlBody .= "{$posTranslate['for_questions_or_complaints_contact_this_number']}: {$replyToPhone}";
        }

        // $fileAttachment = '';  // Single file attachment
        // $cc = [''];  // Optional CC
        // $bcc = [''];  // Optional BCC

        $response = sendEmailTicket($send_to, $subject, $htmlBody, $reply_to);
        // echo $response->toJson();
        echo json_encode($response);

        // {"id":"47036610-b2af-403f-8f47-d18770b079bc"}

        break;
}
