<?php
    /*
       *****************************************************************************
       * MEGA Digital Space - by MEGA Digital Studio                               *
       * ------------------------------------------------------------------------- *
       * CMS Website:  https://megadigital.space                                   *
       * License:  https://megadigital.space/license                               *
       * Owner:  Giorgi Basharuli                                                  *
       * Contact:  online@megadigital.studio                                       *
       * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
       * Website:  https://megadigital.studio                                      *
       * ------------------------------------------------------------------------- *
       * Description: This file is a part of the MEGA Digital Space CMS system.    *
       * Unauthorized distribution, modification, or commercial use is strictly -  *
       * prohibited without prior written permission.                              *
       * ------------------------------------------------------------------------- *
       * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
       * All rights reserved.                                                      *
       *****************************************************************************
   */

    date_default_timezone_set('UTC');

    require_once(__DIR__ . '/../../engine/data/config.php');
    require_once __DIR__ . '/../../vendor/autoload.php';

    require_once(__DIR__ . '/../../engine/jobs/init_job.php');

    mailingLog("RESEND mailing cron start " . date('Y-m-d H:i:s'));

    use Twilio\Rest\Client;

    $twilio = new Client(
        $config["twilio_provider"]["username"],
        $config["twilio_provider"]["password"]
    );
    $twilioFrom = $config["twilio_provider"]["twilio_phone_number"];

    $queueItems = $db_connect->select('mailing_queue', '*', [
        'status' => 'busy',
        'ORDER' => [
            'id' => 'DESC'
        ],
        'LIMIT' => 50
    ]);


    foreach ($queueItems as $item) {
        try {
            $mailing = $db_connect->get('mailings', '*', ['id' => $item['mailing_id']]);

            $now = new DateTime('now', new DateTimeZone('UTC'));
            if (empty($mailing["scheduled_at"])) {
                $process = true;
            } else {
                $scheduled = new DateTime($mailing['scheduled_at'], new DateTimeZone('UTC'));

                $diff = abs($now->getTimestamp() - $scheduled->getTimestamp());
                $isSame = $diff <= 120;
                $process = $isSame || $now >= $scheduled;
            }

            if ($process) {
                mailingLog("Start mailing queue ID:" . $item["id"]);

                $content = $db_connect->get('mailing_contents', '*', ['mailing_id' => $item['mailing_id']]);
                $user = $db_connect->get('users', '*', ['id' => $item['user_id']]);
                $db_connect->update('mailings', ['status' => 'sending'], ['id' => $item['mailing_id']]);

                if (!$user) throw new Exception("User not found: {$item['user_id']}");

                switch ($item['channel']) {
                    case 'sms_text':
                        if (!$user["phone"]) throw new Exception("User phone is empty: {$item['user_id']}");

                        if ($mailing['type'] === 'sms_text') {
                            $response = $twilio->messages->create(
                                $user['phone'],
                                [
                                    'from' => $twilioFrom,
                                    'body' => $content['text']
                                ]
                            );
                            /*
                                                        $response = $twilio->messages->create(
                                                            'whatsapp:'.$user['phone'],
                                                            [
                                                                'from' => 'whatsapp:'.$twilioFrom, // sandbox или approved номер
                                                                'body' => $content['text']
                                                            ]
                                                        );*/
                        }
                        break;

                    case 'sms_audio':
                        if (!$user["phone"]) throw new Exception("User phone is empty: {$item['user_id']}");

                        if ($mailing['type'] === 'sms_audio') {
                            $mediaUrls = [];
                            if ($content['media_url']) $mediaUrls[] = $content['media_url'];
                            $response = $twilio->messages->create(
                                $user['phone'],
                                [
                                    'from' => $twilioFrom,
                                    'body' => $content['text'] ?: 'Аудио сообщение',
                                    'mediaUrl' => $mediaUrls
                                ]
                            );
                        }
                        break;

                    case 'call_audio':
                        if (!$user["phone"]) throw new Exception("User phone is empty: {$item['user_id']}");

                        if ($mailing['type'] === 'call_audio') {
                            $mediaUrls = [];
                            if ($content['media_url']) $mediaUrls[] = $content['media_url'];
                            $response = $twilio->calls->create(
                                $user['phone'],
                                $twilioFrom,
                                [
                                    'twiml' => '<Response><Play>'. $content['media_url'] . '</Play></Response>'
                                ]
                            );
                        }
                        break;

                    case 'text_graphic_sms':
                        if (!$user["phone"]) throw new Exception("User phone is empty: {$item['user_id']}");
                        mailingLog(json_encode($_SERVER));

                        $response = $twilio->messages->create(
                            $user['phone'],
                            [
                                'from' => $twilioFrom,
                                'body' => $content['text'],
                                'mediaUrl' => [$content['media_url']]
                            ]
                        );

                        break;

                    case 'text_to_speech':
                        if (!$user["phone"]) throw new Exception("User phone is empty: {$item['user_id']}");

                        if ($mailing['type'] === 'text_to_speech') {
                            $response = $twilio->calls->create(
                                $user['phone'],
                                $twilioFrom,
                                [
                                    'twiml' => "
                                    <Response>
                                        <Say voice='alice' language='en-US'>
                                            {$content['text']}
                                        </Say>
                                    </Response>
                                "
                                ]
                            );

                        }
                        break;

                    case 'email':
                        if (!$user["email"]) throw new Exception("User email is empty: {$item['user_id']}");

                        if ($user['email']) {
                            $subject = $mailing['title'];
                            $body = $content['text'] ?: '';

                            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);

                            $mail->isSMTP();
                            $mail->Host       = $config["email_settings"]["host"];
                            $mail->SMTPAuth   = $config["email_settings"]["smtp_auth"];
                            $mail->Username   = $config["email_settings"]["username"];
                            $mail->Password   = $config["email_settings"]["password"];
                            $mail->SMTPSecure = $config["email_settings"]["smtp_secure"];
                            $mail->Port       = $config["email_settings"]["port"];

                            $mail->setFrom('megadigital@docsign.space', 'Mega Digital Studio');
                            $mail->addAddress($user['email'], $user['email']);

                            $mail->isHTML(true);
                            $mail->Subject = $subject;
                            $mail->Body    = $body;
                            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

                            $mail->send();

                        }
                        break;

                    default:
                        throw new Exception("Unknown channel: " . $item['channel']);
                }

                mailingLog("FINISH mailing queue ID:" . $item["id"]);

                $db_connect->update('mailing_queue', ['status' => $response->status ?? 'sent', 'error' => $response->errorMessage ?? '', 'sent_at' => date('Y-m-d H:i:s'), "provider_message_id" => $response->sid], ['id' => $item['id']]);
                $db_connect->update('mailings', ['status' => 'done'], ['id' => $item['mailing_id']]);
            }

        } catch (Exception $e) {
            mailingLog("Error mailing queue ID:" . $item["id"]. " ERROR:" . $e->getMessage());

            $db_connect->update('mailing_queue', ['status' => 'failed', 'error' => $e->getMessage()], ['id' => $item['id']]);
            $db_connect->update('mailings', ['status' => 'failed'], ['id' => $item['mailing_id']]);
            error_log("Mailing error for queue item {$item['id']}: " . $e->getMessage());
        }
    }