<?php
include("../../config/web_mysqlconnect.php");
// print_r($_SESSION); 
//updated the code related to sms out queue [vastvikta][27-10-2025]
  include("bulk_function.php");  
  $list_BULK = new BULK();
  $recent_uploads = $list_BULK->get_bulk_upload_list();
  $campaign = 'Email';
  $response_email = $list_BULK->get_email_list();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_sms' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    $delete = "DELETE FROM web_email_information_out WHERE EMAIL_ID = $id";
    echo mysqli_query($link, $delete) ? "success" : "error";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_sms') {
    $id = intval($_POST['id']);
    $message = mysqli_real_escape_string($link, $_POST['message']);
    $schedule = !empty($_POST['schedule']) ? mysqli_real_escape_string($link, $_POST['schedule']) : '0000-00-00 00:00:00';
    $update = "UPDATE web_email_information_out 
               SET v_body = '$message', scheduling_date = '$schedule', schedule_flag = '1' WHERE EMAIL_ID = $id";
    echo mysqli_query($link, $update) ? "success" : "error";
    exit;
}

$signatureHtml = '';
if ($campaign === 'Email') {
$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

    $signatureText = str_replace('%yourname%', $_SESSION['full_name'], $signatureText);

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

<link rel="stylesheet" href="<?=$SiteURL?>public/css/bulk_style.css">
<link rel="stylesheet" href="<?=$SiteURL?>public/css/select2.min.css">
<link rel="stylesheet" href="<?=$SiteURL?>public/css/select2-bootstrap4.min.css">
<!-- CKeditor new code added 21-02-2024 -->
<script src="https://cdn.ckeditor.com/ckeditor5/41.3.1/classic/ckeditor.js"></script>
<style type="text/css">
  /*ckeditor__editable*/
  /* âœ… Restore bullets only inside CKEditor content */
    .ck-content ul {
        list-style: disc !important;
        padding-left: 20px;
    }

    .ck-content ol {
        list-style: decimal !important;
        padding-left: 20px;
    }

    .ck-content li {
        list-style-position: outside !important;
    }

    .ck.ck-content.ck-editor__editable.ck-rounded-corners.ck-editor__editable_inline.ck-blurred {
        height: 200px;
    }
  .sms-table {
    font-size: 12px!important;
  }
  #single_send_button,
  #bulk_send_button{
    float: right;            /* Aligns the button to the right */
    color: white;            /* Sets text color to white */
    font-size: 0.9rem;       /* Slightly smaller text */
    background-color: #17a2b8; /* Optional: keeps Bootstrap's info blue */
    border: none;            /* Optional: cleaner look */
    padding: 8px 16px;       /* Optional: balanced padding */
    border-radius: 4px;      /* Optional: rounded corners */
    margin-bottom:20px;
}


   .select2-container--default .select2-selection--multiple {
       background-color: white;
       border: 1px solid #aaa;
       border-radius: 4px;
       cursor: text;
   }
   h2 {
    /* width: 100%; */
    text-align: center;
    border-bottom: 1px solid coral;
    line-height: 0.1em;
    margin: 30px 0 20px;
}
h2 span {
    background: #fff;
    padding: 0 10px;
}


.collapse {
    display: none
}

.collapse.in {
    display: block
}

tr.collapse.in {
    display: table-row
}

tbody.collapse.in {
    display: table-row-group
}

.collapsing {
    position: relative;
    height: 0;
    overflow: hidden;
    -webkit-transition-timing-function: ease;
    -o-transition-timing-function: ease;
    transition-timing-function: ease;
    -webkit-transition-duration: .35s;
    -o-transition-duration: .35s;
    transition-duration: .35s;
    -webkit-transition-property: height,visibility;
    -o-transition-property: height,visibility;
    transition-property: height,visibility
}

.caret {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: 2px;
    vertical-align: middle;
    border-top: 4px dashed;
    border-top: 4px solid\9;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent
}


</style>
<!-- new code 14-01-2026 -->
<style>
/* Reduce vertical gaps */
.bulk-card .row{
    margin-bottom: 6px !important;
}

.bulk-card label{
    margin-bottom: 3px !important;
}

.bulk-card .form-control,
.bulk-card select{
    height: 34px !important;
    padding: 4px 8px !important;
}

/* Reduce textarea spacing */
.bulk-card textarea{
    padding: 6px 8px !important;
}

/* Remove extra card padding */
.bulk-card .card-body{
    padding: 12px !important;
}

/* Make divider tighter */
.bulk-divider{
    margin: 8px 0 !important;
}

/* Fix date row spacing */
.bulk-card .col-md-3,
.bulk-card .col-md-4,
.bulk-card .col-md-6,
.bulk-card .col-md-12{
    margin-bottom: 6px !important;
}

/* Tighten table spacing */
.tableview th, .tableview td{
    padding: 4px 6px !important;
}
#bulkdrown .dropdown-menu .dropdown-item {
    font-size: 11px !important;
    padding: 4px 10px;
    line-height: 1.2;
}
/*multile file code*/
.file-list-inline {
  display: flex;
  flex-wrap: wrap; /* wraps only if screen is too narrow */
  gap: 10px;
  margin-top: 8px;
  background-color: #f8f8f8;
  padding: 8px;
  border-radius: 8px;
}

.file-item {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  background-color: #ffffff;
  border: 1px solid #ccc;
  border-radius: 16px;
  font-size: 14px;
  white-space: nowrap;
}

.file-name {
  margin-right: 6px;
}

.remove-file {
  cursor: pointer;
  color: red;
  font-weight: bold;
  padding-left: 3px;
}
/*file button layout code*/
input[type="file"]::file-selector-button {
  padding: 6px 12px;
  border: none;
  background: #007bff;
  /*color: white;*/
  border-radius: 4px;
  cursor: pointer;
}

input[type="file"] {
  /*color: transparent; /* hides the file name */*/
}

.email-preview img {
    max-width: 100%;
    height: auto;
}

.attachment-preview {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.attachment-item {
    width: 120px;
    text-align: center;
    font-size: 12px;
}

.attachment-item img {
    width: 100%;
    height: 80px;
    object-fit: cover;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.attachment-item iframe {
    width: 100%;
    height: 80px;
    border: 1px solid #ddd;
    border-radius: 4px;
}
.ck-content .mail-signature {
    opacity: 0.9;
    cursor: not-allowed;
    user-select: none;
}
.tableview tr td a:hover {
    color: #ffffff;
}

#bulkdrown .dropdown-menu{
    min-width: 40px;
}
.dataTables_wrapper { overflow: visible !important; }
/* Fix dropdown clipping inside DataTables */
.table-responsive,
.dataTables_wrapper {
    overflow: visible !important;
}

/* Ensure dropdown appears above row if needed */
#bulkdrown .dropdown-menu {
    z-index: 1055;
}

.header-tag {
    display: inline-block;
    margin: 4px;
    padding: 6px 10px;
    border-radius: 20px;
    background: #e9f3ff;
    color: #007bff;
    border: 1px solid #b8daff;
    cursor: pointer;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.2s ease;
}
.header-tag:hover {
    background: #007bff;
    color: #fff;
}
.bulk-card .card-header {
    background: #f8fbff;
    border-bottom: 1px solid #e5e7eb;
    padding: 12px 15px;
}

.bulk-card .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;
}

#toggleBulkForm {
    border: none;
    background: transparent;
    font-size: 18px;
    color: #007bff;
    cursor: pointer;
}

#toggleBulkForm:focus {
    outline: none;
    box-shadow: none;
}
.badge{
    color: black;
}
.bg-primary {
    --bs-bg-opacity: 1;
    background-color: rgb(54 92 36) !important;
}
</style>

<div class="col-sm-10 mt-3" style="padding-left:0">
  <span class="breadcrumb_head" style="height:37px;padding:9px 16px">
      Bulk Email
  </span>
  <div class="Reports-page#" style="display: block;border: #d4d4d4 1px solid;margin-bottom:20px;min-height: 420px;margin-top:37px">
    <div class="card card-info card-outline card-outline-tabs">
      <div class="card-header" style="border-bottom: 0px solid rgba(0,0,0,.125);">
        <ul class="nav nav-tabs" id="custom-content-above-tab" role="tablist">
          <li class="nav-item">
            <button type="button" class="nav-link active btn-tab" data-target="#custom-content-above-home"  data-tab="single">
              Compose Email
            </button>
          </li>
          <li class="nav-item">
            <button type="button" class="nav-link btn-tab" data-target="#custom-content-above-profile" data-tab="campaign">
              Campaign Email
            </button>
          </li>
        </ul>
      </div>
      <div class="card-body" style="padding:0;">
        <div class="tab-content" id="custom-content-above-tabContent">
          <div class="row">
            <div class="col-sm-6">
              <div class="card card-info card-outline" style="margin-top: 1px; margin-left: 3px; margin-bottom:20px;">
                <!-- <div class="card-header"> -->
                  <!-- <h3 class="card-title">Send Messages</h3> -->
                <!-- </div> -->

                <form id="quickForm" method="post">
                  <input type="hidden" name="action" value="send_sms_index">

                  <div class="card-body">
                    <span class="text text-danger custom_sms"></span>

                    <div class="form-group" style="display: none;">
                      <label>Channel Type</label>
                      <select class="form-control selectchannel" name="channel_type_direct" id="channel_type">
                          <option value="Email" selected>Email</option>
                      </select>
                    </div>
                    <div class="col-md-6" style="display: none;">
                        <label>Select Template</label>
                        <!-- <select class="form-control selectchannel" name="selecttemplate" id="selecttemplate">
                            <option value="0">Select Template</option>
                            <?php foreach($template_assign as $value){ ?>
                                <option value="<?php echo $value['name'];?>"><?php echo $value['name'];?></option>
                            <?php } ?>
                        </select> -->
                    </div>
                    <?php if ($campaign == 'Email') { ?>
                      <div class="form-group email_div">
                        <label>To</label>
                        <select class="form-control" name="email" id="email">
                          <?php while ($value = mysqli_fetch_array($response_email)) { ?>
                            <option value="<?php echo $value['email']; ?>"><?php echo $value['email']; ?></option>
                          <?php } ?>
                        </select>
                        <span class="text text-danger mobile_error"></span>
                      </div>
                      <div class="form-group email_div">
                        <label>Subject</label>
                        <input type="text" class="form-control" id="Subject" name="Subject" value="">
                        <span class="text text-danger mobile_error"></span>
                      </div>
                    <?php } ?>
                    <div class="form-group">
                      <label for="message">Message</label>
                      <div class="textarea_div">
                        <?php 
                          // Set maximum length dynamically based on campaign
                          $maxLength = 1600;
                        ?>
                       <div style="position: relative; width: 100%;">
                          <textarea class="form-control" id="message" placeholder="Write your message" name="message" maxlength="<?= $maxLength ?>" style="height:150px; resize:none; width:100%; font-size:14px"></textarea>
                          <div id="char-count" 
                              style="position: absolute; right: 10px; bottom: 5px; font-size:12px; color:#555;">
                              0 / <?= $maxLength ?>
                          </div>
                        </div>
                        <textarea id="output" style="display:none;"></textarea>
                      </div>
                      <span class="limi" id="counter"></span>
                      <span class="text text-danger message_error"></span>
                    </div>

                    <div class="form-group">
                      <div class="custom-control custom-switch custom-switch-off-danger custom-switch-on-success">
                        <input type="checkbox" class="custom-control-input" id="scheduletime" name="scheduletime">
                        <label class="custom-control-label" for="scheduletime">Schedule</label>
                      </div>
                    </div>

                    <div class="form-group" id="hi" style="display:none">
                      <input id="pickdate" class="form-control pickdate" placeholder="Select date and Time" autocomplete="off" name="date" value="">
                    </div>

                    <span class="text text-danger date_error"></span>

                    <div class="form-group text-right">
                      <button type="submit" id="single_send_button" class="btn btn-info">Create</button>
                    </div>
                  </div>
                </form>
              </div> <!-- card end -->
            </div> <!-- col end -->


                <div class="card card-info card-outline direct-chat direct-chat-info collapsed-card">
                  <div class="card-body">
                    <table class="table table-bordered">
                      <thead>
                        <tr>
                          <th style="font-size: 12px;">Message</th>
                          <th style="font-size: 12px;">Created On</th>
                          <th style="font-size: 12px;">Scheduled On</th>
                          <th style="font-size: 12px;">Status</th>
                          <th style="font-size: 12px;">Action</th>
                        </tr>
                      </thead>
                      <tbody style="font-size: 12px;">
                        <?php
                        $limit = 5; // records per page
                        $page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
                        $offset = ($page - 1) * $limit;

                        // Count total records
                        $totalQuery = "SELECT COUNT(*) as total FROM web_email_information_out WHERE message_type_flag = '1'";

                        $totalResult = mysqli_query($link, $totalQuery);
                        $totalRow = mysqli_fetch_assoc($totalResult);
                        $totalRecords = $totalRow['total'];
                        $totalPages = ceil($totalRecords / $limit);

                        // Fetch paginated records
                        $query = "SELECT EMAIL_ID, v_body, d_email_date, scheduling_date, I_Status 
                                  FROM web_email_information_out 
                                  WHERE message_type_flag = '1'
                                  ORDER BY EMAIL_ID DESC 
                                  LIMIT $limit OFFSET $offset";
                        $result = mysqli_query($link, $query);

                        if (mysqli_num_rows($result) > 0) {
                          while ($row = mysqli_fetch_assoc($result)) {
                            $id = $row['EMAIL_ID'];
                            $msg = htmlspecialchars($row['v_body']);
                            $created = !empty($row['d_email_date']) ? $row['d_email_date'] : '-';
                            $scheduled = !empty($row['scheduling_date']) ? $row['scheduling_date'] : '-';
                            $status = $row['I_Status'];
                        ?>
                            <tr id="row_<?php echo $id; ?>">
                              <td style="max-width:200px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"><?php echo $msg; ?></td>
                              <td><?php echo $created; ?></td>
                              <td><?php echo $scheduled; ?></td>
                              <td>
                                <?php if ($status == 2) { ?>
                                  <span class="badge badge-success text-dark">Sent</span>
                                <?php } else { ?>
                                  <span class="badge badge-warning text-dark">In Queue</span>
                                <?php } ?>
                              </td>
                              <td>
                                <button class="btn btn-sm btn-info viewMsg" style="background-color:white;border-color:white;" data-id="<?php echo $id; ?>" data-msg="<?php echo htmlspecialchars($row['v_body'], ENT_QUOTES); ?>">
                                  <i class="fas fa-eye" style="color:#1684b5;background-color:white;"></i>
                                </button>
                              <?php if($status == '1'){ ?>
                                  <button class="btn btn-sm btn-warning editMsg" style="background-color:white;border-color:white;"
                                    data-id="<?php echo $id; ?>" 
                                    data-msg="<?php echo htmlspecialchars($row['v_body'], ENT_QUOTES); ?>" 
                                    data-schedule="<?php echo ($row['scheduling_date'] != '0000-00-00 00:00:00') ? $row['scheduling_date'] : ''; ?>">
                                    <i class="fas fa-edit" style="color:#1684b5;background-color:white;"></i>
                                  </button>

                                  <button class="btn btn-sm btn-danger deleteMsg" style="background-color:white;border-color:white;" data-id="<?php echo $id; ?>" data-channel="<?php echo $_GET['campaign'];?>">
                                    <i class="fas fa-trash" style="color:red;background-color:white;"></i>
                                  </button>
                              <?php }?>
                              </td>
                            </tr>
                        <?php
                          }
                        } else {
                          echo "<tr><td colspan='6' class='text-center text-muted'>No records found</td></tr>";
                        }
                        ?>
                      </tbody>
                    </table>

                    <div class="d-flex justify-content-between mt-2">
                      <div>
                        Showing page <?php echo $page; ?> of <?php echo $totalPages; ?>
                      </div>
                      <div>
                        <?php
                        $sms1 = base64_encode('web_bulksms');

                        if ($page > 1) { ?>
                          <a href="?token=<?php echo $sms1; ?>&campaign=Email&page=<?php echo $page - 1; ?>" class="btn btn-sm btn-secondary">Prev</a>
                        <?php } ?>
                        <?php if ($page < $totalPages) { ?>
                          <a href="?token=<?php echo $sms1; ?>&campaign=Email&page=<?php echo $page + 1; ?>" class="btn btn-sm btn-secondary">Next</a>
                        <?php } ?>
                      </div>
                    </div>
                  </div>
                </div>
              <div class="card card-info card-outline direct-chat direct-chat-info" id="recent" style="display: none;">
                <div class="card-header">
                  <h3 class="card-title">Last interaction 360Â°</h3>
                </div>
                <div class="card-body">
                  <div class="direct-chat-messages interaction-chat">
                    <div id="interaction_history" class="direct-chat-msg left"></div>
                  </div>
                </div>
              </div>
            </div> <!-- col end -->
          </div> <!-- row end -->
        </div> <!-- tab-content end -->
      </div>
      </div> <!-- card-body end -->
      <div class="tab-pane" id="custom-content-above-profile" style="display:none;">        
        <div class="row">
         <div class="col-sm-12">
            <div class="card card-info card-outline bulk-card" id="bulkCampaignCard">
    
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h3 class="card-title mb-0">Bulk Campaign Form</h3>

                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" id="toggleBulkForm">
                                <i class="fa fa-plus" id="bulkToggleIcon"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Hidden by default -->
                    <div class="card-body" id="bulkFormBody" style="display:none;">
                      <form method="post" id="import_form" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="import_file" id="form_action">
                        <input type="hidden" name="channel_type" value="<?php echo $campaign;?>">

                        <input type="hidden" name="mode" id="form_mode" value="create">
                        <input type="hidden" name="edit_id" id="edit_id" value="">

                        <div class="card-body">
                        <!-- Row 1 -->
                        <div class="row">
                            <div class="col-md-6">
                                <label>Select Template</label>
                                <select class="form-control  select2bs4s"  style="width: 100%;" name="selecttemplate" id="selecttemplate">
                                  <option value="0">Select Template</option>
                                  <?php
                                    $template_assign = $list_BULK->get_templates($campaign);
                                    if(!empty($template_assign)){
                                       $id=0;
                                       foreach ($template_assign as $value) 
                                       {
                                       $id++;
                                       ?>
                                    <option 
                                        value="<?php echo htmlspecialchars($value['name']); ?>"
                                        data-id="<?php echo $value['id']; ?>"
                                    >
                                        <?php echo $value['name']; ?>
                                    </option>                                      <?php } 
                                    }
                                  ?>
                                </select>
                                <button type="button" class="btn btn-success ml-2" id="createTemplateBtn" style="display:none;">
                                    <i class="fa fa-plus"></i>
                                </button>
                            </div>

                            <div class="col-md-6">
                                <label>Uploaded Campaign</label>
                                <select class="form-control select2bs4s" name="select_file_name" id="select_file_name" onchange="get_count_of_list(this.value)">
                                    <option value="0">Select Campaign</option>
                                    <?php foreach($recent_uploads as $row){ ?>
                                        <option value="<?php echo $row['id'];?>"><?php echo $row['list_name'];?></option>
                                    <?php } ?>
                                </select>
                            </div>
                        </div>

                        <?php if($campaign=='Email'){ ?>
                        <!-- Email Date Filter -->
                        <div class="row mt-3" style="display:none">
                            <div class="col-md-3">
                                <label>Start Date</label>
                                <input type="text" class="form-control dob1" id="BulkEmailStartDate">
                            </div>
                            <div class="col-md-3">
                                <label>End Date</label>
                                <input type="text" class="form-control dob1" id="BulkEmailEndDate">
                            </div>
                            <div class="col-md-3">
                                <button class="btn btn-warning btn-sm mt-2" id="BulkEmailSubmit">Download CSV</button>
                            </div>
                            <button class="btn btn-sm btn-info bulkDownload" style="background:white;border:none">
                            getting data from database<i class="fa fa-download text-primary"></i>
                        </button>
                        </div>
                        
                        <?php } ?>

                        <span id="show-counts"></span>
                        <!-- <div class="bulk-divider"><span>OR Upload File</span></div> -->
                        <!-- Upload row -->
                        <div class="row">
                            <div class="col-md-6">
                                <label>Select File</label>

                                <input type="file" name="file" id="file" class="form-control" style="font-size: 12px;">
                                <button type="button"class="btn btn-sm btn-outline-primary mt-2"
                                    id="openDbCsvModal" style="display:none;">
                                    <i class="fa fa-database"></i> Get Data from Database
                                </button>

                                <div id="oldFileBox" class="mt-2" style="display:none;">
                                    <small>Existing file:</small><br>
                                    <a href="#" target="_blank" id="oldFileLink"></a>
                                    <button type="button" class="btn btn-sm btn-danger ml-2" id="removeOldFile">
                                        Remove
                                    </button>
                                </div>

                                <input type="hidden" name="old_file" id="old_file">
                            </div>

                            <div class="col-md-6">
                                <label>Campaign Name</label>
                                <input type="text" name="list_name" id="list_name" class="form-control">
                            </div>
                        </div>
                        <div class="row">
                                <?php if($campaign=='Email'){ ?>
                                  <div class="col-md-6">
                                    <div class="col-md-12">
                                          <label>Subject</label>
                                          <input type="text" name="description" id="description" class="form-control">
                                      </div>
                                  </div>
                                   
                                  <div class="col-md-6">
                                    <?php
                                    $form_sql = "SELECT id, form_name FROM form_master WHERE status = 1";
                                    $form_result = mysqli_query($link, $form_sql);
                                    ?>
                                    <label>Select Form</label>
                                    <select name="form_link" class="form-control  select2bs4s"  style="width: 100%;"  id="form_id">
                                         <?php
                                        if ($form_result && mysqli_num_rows($form_result) > 0) {
                                            while ($row = mysqli_fetch_assoc($form_result)) {?>
                                            
                                                <option value="<?php echo $row['id'];?>"><?php echo $row['form_name'];?></option>
                                            <?php }
                                        }
                                        ?>
                                    </select>
                                </div>
                                
                              <?php } ?>
                                <div class="col-md-6">
                                  <!-- Message -->
                                    <div class="col-md-12">
                                        <label>Message</label>
                                        <input type="hidden" name="csv_headers" id="csv_headers">
                                        <!-- <textarea class="form-control messagebulk" id="message" name="message" maxlength="1600" style="height:140px"></textarea> -->
                                        <textarea class="form-control messagebulk" name="message" rows="8" cols="40" style="width:100%; height:300px" id="V_Content" ></textarea>
                                    </div>
                                    <div class="" id="files" style="padding: 10px;">
                                        <font color="#000000" face=verdana size=2><b>Attachment</b></font>
                                        <input type="file" id="fileInput" multiple name="attachments"><br><br>
                                        <ul id="fileList" class="file-list"></ul>
                                  </div>
                                  <div id="oldAttachmentBox" class="mt-2" style="display:none;">
                                    <small>Existing Attachment:</small><br>
                                    <a href="#" id="oldAttachmentLink" target="_blank"></a>
                                    <button type="button" class="btn btn-sm btn-danger ml-2" id="removeOldAttachment">
                                      Remove
                                    </button>
                                  </div>
                                  <input type="hidden" name="old_attachments" id="old_attachments">
                                 
                                <button type="button" class="btn btn-primary mt-2" id="saveTemplateBtn" style="display:none;">
                                    Save Template
                                </button>
                                </div>
                                <div class="col-md-4">
                                    <label>Available Excel Headers</label>
                                    <div id="excelHeadersBox" class="border rounded p-2" 
                                         style="min-height:300px; max-height:300px; overflow-y:auto; background:#f8f9fa;">
                                        <small class="text-muted">Upload CSV/Excel file to show headers</small>
                                    </div>
                                    
                                    <div class="row mt-2">
                                        <div class="col-md-12">
                                            <!-- Hidden fields -->
                                            <input type="hidden" id="csv_file_path" value="">
                                            <input type="hidden" id="bulk_id" value="">
                                            <input type="hidden" id="channel_type" value="Email"> <!-- set dynamically if needed -->
                                            <input type="hidden" id="queue_session" value="<?= uniqid('bulk_') ?>">

                                            <!-- Preview button -->
                                            <button type="button" class="btn btn-info btn-sm" id="previewTemplateBtn">Preview</button>
                                        </div>
                                    </div>
                                </div>
                              </div>
                              <div class="col-md-6">
                                  <div class="custom-control custom-switch">
                                      <input type="checkbox" class="custom-control-input" id="scheduletime2" name="scheduletime">
                                      <label class="custom-control-label" for="scheduletime2">Schedule</label>
                                  </div>
                                  <div class="col-m" id="datepicker_div" style="display:none">
                                    <!-- <input id="pickdate" class="form-control pickdate" name="date" placeholder="Select date & time"> -->
                                     <input id="pickdatenew" type="text" name="date" class="date_class dob1"
                                                    value="" id="date">
                                  </div>
                              </div>
                        <div class="text-right">
                            <input type="submit" id="bulk_send_button" value="Create Campaign" class="btn btn-info">
                              <button type="button" id="cancelEditBtn" class="btn btn-secondary d-none">
                              Cancel
                            </button>
                        </div>
                        <div class="card-footer">
                             <span><a style="text-decoration: none;color: #337ab7;" href="sample/Bulk_Campagin_Recipient_List.csv">Download Template </a></span>  
                                <br><span style="color:red">Note : <?php if($campaign=='Email'){ echo 'Email ID is mandatory';}else{?>Contact number is mandatory. Enter the contact number in csv file without +254. <?php }?></span>  
                              
                          </div> 
                        </div>
                      </form>
                </div>
            </div>
          </div>

          <div class="col-sm-12">
            <!-- Show Recent Bulk Uploaded In Queue -->
            <!-- show Recent Uploaded List -->
            <div class="card card-info card-outline">
              <div class="card-header">
                <h3 class="card-title">Recent Uploads </h3>
              </div>
              <!-- /.card-header -->
              <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm tableview bulks_report" id="bulks_report">
                      <thead>
                        <tr>
                          <th style="font-size: 10px;">Campaign</th>
                           <!-- <th>Message</th> -->
                          <th style="font-size: 10px;">Channel</th>
                          <th style="font-size: 10px;">Count</th>
                          <th style="font-size: 10px;">Created Date</th>
                          <th style="font-size: 10px;">Scheduled Date</th>
                          <th style="font-size: 10px;">Status</th>
                          <th style="font-size: 11px;">Verified By</th>
                          <th style="font-size: 11px!important;">Created By</th>
                          <th style="font-size: 11px;color:black!important">Action</th>
                        </tr>
                      </thead>
                </table>
              </div>
              </div>
            </div>
          </div> <!-- tab-content end -->
        </div> <!-- card-body end -->
      </div> <!-- row end -->
      </div>
    </div> <!-- card end -->
  </div> <!-- Reports-page end -->
</div> <!-- col end -->
<!-- Modal -->

<div class="modal fade" id="viewModal">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">Campaign Preview</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <!-- SUBJECT -->
        <div id="viewSubjectBox" class="mb-3">
          <strong>Subject:</strong>
          <div id="viewSubject" class="border rounded p-2 bg-light"></div>
        </div>

        <!-- MESSAGE -->
        <div class="mb-3">
          <strong>Message:</strong>
          <div id="viewMessage" class="border rounded p-3 bg-white email-preview"></div>
        </div>

        <!-- ATTACHMENTS -->
        <div id="viewAttachmentBox" style="display:none;">
          <strong>Attachments:</strong>
          <div id="viewAttachments" class="mt-2"></div>
        </div>

        <!-- REMARK -->
        <div class="mt-3 verifyRemarked">
          <label><strong>Remarks</strong></label>
          <textarea id="verifyRemark" class="form-control" rows="3"
            placeholder="Enter verification / rejection remarks"></textarea>
        </div>

      </div>

      <div class="modal-footer justify-content-between">

        <div>
          <a href="#" id="downloadFileBtn" target="_blank"
             class="btn btn-outline-primary btn-sm">
            â¬‡ Download File
          </a>
        </div>

        <div>
          <button type="button"
                class="btn btn-danger btn-sm deleteMsgbulk"
                id="deleteMsgbulk"
                data-id=""
                data-channel_type="">
          âŒ Delete
        </button>

          <button type="button" class="btn btn-danger btn-sm" id="rejectPostBtn">
            âŒ Reject
          </button>

          <button type="button" class="btn btn-success btn-sm" id="confirmVerifyBtn">
            âœ… Approve
          </button>

          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
            Cancel
          </button>
        </div>

      </div>
    </div>
  </div>
</div>

<!-- single bulk sms  -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document" style="max-width:600px;">
    <div class="modal-content">
      <div class="modal-header"  style="background-color: #28a745; color: white; display:flex; justify-content: space-between; align-items: center;">
        <h5 class="modal-title mb-0">Edit Message</h5>
        <span id="closeEditModal" style="cursor:pointer; font-size:1.5rem;">&times;</span>
      </div>
      <div class="modal-body">
        <form id="editForm">
          <input type="hidden" name="id" id="edit_id">
          <input type="hidden" name="channelsingle" id="channelsingle" value="<?php echo $_GET['campaign'];?>">
          <div class="form-group">
            <label for="edit_message">Message</label>
            <textarea class="form-control" id="edit_message" name="message" rows="4"></textarea>
          </div>
          <div class="form-group">
            <label for="edit_schedule">Schedule Date & Time</label>
            <input type="datetime-local" class="form-control" id="edit_schedule" name="schedule">
          </div>
          <button type="submit" class="btn btn-warning" style = "background-color: #28a745; color: white;border-color:#28a745;">Update</button>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- bulk form  -->
<div class="modal fade" id="editModalbulk" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document" style="max-width:600px;">
    <div class="modal-content">
      <div class="modal-header"  style="background-color: #28a745; color: white; display:flex; justify-content: space-between; align-items: center;">
        <h5 class="modal-title mb-0">Bulk Edit Message</h5>
        <span id="closeEditModalbulk" style="cursor:pointer; font-size:1.5rem;">&times;</span>
      </div>
      <div class="modal-body">
        <form id="editFormbulk">
          <input type="hidden" name="id" id="edit_idbulk">
          <input type="hidden" name="id" id="queue_session" value="">
          <input type="hidden" name="channelbulk" id="channelbulk" value="<?php echo $_GET['campaign'];?>">
          <div class="form-group">
            <label for="edit_message">Message</label>
            <textarea class="form-control" id="edit_messagebulk" name="message" rows="4"></textarea>
          </div>
          <div class="form-group">
            <label for="edit_schedule">Schedule Date & Time</label>
            <input type="datetime-local" class="form-control" id="edit_schedulebulk" name="schedule">
          </div>
          <button type="submit" class="btn btn-warning" style = "background-color: #28a745; color: white;border-color:#28a745;">Update</button>
        </form>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="bulkDownloadModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Download Campaign Data</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <div class="modal-body">

        <input type="hidden" id="bulk_queue_session">
        <input type="hidden" id="bulk_campaign_name">

        <div class="row">
          <div class="col-md-6">
            <label>Start Date</label>
            <input type="text" class="form-control dob1" id="BulkEmailStartDate">
          </div>

          <div class="col-md-6">
            <label>End Date</label>
            <input type="text" class="form-control dob1" id="BulkEmailEndDate">
          </div>
        </div>

      </div>

      <div class="modal-footer">
        <button class="btn btn-success" id="BulkDownloadBtn">
            <i class="fa fa-file-excel-o"></i> Download CSV
        </button>
      </div>

    </div>
  </div>
</div>

<div class="modal fade" id="remarksModal" tabindex="-1">
 <div class="modal-dialog modal-lg modal-dialog-centered">
  <div class="modal-content">

    <div class="modal-header bg-success text-white ">
      <h5 class="modal-title">Approval History</h5>
      <button class="btn-close" data-bs-dismiss="modal"></button>
    </div>

    <div class="modal-body">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>Agent</th>
            <th>Action</th>
            <th>Channel</th>
            <th>Remark</th>
            <th>Date & Time</th>
            <!-- <th>IP</th> -->
          </tr>
        </thead>
        <tbody id="remarksTable"></tbody>
      </table>
    </div>

  </div>
 </div>
</div>
<div class="modal fade" id="dbCsvModal">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">

      <div class="modal-header bg-info text-white">
        <h5 class="modal-title">Generate CSV from Database</h5>
        <button class="close" data-dismiss="modal">&times;</button>
      </div>

      <div class="modal-body">

        <!-- Module -->
        <div class="form-group">
          <label>Select Module</label>
            <select id="module" class="form-control">
              <option value="">Select Module</option>
              <option value="customers">Customers</option>
              <option value="interactions">Interactions</option>
            </select>

          <div id="fieldBox" class="mt-3"></div>

        </div>

        <!-- Date Range -->
        <div class="row">
          <div class="col-md-6">
            <label>Start Date</label>
            <input type="date" id="csv_start" class="form-control">
          </div>
          <div class="col-md-6">
            <label>End Date</label>
            <input type="date" id="csv_end" class="form-control">
          </div>
        </div>

        <!-- Fields -->
        <div class="form-group mt-3">
          <label>Select Fields</label>
          <div id="csv_fields">
            <!-- dynamic -->
          </div>
        </div>

      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button class="btn btn-success" id="generateCsvBtn">
          Generate CSV
        </button>
      </div>

    </div>
  </div>
</div>
<div class="modal fade" id="templatePreviewModal" tabindex="-1" role="dialog" aria-labelledby="templatePreviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document" style="max-width: 1100px;">
        <div class="modal-content">
            
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Bulk Template Preview & Final Validation</h5>
                <button type="button" class="close text-white" aria-label="Close" onclick="$('#templatePreviewModal').modal('hide')">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">

                <div class="row">
                    <!-- Left side: rendered content -->
                    <div class="col-md-8">
                        <label><strong>Rendered Preview (Final Output)</strong></label>
                        <div id="previewContentBox" style="min-height:350px; max-height:550px; overflow:auto; border:1px solid #ddd; padding:15px; background:#fff;">
                        </div>
                    </div>

                    <!-- Right side: raw CSV data -->
                    <div class="col-md-4">
                        <label><strong>CSV Row Data Used</strong></label>
                        <div id="previewRawDataBox" style="min-height:350px; max-height:550px; overflow:auto; border:1px solid #ddd; padding:10px; background:#fafafa;">
                        </div>
                    </div>
                </div>
                <!-- Navigation -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <button type="button" class="btn btn-secondary btn-sm" id="previewPrevBtn">
                        &lt; Previous
                    </button>

                    <div class="text-center">
                        <strong>Record <span id="previewCurrentIndex">1</span> of <span id="previewTotalCount">0</span></strong>
                    </div>

                    <button type="button" class="btn btn-secondary btn-sm" id="previewNextBtn">
                        Next &gt;
                    </button>
                </div>
                <hr>

                <!-- Missing placeholder warning -->
                <div id="previewWarningBox" class="alert alert-warning" style="display:none;"></div>

            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="$('#templatePreviewModal').modal('hide')">
                    Close
                </button>
            </div>

        </div>
    </div>
</div>
<div class="modal fade" id="templateNameModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header">
        <h5>Template Name</h5>
      </div>

      <div class="modal-body">
        <input type="text" id="template_name" class="form-control">
      </div>

      <div class="modal-footer">
        <button class="btn btn-success" id="confirmSaveTemplate">
            Save
        </button>
      </div>

    </div>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>

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

</script>
