<?php
use WHMCS\Session;
use Carbon\Carbon;
use WHMCS\Database\Capsule;

$hook = array(
    'hook' => 'EmailPreLog',
    'function' => 'suiten_ForwardEmail'
);

global $suiten_nomorwhatsapp;
global $suiten_Whatsapp_Message;
global $KoreksiNomor;
global $client_id, $client_info;

if (!function_exists('suiten_ForwardEmail')) {
    function suiten_ForwardEmail($SuitenObject) {
        global $suiten_nomorwhatsapp;
        global $suiten_Whatsapp_Message;
        global $KoreksiNomor;
        global $client_id, $client_info;

        $global_module_name = 'Hostinoz Whatsapp API';
        $daftarforward = array();
        $daftarfwdadmin = array();
        $kirimkeclient = false;
        $kirimkeadmin = false;

        logActivity('SUITEN_DEBUG: suiten_ForwardEmail called');

        // Fetch the template settings
        foreach (Capsule::table('s10wa_templates')->where('s10wa_templatetitle', 'Forward Email to Whatsapp')->get() as $bacatemplate) {
            logActivity('SUITEN_DEBUG: Template status - ' . $bacatemplate->s10wa_templatestatus);

            if ($bacatemplate->s10wa_templatestatus == 1) {
                // Handle client forward template (s10wa_templatecontent)
                if (!empty($bacatemplate->s10wa_templatecontent)) {
                    // Split the template content by commas and trim any extra spaces
                    $daftarforward = array_map('trim', explode(',', html_entity_decode($bacatemplate->s10wa_templatecontent)));
                    $kirimkeclient = true;
                    logActivity('SUITEN_DEBUG: Forward client templates found: ' . print_r($daftarforward, true));
                }

                // Handle admin forward template (s10wa_templateenglish)
                if (!empty($bacatemplate->s10wa_templateenglish)) {
                    $daftarfwdadmin = array_map('trim', explode(',', html_entity_decode($bacatemplate->s10wa_templateenglish)));
                    $kirimkeadmin = true;
                    logActivity('SUITEN_DEBUG: Forward admin templates found: ' . print_r($daftarfwdadmin, true));
                }
            }
        }

        // Log the email subject being processed
        logActivity('SUITEN_DEBUG: Email Subject - ' . $SuitenObject['subject']);

        // Now match email subject with multiple forward templates
        $judulemail = $SuitenObject['subject'];
        $ketemu = false;

        // Check if the email subject matches client forward template
        if ($kirimkeclient) {
            foreach ($daftarforward as $cekjudul) {
                logActivity('SUITEN_DEBUG: Checking client forward template match: ' . $cekjudul);
                if (stripos($judulemail, trim($cekjudul)) !== false) {
                    logActivity('SUITEN_DEBUG: Email subject matches client forward template: ' . $cekjudul);
                    $ketemu = true;
                    break;
                }
            }
            if (!$ketemu) {
                logActivity('SUITEN_DEBUG: No match for client email subject in forward templates');
                $kirimkeclient = false;
            }
        }

        // Check if the email subject matches admin forward template
        $ketemu = false;
        if ($kirimkeadmin) {
            foreach ($daftarfwdadmin as $cekjudul) {
                logActivity('SUITEN_DEBUG: Checking admin forward template match: ' . $cekjudul);
                if (stripos($judulemail, trim($cekjudul)) !== false) {
                    logActivity('SUITEN_DEBUG: Email subject matches admin forward template: ' . $cekjudul);
                    $ketemu = true;
                    break;
                }
            }
            if (!$ketemu) {
                logActivity('SUITEN_DEBUG: No match for admin email subject in forward templates');
                $kirimkeadmin = false;
            }
        }

        // If no match for both client and admin, exit the hook
        if (!$kirimkeclient && !$kirimkeadmin) {
            return $hook;
        }

        // Process for client
        $client_id = $SuitenObject['userid'];
        foreach (Capsule::table('tblclients')->where('id', $client_id)->get() as $CustomerInfo) {
            $firstname = rtrim($CustomerInfo->firstname);
            $lastname = rtrim($CustomerInfo->lastname);
            $email = $CustomerInfo->email;
            $phonenumber = $CustomerInfo->phonenumber;
            $client_info = $firstname . ' ' . $lastname . ' (' . $email . ')';
        }

        $suiten_nomorwhatsapp = '';
        foreach (Capsule::table('s10wa_config')->where('suiten_Nama_Modul', $global_module_name)->get() as $modulwa_config) {
            $whatsapp_source = $modulwa_config->suiten_field_nomorwa;
            $whatsapp_admin = $modulwa_config->suiten_adminwa;
            $whatsapp_metode_kirim = $modulwa_config->suiten_sending_method;
        }

        // Get client WhatsApp number
        if ($whatsapp_metode_kirim == 'Custom') {
            foreach (Capsule::table('tblcustomfieldsvalues')->where([['fieldid', '=', $whatsapp_source], ['relid', '=', $client_id]])->get() as $datarecord) {
                $suiten_nomorwhatsapp = $datarecord->value;
            }
        } else {
            $suiten_nomorwhatsapp = $phonenumber;
        }

        $KoreksiNomor = suiten_koreksinomor($CustomerInfo->country, $suiten_nomorwhatsapp);

        // Get the email message content
        require_once(__DIR__ . "/../Html2Text.php");
        require_once(__DIR__ . "/../Html2TextException.php");

        $h2toptions = array(
            'ignore_errors' => true,
            'drop_links' => true,
        );

        try {
            $emailMessage = Soundasleep\Html2Text::convert($SuitenObject['message'], $h2toptions);
            logActivity("Successfully converted HTML to text for message ID: " . $SuitenObject['id']);
        } catch (Soundasleep\Html2TextException $e) {
            logActivity("Error converting HTML to text: " . $e->getMessage() . ($e->more_info ? " More info: " . $e->more_info : ""));
        }

        if (empty($emailMessage)) {
            logActivity('SUITEN_DEBUG: Email message content is empty or not provided');
        } else {
            logActivity('SUITEN_DEBUG: Email message content retrieved');
        }

        // If client email matched and number is valid, send WhatsApp message to client
        if ($kirimkeclient && $suiten_nomorwhatsapp != "" && strlen($suiten_nomorwhatsapp) > 8) {
            try {
                Capsule::connection()->transaction(function ($connectionManager) use ($KoreksiNomor, $emailMessage, $client_id, $client_info) {
                    $connectionManager->table('s10wa_sendmsg')->insert([
                        's10wa_date' => timeStampWhatsapp(),
                        's10wa_wanumber' => $KoreksiNomor,
                        's10wa_interval' => (int)4,
                        's10wa_message' => $emailMessage,
                        's10wa_msgtype' => (int)1,
                        's10wa_attachment' => '',
                        's10wa_clientid' => $client_id,
                        's10wa_clientinfo' => $client_info,
                        's10wa_status' => (int)0
                    ]);

                    logActivity('SUITEN_DEBUG: Forwarded to Client WhatsApp - ' . $KoreksiNomor);
                });
            } catch (\Exception $e) {
                logActivity('SUITEN_DEBUG: MySQL Error while sending to client: ' . $e->getMessage());
            }
        }

        // Send to Admin if required
        if ($kirimkeadmin && !empty($whatsapp_admin)) {
            try {
                $adminNumbers = explode(";", $whatsapp_admin);
                foreach ($adminNumbers as $adminNumber) {
                    $KoreksiNomor = suiten_koreksinomor($CustomerInfo->country, $adminNumber);
                    Capsule::connection()->transaction(function ($connectionManager) use ($KoreksiNomor, $emailMessage, $client_id, $client_info) {
                        $connectionManager->table('s10wa_sendmsg')->insert([
                            's10wa_date' => timeStampWhatsapp(),
                            's10wa_wanumber' => $KoreksiNomor,
                            's10wa_interval' => (int)4,
                            's10wa_message' => $emailMessage,
                            's10wa_msgtype' => (int)1,
                            's10wa_attachment' => '',
                            's10wa_clientid' => $client_id,
                            's10wa_clientinfo' => $client_info,
                            's10wa_status' => (int)0
                        ]);

                        logActivity('SUITEN_DEBUG: Forwarded to Admin WhatsApp - ' . $KoreksiNomor);
                    });
                }
            } catch (\Exception $e) {
                logActivity('SUITEN_DEBUG: MySQL Error while sending to admin: ' . $e->getMessage());
            }
        }

        return $hook;
    }
}

add_hook($hook['hook'], 1, $hook['function']);
?>
