<?php
/***
* Login Script
* Author: Aarti
* Date: 29-02-2024
* Description: This file uses the reply option on mail send user.
**/
include_once "../../config/web_mysqlconnect.php"; // Database file incluede
include "../web_function.php"; // handling common function
// include "omnichannel_function.php";

$caseid = $_REQUEST['caseid'];
$customerid = $_REQUEST['customerid'];
//get value
$view=$_GET['view'];
$cemail=$_GET['cemail'];
$uid=$_GET['uid'];
$subject= "(ID:$uid)";	
$addbtn_sms=$_REQUEST['addbtn_sms'];
$ticketid=$_REQUEST['iid']; 
$replyid = $_REQUEST['replyid'];
$reginoal_spoc = ($_SESSION['reginoal_spoc']!='') ? $_SESSION['reginoal_spoc'] : 3;
$reply_to = $_REQUEST['reply_to'] ?? "";
$v_cc_email=$_REQUEST['v_cc_email'];//cc
$userid = $_SESSION['userid'] ?? '';

// this code for forward[aarti][06-02-2026]
$fwdflag = $_REQUEST['fwdflag'] ?? '';
// if(!empty($fwdflag)){
    $query5 = mysqli_query($link, "SELECT v_body,v_toemail,v_fromemail,v_subject,d_email_date FROM $db.web_email_information WHERE EMAIL_ID='$replyid'");
    $query5 = mysqli_fetch_array($query5);
    $originalMessage = $query5['v_body'];
    $mail_from_email = $query5['v_fromemail'];
    $mail_to_email = $query5['v_toemail'];
    $mail_date = $query5['d_email_date'];
    $mail_subject = $query5['v_subject'];
    $mail_from_name = getFirstNameByEmail($mail_to_email);

// }
// close
function getFirstNameByEmail($email) {
    global $link,$db;
    $sql = "SELECT fname FROM {$db}.web_accounts WHERE email = ?";
    $stmt = mysqli_prepare($link, $sql);

    if (!$stmt) {
        return '';
    }
    mysqli_stmt_bind_param($stmt, 's', $email);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $fname);

    $result = '';
    if (mysqli_stmt_fetch($stmt)) {
        $result = $fname;
    }

    mysqli_stmt_close($stmt);
    return $result;
}
function log_debug($msg) {
    $file = 'attachment_debug_log.txt';
    $entry = "[" . date('Y-m-d H:i:s') . "] $msg\n";
    file_put_contents($file, $entry, FILE_APPEND);
}
function logUserAction($link, $db, $user_id, $actionlog, $comments) {
    $ip = getenv('REMOTE_ADDR') ?: '';
    $sql = "INSERT INTO {$db}.web_audit_history (user_id, action, created_on, ticket_id, comments, ip_address) VALUES (?, ?, NOW(), NULL, ?, ?)";
    $stmt = mysqli_prepare($link, $sql);
    mysqli_stmt_bind_param($stmt, "isss", $user_id, $actionlog, $comments, $ip);
    return mysqli_stmt_execute($stmt);
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // print_r($_POST); die;
    log_debug("POST request received");

    // ---- STEP 0: Decode attachments JSON or comma list ----
    $liValuesJson = $_POST['liValues'] ?? '';
    log_debug("liValues JSON received: " . var_export($liValuesJson, true));

    $liValues = json_decode($liValuesJson, true);
    if (!is_array($liValues)) {
        $liValues = explode(',', $liValuesJson);
    }
    $liValues = array_filter(array_map('trim', $liValues));
    log_debug("liValues final array: " . var_export($liValues, true));

    // ---- STEP 1: Define base and datewise upload directories ----
    $baseUploadDir = "/home/unistorage/2224/omnichannel_config/email_attachments/";
    $publicBasePath = "unistorage/2224/omnichannel_config/email_attachments/"; // path saved in DB
    $currentDate = date("Y-m-d");

    $uploadDir = rtrim($baseUploadDir, '/') . "/" . $currentDate . "/";
    $publicDir = rtrim($publicBasePath, '/') . "/" . $currentDate . "/";

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
        log_debug("Created upload directory: $uploadDir");
    }

    $imapBasePath = "../../../unistorage/2224/imap/";
    $tempDir = $uploadDir . "temp_" . time() . "/"; // temporary folder for zipping
    mkdir($tempDir, 0777, true);

    $savedFiles = [];

    // ---- STEP 2: Copy existing attachments from IMAP folder ----
    foreach ($liValues as $file) {
        $sourcePath = $imapBasePath . $file;
        $destinationPath = $tempDir . basename($file);

        if (file_exists($sourcePath)) {
            if (copy($sourcePath, $destinationPath)) {
                log_debug("Copied existing attachment: $sourcePath -> $destinationPath");
                $savedFiles[] = basename($file);
            } else {
                log_debug("Failed to copy existing file: $sourcePath");
            }
        } else {
            log_debug("Source file missing: $sourcePath");
        }
    }

    // ---- STEP 3: Save newly uploaded files ----
    if (!empty($_FILES['attachments']['name'][0])) {
        foreach ($_FILES['attachments']['name'] as $index => $filename) {
            $tmpName = $_FILES['attachments']['tmp_name'][$index];
            $destination = $tempDir . basename($filename);

            if (move_uploaded_file($tmpName, $destination)) {
                $savedFiles[] = basename($filename);
                log_debug("File uploaded successfully: $filename");
            } else {
                log_debug("Failed to upload file: $filename");
            }
        }
    } else {
        log_debug("No new attachments uploaded.");
    }

    // Remove duplicates
    $allFiles = array_unique($savedFiles);
    log_debug("All attachments combined: " . var_export($allFiles, true));

    // ---- STEP 4: Create ZIP or retain single file ----
    $targetPath = "";
    if (count($allFiles) > 1) {
        // Multiple attachments → create one ZIP only
        $zipFileName = "attachments_" . date("Y-m-d_H-i-s") . ".zip";
        $zipFilePath = $uploadDir . $zipFileName;

        $zip = new ZipArchive();
        if ($zip->open($zipFilePath, ZipArchive::CREATE) === TRUE) {
            foreach ($allFiles as $file) {
                $filePath = $tempDir . $file;
                if (file_exists($filePath)) {
                    $zip->addFile($filePath, basename($filePath));
                    log_debug("Added to ZIP: $filePath");
                }
            }
            $zip->close();
            log_debug("ZIP created successfully: $zipFilePath");
            $targetPath = $publicDir . $zipFileName;

        } else {
            log_debug("Failed to create ZIP archive");
        }

        // Delete temp folder and its contents (since only ZIP should remain)
        foreach (glob($tempDir . "*") as $tempFile) {
            @unlink($tempFile);
        }
        @rmdir($tempDir);
        log_debug("Temporary files deleted after ZIP creation.");

    } elseif (count($allFiles) == 1) {
        // Only one attachment → move it to main folder
        $singleFile = $allFiles[0];
        $sourceFile = $tempDir . $singleFile;
        $destinationFile = $uploadDir . $singleFile;

        if (rename($sourceFile, $destinationFile)) {
            log_debug("Single attachment moved: $sourceFile -> $destinationFile");
            $targetPath = $publicDir . $singleFile;
        } else {
            log_debug("Failed to move single attachment: $sourceFile");
        }

        @rmdir($tempDir); // clean temp folder
    } else {
        log_debug("No attachments found.");
        @rmdir($tempDir);
    }

    // ---- STEP 5: Email processing ----
    $Mail = $_POST['V_EmailId'] ?? '';
    log_debug("Mail: $Mail");

    $V_Content = $link->real_escape_string($_POST['V_Content'] ?? '');
    $V_Subject = $_POST['V_Subject'] ?? '';
    $view = $_POST['view'] ?? '';
    $AccountName = $_POST['AccountName'] ?? '';
    $v_queue_type = $_POST['v_queue_type'] ?? '';
    $i_templateid = !empty($_POST['i_templateid'])
        ? explode("|", $_POST['i_templateid'])[0]
        : 0;

    $replyid = $_REQUEST['replyid'] ?? 0;
    $caseid = $_REQUEST['caseid'] ?? 0;
    $customerid = $_REQUEST['customerid'] ?? 0;
    $userid = $_SESSION['userid'] ?? 0;
    $todaytime = date("Y-m-d H:i:s");
    $from = isset($_REQUEST['forward']) ? $from_email : from_email;

    $pos = stripos($V_Subject, "[TICKET - " . ($_REQUEST['iid'] ?? '') . "] ");
    $V_Subject = is_int($pos)
        ? $V_Subject
        : (is_numeric($_REQUEST['iid'] ?? '') ? "[TICKET -" . $_REQUEST['iid'] . "] " . $V_Subject : $V_Subject);

    log_debug("Final Subject: $V_Subject");
    log_debug("Final TargetPath (for DB): $targetPath");

    $uploadedFiles = $targetPath;
    $queue_type = ($v_queue_type == 'inquiry') ? 'inquiry' : 'complain';

    $data_email = [
        'Mail' => $Mail,
        'from' => $from,
        'V_Subject' => $V_Subject,
        'V_Content' => $V_Content,
        'V_rule' => $uploadedFiles,
        'todaytime' => $todaytime,
        'view' => $view,
        'subjectid' => $_REQUEST['subjectid'] ?? '',
        'i_templateid' => $i_templateid,
        'queue_type' => $queue_type,
        'caseid' => $caseid,
        'customerid' => $customerid,
        'parent_id'  => $replyid,
        'reply_mail'=>true
    ];

    log_debug("Prepared data_email: " . var_export($data_email, true));

    insert_emailinformationout($data_email);
    
    $comments = 'Replied to email: ' . $Mail;
    logUserAction($link, $db, $userid, 'reply_mail', $comments);

    // ---- STEP 6: Update database ----
    // updating other replied details available in the table [vastvikta][20-1-2026]
    $sql_update = "UPDATE $db.web_email_information 
                   SET Flag = 1, email_replay_status = 1 , replied_by = '$userid', replied_date = NOW()";
    if ($_SESSION['user_group'] === '070000') {
        $sql_update .= ",
            visibility = 1,
            replied_by = '$userid',
            replied_date = NOW()";
        // I have comment this code need to be check with samir sir - Aarti 30-01-2026
        // $sql_update .= ",
        //     agent_assigned = '$userid',
        //     assigned_date = NOW(),
        //     visibility = 1,
        //     replied_by = '$userid',
        //     replied_date = NOW()";
    }
    $sql_update .= " WHERE EMAIL_ID = $replyid";
    mysqli_query($link, $sql_update);
    log_debug("Updated web_email_information: $sql_update");

    // ---- STEP 7: Audit log ----
    $userName = $_SESSION['logged'] ?? '';
    if($_GET['fwdflag'] == '1'){
        $comments = "{$userName} has forward on mail ID {$replyid}";
    }else{
        $comments = "{$userName} has Replied on mail ID {$replyid}";
    }
    add_audit_log($userid, 'mail_reply', $caseid, $comments, $db);

    log_debug("Upload + mail process complete.");
    ?>

    <script type="text/javascript">
        setTimeout(function () {
            window.top.close();
        }, 2000);
    </script>

    <?php
    $error = "Message has been sent to $Mail";
    log_debug("Success: $error");
}
$signatureHtml = '';

$sql = "
    SELECT MailSignature, MailSignImage
    FROM $db.tbl_mailformats
    WHERE MailStatus = 1
    LIMIT 1
";

$res = mysqli_query($link, $sql);

if ($row = mysqli_fetch_assoc($res)) {

    $signatureText = $row['MailSignature'];       // HTML text
    $signatureImg  = $row['MailSignImage'];       // admin/SignatureImage/123456.jpg

    $fullName = ucwords(strtolower(trim($_SESSION['full_name'])));
$signatureText = str_replace('%yourname%', $fullName, $signatureText);
    $signatureHtml .= '<hr style="border:0;border-top:1px solid #ddd;">';
    $signatureHtml .= '<div style="font-size:13px;color:#333;">';
     $signatureHtml .= $signatureText;
    if (!empty($signatureImg)) {
        $signatureHtml .= '<br>
            <img 
                src="'.$SiteURL.'CRM/'.$signatureImg.'"
          
                  style="margin-left:0!important; margin-right:auto; text-align:left!important;"
    width="120opx"
            >';
    }
    $signatureHtml .= '</div>';
}
?>



<!-- Jquery and css code start -->
 <!DOCTYPE html>
 <html lang="en">
    <head>
        <meta http-equiv="Content-Language" content="en-us">
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <script src="<?=$SiteURL?>public/js/jquery.min.js"></script>
        <!-- <link rel="stylesheet" type="text/css" href="home_page/css/style.css" /> -->
        <link rel="stylesheet" type="text/css" href="<?=$SiteURL?>public/css/email_template_css.css" /> 
        <!-- DataTables JS ADDED THIS file as it was giving error datatable not defined [vastvikta][09-01-2026dn.ckeditor.com] -->
        <script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
        <!-- DataTables CSS -->
        <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/jquery.dataTables.min.css">
        <!-- jquery code start File upload -->
        <style type="text/css"> .myclass{ display: block !important;  } </style>
        <!-- CKeditor new code added 21-02-2024 -->
         <script src="https://cdn.ckeditor.com/ckeditor5/41.3.1/classic/ckeditor.js"></script>

        <link rel="stylesheet" type="text/css" href="<?=$SiteURL?>CRM/omnichannel_config/css/web_send_email_reply.css">
        <style>
        .ck-content figure.image {
            text-align: left !important;
        }

        .ck-content figure.image img {
            margin-left: 0 !important;
            margin-right: auto !important;
            display: block;
        }

        input[type=text]{ border:1px solid #A9A6A6; border-radius:2px; padding:4px; width:99%; }
        body {
            padding: 20px;
        }
        .btn-file {
            position: relative;
            overflow: hidden;
        }
        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }	
        ul {
            list-style-type: none;
        }
        li {
            font-family: Arial, sans-serif;
            font-size: 14px;
        }
        a {
            color: purple;
            text-decoration: underline;
        }
        /*ckeditor__editable*/
        .ck.ck-content.ck-editor__editable.ck-rounded-corners.ck-editor__editable_inline.ck-blurred {
            height: 200px;
        }
        /* Full-screen background blur and loader */
        #loaderOverlay {
            display: none; /* Initially hidden */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8); /* Semi-transparent white background */
            z-index: 9999;
            backdrop-filter: blur(5px); /* Apply blur */
        }

        /* Loader in the center */
        #loader {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }    
/*Multiple email selection-Aarti-06-04-2026*/
.email-container {
    min-height: 38px;
    width: 400px;
    border: 1px solid #ccc;
    padding: 5px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 5px;
    background: #fff;
    border-radius: 4px;
    cursor: text;
}

.email-tag {
    display: inline-flex;
    align-items: center;
    background: #e7f3ff;
    border: 1px solid #b3d7ff;
    border-radius: 15px;
    padding: 4px 8px;
    font-size: 13px;
    color: #004085;
}

.email-tag .remove-email {
    margin-left: 8px;
    cursor: pointer;
    color: #d00;
    font-weight: bold;
}

.email-input {
    border: none;
    outline: none;
    flex: 1;
    min-width: 180px;
    font-size: 14px;
    padding: 5px;
}
</style>

    </head>
<body>
    
    <span id="closeButton" style="position: absolute; top: 10px; right: 15px; font-size: 20px; cursor: pointer;">Close</span>

	<form id="fileupload" method="POST" enctype="multipart/form-data">
		<input type="hidden" name="replyid" id="replyid" value="<?=$replyid?>">
	<table align='center' width="90%" border="0" cellspacing="0">
		<tr class='mail-pagination'>
			<td valign=middle align='left' class='normaltextabhi'>
				<input type="submit" name="addbtn_email" id="compose" class="compose" value="Send" onclick='javascript:return validate();' 
				style='float:left; width:auto; margin-bottom:4px;'>
            <?php

			$q_reply = mysqli_query($link, "SELECT * FROM $dbname.web_email_information WHERE EMAIL_ID='$replyid'");
            while ($row_reply = mysqli_fetch_array($q_reply)) {
                $d_email_date = $row_reply['d_email_date'];
                $reply_body = "<br><br><br><hr>" . $row_reply['v_body'];
                $reply_body = nl2br(quoted_printable_decode($reply_body));
                $reply_subject = $row_reply['v_subject'];
                if (!empty($ticketid)) {
                    // $ticketTag = "[TICKET ID - $ticketid]";
                    if($_GET['fwdflag'] == '1'){
                        $ticketTag = "FW:";
                        $reply_to = '';
                    }else{
                        $ticketTag = "RE:";
                    }
                    if (stripos($reply_subject, $ticketTag) === false) {
                        $reply_subject = "$ticketTag " . $reply_subject;
                    }
                }
                $v_cc_email = $row_reply['v_cc_email'];
                $v_queue_type = $row_reply['queue_type'];

                // Parse attachments safely
                $multi_attach_raw = trim($row_reply['V_rule']);
                $multi_attach = !empty($multi_attach_raw) ? explode(",", $multi_attach_raw) : [];
                $logoFile = defined('BIS_LOGO_FILE') ? BIS_LOGO_FILE : $dbheadlogo;
                $signatureimages = '<img src="' . $SiteURL . 'public/images/' . $logoFile . '" title="BIS Research" alt="BIS Research" style="width:100px;height:auto;max-height:40px;margin-top:10px;">';
            }
            ?>

			</td>
		</tr>
	</table>
	<div id="myDiv" style="position:relative;top:50px;left:1px;background-color:white;width:504px;display:none;"></div>
	<!-- Dropdown Menu-->
	<table width="90%" BORDER='0' align="center" cellpadding='0' cellspacing='0'>
		<? if($error!=''){?>
		<tr>
		<td style="color:#ffffff; width:100%; background:#00CC66; padding:5px; border:1px solid #02944b; text-align:center;"><?=$error?></td>
		</tr>
		<? } ?>
		<tr>
			<td style='border-bottom:1px solid #DBE1F1;'><font face="verdana" color=""><b>&nbsp;Compose Mail</b></font></td>
		</tr>
		<tr>
			<td class="contentRed" colspan="2" align="center">&nbsp;</td>
		</tr>
		<tr>
			<td>
				<style type="text/css">.tbl td{ padding: 4px; border-color: #e3e2e2;  }</style>
				<table width="100%" border="1" cellpadding="4" cellspacing="1" align="center" class="tbl" style='border-collapse: collapse;' bordercolor='#e3e2e2'>
                <!-- readonly in case when there is value [vastvikta][03-05-2025] -->
                    <tr>
                        <td valign="top">
                            <font color="#000000" face="verdana" size="2">To Email-Id<span class="orangeTxt">*</span></font>
                        </td>
                        <td>
                           <!--  <input type="text" name="V_EmailId" id="V_EmailId" 
                                value="<?= htmlspecialchars($reply_to) ?>" 
                                class="textbox" size="40" 
                                style="<?= $dis ?> margin-top: 2px;" 
                                placeholder="To :"
                                > -->
                               <!-- Multiple email selection Aarti 06-04-2206-->
    
                                    <div id="emailContainer" class="email-container" style="<?= $dis ?> margin-top:2px;">
                                        <input type="text" id="emailInput" class="email-input" placeholder="Type email and press Enter">
                                    </div>

                                    <input type="hidden" name="V_EmailId" id="V_EmailId" value="<?= htmlspecialchars($reply_to) ?>">

                        </td>
                    </tr>

					<tr>
						<td><font color="#000000" face=verdana size=2>Subject<span class="orangeTxt">*</span></font></td>
						<td>
                            <input 
                                type="text" 
                                name="V_Subject" 
                                class="textbox" 
                                size="40" 
                                value="<?= htmlspecialchars($reply_subject) ?>" 
                                <?= !empty($reply_subject) ? 'readonly' : '' ?>>
                            <input type="hidden" name="customerid" id="customerid"  value="<?=$customerid?>">
                            <input type="hidden" name="caseid" id="caseid"  value="<?=$caseid?>">
						</td> 
					</tr>

					<tr>
						<td ><font color="#000000" face=verdana size=2>Created on</font></td>
						<td >
                            <!-- <font face="verdana" size=2><?=date("d-m-Y H:i:s",strtotime($d_email_date))?></font> changed date code [vastvikta][03-05-2025] -->
						<font face="verdana" size=2><?=date("d-m-Y H:i:s")?></font>
						</td>
					</tr>

					<tr>
                        <!--  UPDATED the code related to the template [vastvikta][14-11-2025] -->
                        <td>
                            <font color="#000000" face="verdana" size="2">
                                Template<span class="orangeTxt">*</span>
                            </font>
                        </td>

                        <td>
                            <?php
                            // Base query
                            $userId = $_SESSION['userid'];
                            $query = "SELECT * FROM $db.`reply_templates`
                                    ORDER BY 
                                        CASE WHEN created_by = '$userId' THEN 0 ELSE 1 END,
                                        template_name ASC";
                            $result = $link->query($query);

                            ?>

                            <select name="template" id="template">
                                <option value="">Select template</option>

                                <?php 
                                while ($row = $result->fetch_assoc()):
                            
                                    $safeContent = htmlspecialchars($row['template_content']);
                                ?>
                                <option 
                        value="<?= $row['id'] ?>" 
                        data-content='<?= htmlspecialchars($row['template_content'], ENT_QUOTES, 'UTF-8') ?>'>
                        <?= htmlspecialchars($row['template_name']) ?>
                    </option>

                                <?php endwhile; ?>
                            </select>
                        </td>
                    </tr>
    					<tr>
                            <? if($action == "") {?>
                                <td ><font color="#000000" face=verdana size=2>Content<span class="orangeTxt">*</span></font></td>
                                <td ><font color="#000000" face=verdana size=2 style="vertical-align:super">Reply with AI </font><a href="javascript:void(0)" id="generateReply"><img src="<?=$SiteURL?>public/images/magic.png" alt="AI" style="height: 25px;"></a></td>
                            <? }else { ?>
                                <td colspan='2'><font color="#000000" face=verdana size=2>Content<span class="orangeTxt">*</span></font></td>
                            <? } ?>
                        </tr>
					<tr>
						<td colspan='2'>
						<textarea name="V_Content" rows="8" cols="40" style="width:100%; height:300px" id="V_Content" >
                      
						</textarea>
						</td>
					</tr>	
                   <tr>
                        <td>
                            <div class="file-upload">
                                <label class="btn btn-primary mb-0">
                                     Attachment
                                </label>
                            </div>
                        </td>

                        <td>
                            <input type="file" name="attachments[]" id="attachment" multiple>
                        </td>
                    </tr>


					<tr>
						<td colspan="2" align="center">		
							<input type="hidden" name="v_queue_type" value="<?=$v_queue_type?>" />
							<input type="hidden" name="AccountName" value="<?=$AccountName?>" />
							<input type="hidden" name="view" value="<?=$view?>" />
							<input type="hidden" name="name" value="<?=$name?>" />
							<input type="hidden" name="iid" value="<?=$_REQUEST['iid']?>" /> <!--uid hidden field -->
						</td>
					</tr>

				</table>

			</td>
		</tr>
	</table>
	</form>
<div id="loaderOverlay">
<div id="loader">
    <img src="<?=$SiteURL?>public/images/galaxy_ai.gif" alt="Loading...">
</div>
</div><?php
function decodeAndCleanEmailBody($rawBody){
        // Decode quoted-printable characters
        $body = quoted_printable_decode($rawBody);

        // Remove soft line breaks (e.g., =\n)
        $body = preg_replace("/=\r?\n/", "", $body);

        // Normalize line endings
        $body = str_replace(["\r\n", "\r"], "\n", $body);

        // Optionally remove excess whitespace lines
        $body = preg_replace("/\n{3,}/", "\n\n", $body);

        return trim($body);
    }
// Use SAME function as normal display
$cleanBody = decodeAndCleanEmailBody($originalMessage);

// Convert line breaks for CKEditor HTML
$cleanBody = nl2br($cleanBody);

// Optional cleanup
$cleanBody = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $cleanBody);
$cleanBody = preg_replace('/<!--(.*?)-->/s', '', $cleanBody);
$cleanBody = trim($cleanBody);

// Build reply trail
$formattedTrail = '
<br><br>

<div style="border-top:1px solid #ccc; margin:15px 0;"></div>

<div style="font-family:Calibri, Arial, sans-serif; font-size:13px; background:#f3f3f3; padding:10px; line-height:1.6;">
    <b>From:</b> ' . htmlspecialchars($mail_from_name) . ' &lt;' . htmlspecialchars($mail_from_email) . '&gt;<br>
    <b>Sent:</b> ' . htmlspecialchars($mail_date) . '<br>
    <b>To:</b> ' . htmlspecialchars($mail_to_name) . ' &lt;' . htmlspecialchars($mail_to_email) . '&gt;<br>';

if (!empty($mail_cc)) {
    $formattedTrail .= '
    <b>Cc:</b> ' . htmlspecialchars($mail_cc) . '<br>';
}

$formattedTrail .= '
    <b>Subject:</b> ' . htmlspecialchars($mail_subject) . '
</div>

<div style="margin-top:10px; font-family:Calibri, Arial, sans-serif; font-size:13px; line-height:1.6;">
    ' . $cleanBody . '
</div>
';

?>

<script>
    var ORIGINAL_MAIL_TRAIL = <?php echo json_encode($formattedTrail); ?>;

    // var ORIGINAL_MAIL_TRAIL = <?php echo json_encode($originalMessage); ?>;

    <?php if(!empty($fwdflag)){ ?>
         const forwardv_body = <?= json_encode($originalMessage) ?>;
    <?php }else{?>
        const forwardv_body ='';
    <?php }?>
    const DEFAULT_MAIL_SIGNATURE = <?= json_encode($signatureHtml) ?>;

    const LOGGED_USER = <?php echo json_encode($_SESSION['logged'] ?? ''); ?>;

document.getElementById("closeButton").addEventListener("click", function () {
    window.close();
});

// Multiple email selection option added - Aarti -06-04-2026
$(document).ready(function () {
    let emails = [];

    // -------------------------------
    // Load existing emails from DB
    // -------------------------------
    let existing = $("#V_EmailId").val();
    existing = existing ? existing.trim() : "";

    if (existing !== "") {
        let existingEmails = existing.split(/[,;]+/).map(function(e) {
            return e.trim();
        }).filter(function(e) {
            return e !== "";
        });

        existingEmails.forEach(function(email) {
            addEmailTag(email, false); // false = no alert on invalid
        });
    }

    // -------------------------------
    // Focus input when click container
    // -------------------------------
    $("#emailContainer").on("click", function () {
        $("#emailInput").focus();
    });

    // -------------------------------
    // Add email on Enter / comma / semicolon
    // -------------------------------
    $("#emailInput").on("keydown", function (e) {
        if (e.key === "Enter" || e.key === "," || e.key === ";") {
            e.preventDefault();

            let inputVal = $(this).val().trim().replace(/[,;]$/, "");
            if (inputVal !== "") {
                addEmailTag(inputVal, true);
                $(this).val("");
            }
        }
    });

    // -------------------------------
    // Add on blur also
    // -------------------------------
    $("#emailInput").on("blur", function () {
        let inputVal = $(this).val().trim().replace(/[,;]$/, "");
        if (inputVal !== "") {
            addEmailTag(inputVal, true);
            $(this).val("");
        }
    });

    // -------------------------------
    // Remove email
    // -------------------------------
    $(document).on("click", ".remove-email", function () {
        let email = $(this).parent().attr("data-email");

        emails = emails.filter(function(e) {
            return e !== email;
        });

        $(this).parent().remove();
        updateHiddenInput();
    });

    // -------------------------------
    // Add tag function
    // -------------------------------
    function addEmailTag(email, showAlert) {
        email = email.trim();
        let lowerEmail = email.toLowerCase();

        if (!isValidEmail(email)) {
            if (showAlert) {
                alert("Invalid email: " + email);
            }
            return;
        }

        // Prevent duplicate
        if (emails.indexOf(lowerEmail) !== -1) {
            return;
        }

        emails.push(lowerEmail);

        let tagHtml = `
            <span class="email-tag" data-email="${lowerEmail}">
                ${escapeHtml(email)}
                <span class="remove-email">&times;</span>
            </span>
        `;

        $("#emailInput").before(tagHtml);
        updateHiddenInput();
    }

    // -------------------------------
    // Update hidden input
    // -------------------------------
    function updateHiddenInput() {
        $("#V_EmailId").val(emails.join(","));
    }

    // -------------------------------
    // Email validation
    // -------------------------------
    function isValidEmail(email) {
        let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return regex.test(email);
    }

    // -------------------------------
    // Escape HTML
    // -------------------------------
    function escapeHtml(text) {
        return $('<div>').text(text).html();
    }
});
// close
</script>
<script src="<?=$SiteURL?>CRM/omnichannel_config/js/omni_config.js"></script>   
