  $('.select2bs4').select2({
    theme: 'bootstrap4'
  })

// for Schedule toggle : Checkbox 
  $("#scheduletime").click(function () {
      if ($(this).is(":checked")) {
        // $("#single_send_button").text('Save');
       $("#hi").show();
      } else {
        // $("#single_send_button").text('Save');
       $("#hi").hide();
      }
  });

  $("#scheduletime2").on('change', function(event) {
    console.log('check date ');
    if($(this).is(':checked')){
      // $("#bulk_send_button").val('Save');
      $("#datepicker_div").show();
    }
    else{
      // $("#bulk_send_button").val('Send Now');
      $("#datepicker_div").hide();
    }
  });
$('.pickdate').datetimepicker({
  format: 'd-m-Y H:i',
  formatTime: 'H:i',
  formatDate: 'd-m-Y',
  step: 30,
  minDate: new Date(),
  position: 'top'
});

$("#message").keyup(function(event){
    event.preventDefault();
      // Getting the current value of textarea
      var currentText = $(this).val();
      console.log('currentText');
      console.log(currentText);
      // Setting the Div content
      $("#output").val(currentText);
});
  // aarti::  Template Redirect in textarea with Current Value :02-01-2025
 $("#selecttemplate").on("change", function () {
    var tempname   = $("#selecttemplate").val();
    var currentVal = $("#outputid").val();

    $.ajax({
        url: "omnichannel_config/direct_message_function.php",
        type: "POST",
        data: {
            tempname: tempname,
            action: 'get_template_content'
        },
        success: function (data) {
            var obj = JSON.parse(data);
            var temp_content = obj.template_content;

            var finalMessage = currentVal + temp_content;

            // fill textarea
            $(".messagebulk").val(finalMessage);

            // 🔥 update preview in real-time
            $("#previewMessage").text(finalMessage);
            $("#postPreview").show();
        },
        error: function (xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
});

  $('#messenger').on('click',function(){
    if($('#messenger').is(":checked"))
      $('.phone_div').show();
    else
      $('.phone_div').hide();
  });
$(document).ready(function () {

    fill_datatables_post();

    // 🔄 Reload every 10 seconds
    setInterval(function () {
        if (PostTable) {
            PostTable.ajax.reload(null, false); // keep pagination
        }
    }, 10000);
  function showPreviewIfNeeded() {
    const channel = $('#channelDropdown').val();
    const message = $('#message').val();
    const hasImages = $('#previewImages').children().length > 0;

    if (channel || message || hasImages) {
      $('#postPreview').show();
    } else {
      $('#postPreview').hide();
    }
  }

  // Channel change
  $('#channelDropdown').on('change', function () {
    const channelText = $(this).val() === 'twitter'
      ? 'Twitter Post'
      : $(this).val() === 'facebook'
        ? 'Facebook Post'
        : '';

    $('#previewChannel').text(channelText);
    showPreviewIfNeeded();
  });

  // Message typing
  $('#message').on('input', function () {
    $('#previewMessage').text($(this).val());
    showPreviewIfNeeded();
  });

  // Schedule toggle
  $('#scheduletime').on('change', function () {
    if ($(this).is(':checked')) {
      $('#previewSchedule').show();
    } else {
      $('#previewSchedule').hide();
    }
  });

  // 
});
function fill_datatables_post() {
    // ✅ If already initialized → just reload
    if ($.fn.DataTable.isDataTable('#channel_list')) {
        console.log("reloaded");
        PostTable.ajax.reload(null, false);
        return;
    }
    // ✅ Initialize ONLY ONCE
    PostTable = $('#channel_list').DataTable({
        processing: false,
        serverSide: true,
        pageLength: 10,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        searching: false,
        ajax: {
            url: "omnichannel_config/direct_message_function.php",
            type: "POST",
            data: function (d) {
                d.schedule = $('#schedule_type').val();
                d.channeltype = $('#channel_type').val();
                d.status = $('#status').val();
                d.agent_n = $('#agent_n').val();
                d.startdatetime = $('#startdatetime').val();   // ✅ added
                d.enddatetime = $('#enddatetime').val();       // ✅ added
                d.action = 'recent_uploads';
            },
            error: function (xhr) {
                console.log("AJAX Error:", xhr.responseText);
            }
        },
         "createdRow": function(row, data, dataIndex) {
            // Apply row classes based on the value in the color field
            var clr = data[17];  // Assuming the color field is at index 9
             if (clr == 'red') {
                $(row).addClass('Unread'); // read mail
            }
           
        },
        drawCallback: function() {
            // Reinitialize colorbox after redraw
            $(".ico-interaction2").colorbox({
                iframe: true,
                innerWidth: 750,
                innerHeight: 560
            });
        }
    });
}

  // Form submission event to update filters and reload DataTable
$('#post_whatsapp').submit(function(e) {
    e.preventDefault();
    // Destroy existing DataTable instance
    $('#channel_list').DataTable().destroy();

    // Reinitialize DataTable with new filter values
    fill_datatables_post();
});
$(document).ready(function () {
    $('#agent_n').select2({
        placeholder: "Search agent name",
        allowClear: true,
        width: "100%"
    });
});
$(document).on('click', '#viewDelete', function (e) {
    e.preventDefault();

    let id      = $(this).data('id');
    let channel = $(this).data('channel');

    // Trigger existing delete logic
    $('<a>')
        .addClass('delete-post')
        .attr('data-id', id)
        .attr('data-channel_type', channel)
        .appendTo('body')
        .trigger('click')
        .remove();

    // Close view modal (optional)
    $('#viewPostModal').modal('hide');
});
$("#quickForm").on("submit", function (e) {
    e.preventDefault();

    let formData = new FormData();

    formData.append("action", "send_direct_message");

    let editId = $("#edit_id").val();
    if (editId) formData.append("edit_id", editId);

    let channel = $("#channelDropdown").val();
    if (channel) formData.append("channeltype[]", channel);

    let message = $("#message").val()?.trim();
    console.log('message');
     if(message === '' || message === null || message === undefined){
        alert("Select Channel and Message cannot be empty.");
        return;
    }
    if (message) formData.append("message", message);

    if ($("#scheduletime").is(":checked")) {
        formData.append("schedule", 1);
        formData.append("pickdate", $("#pickdate").val());
    }

    // ✅ FIX: append REAL File objects
    newFiles.forEach(f => {
        formData.append("attachments[]", f.file);
    });
    

    // --- AJAX CALL ---
    $.ajax({
        url: "omnichannel_config/direct_message_function.php",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            console.log("Response: ", res);
            // Parse JSON if you return JSON
            try {
                let response = JSON.parse(res);
                if (response.status === 'success') {
                    alert("Post saved successfully.");
                    $("#quickForm")[0].reset(); // reset form
                    $(".select2bs4").val(null).trigger("change");
                    $("#hi").hide();
                      location.reload(); // or use DataTable refresh if applicable
                } else {
                    alert("Error: " + response.message);
                }
            } catch (e) {
                alert("Server response error. Check console.");
                console.log(res);
            }
        },
        error: function (xhr, status, err) {
            alert("AJAX Error: " + err);
        },
        complete: function () {
            // $("#single_send_button").prop("disabled", false).text("Send Now");
        }
    });
});
// Delete button click using event delegation (works with dynamic rows)
$(document).on('click', '.delete-post', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var channeltype = $(this).data('channel_type');
    $.ajax({
    url: 'omnichannel_config/direct_message_function.php',
    type: 'POST',
    data: {
        action: 'delete_post',
        id: id,
        channeltype:channeltype
    },
    success: function(response) {
        try {
        var res = JSON.parse(response);
        if (res.status === 'success') {
            alert("Post deleted successfully!");
            location.reload(); // or use DataTable refresh if applicable
        } else {
            alert("Failed to delete post: " + res.message);
        }
        } catch (e) {
        alert("Unexpected response from server.");
        }
    },
    error: function(xhr, status, error) {
        alert("AJAX Error: " + error);
    }
    });
  
});
$(document).on('click', '#cancelCreatePostModal', function () {
    $('#createPostModal').modal('hide');
});
/* ===================== GLOBAL STATE ===================== */
let newFiles = [];
let existingAttachments = [];

/* ===================== FILE INPUT ===================== */

const IMAGE_LIMITS = {
    twitter: 4,
    facebook: 10,
    both:4
};

/* ===================== CHANNEL CHANGE ===================== */
$('#channelDropdown').on('change', function () {
    const channel = $(this).val();
    const $message = $('#message');
    const $fileInput = $('#fileInput');

    if (channel === 'twitter') {
        $message.prop('disabled', false).attr('maxlength', 280);
    } else if (channel === 'facebook') {
        $message.prop('disabled', false).attr('maxlength', 60000);
    } else if (channel === 'both') {
        $message.prop('disabled', false).attr('maxlength', 280);
    } else {
        $message.prop('disabled', true).val('').removeAttr('maxlength');
    }

    if (!channel) {
        $fileInput.prop('disabled', true).val('');
        return;
    }

    $fileInput.prop('disabled', false);
    $fileInput.data('max-files', IMAGE_LIMITS[channel]);
});

/* ===================== FILE INPUT (CUMULATIVE + EDIT MODE LIMIT FIX) ===================== */
$('#fileInput').on('change', function () {
    const maxFiles = $(this).data('max-files') || 0;
    const selectedFiles = Array.from(this.files);

    // ✅ count existing + already added + newly selected
    const existingCount = existingAttachments.length;
    const newCount = newFiles.length;
    const totalAfterAdd = existingCount + newCount + selectedFiles.length;

    if (maxFiles && totalAfterAdd > maxFiles) {
        alert(`You can select a maximum of ${maxFiles} images for this channel.`);
        this.value = '';
        return;
    }

    selectedFiles.forEach(file => {
        newFiles.push({
            id: crypto.randomUUID(),
            file: file,
            url: URL.createObjectURL(file),
            isImage: file.type.startsWith('image/')
        });
    });

    renderLists();
    appendNewPreviews();
    this.value = '';
});


/* ===================== RENDER FILE LISTS ===================== */
function renderLists() {
    if (existingAttachments.length) {
        $('#existingFileList').html(
            existingAttachments.map((att, index) => `
                <li class="mb-2 d-flex align-items-center gap-2" data-index="${index}">
                    ${att.isImage
                        ? `<img src="${att.url}" style="max-height:60px">`
                        : `<i class="fas fa-file-alt"></i>`}
                    <span class="small flex-grow-1">${att.name}</span>
                    <span class="badge bg-secondary">existing</span>
                    <button 
                        type="button" 
                        class="btn btn-sm btn-outline-danger remove-existing"
                        data-index="${index}">✖
                    </button>
                </li>
            `).join('')
        );
    }
    $('#newFileList').html(
        newFiles.map(f => `
            <li class="mb-2 d-flex align-items-center gap-2" data-id="${f.id}">
                ${f.isImage
                    ? `<img src="${f.url}" style="max-height:60px">`
                    : `<i class="fas fa-file-alt"></i>`}
                <span class="small flex-grow-1">${f.file.name}</span>
                <span class="badge bg-info">new</span>
                <button type="button" class="btn btn-sm btn-outline-danger remove-file">✖</button>
            </li>
        `).join('')
    );
}
$(document).on('click', '.remove-existing', function () {

    // alert("Are You Sure You want to remove image from Post?");
    let index = $(this).data('index');
    let removedAttachment = existingAttachments[index];

    // remove from array
    existingAttachments.splice(index, 1);
    $('#previewImages')
        .find(`img[data-existing="${removedAttachment.url}"]`)
        .remove();
    // remove from UI
    $(this).closest('li').remove();

    $.ajax({
        url: 'omnichannel_config/direct_message_function.php',
        type: 'POST',
        data: {
            id: $('#edit_id').val(),                     // correct post id
            channeltype: $('#channelDropdown').val(),    // ✅ FIXED
            attachment: removedAttachment.url,         // exact DB value
            action: 'delete_attachment'
        },
        success: function (res) {
            let data = (typeof res === 'string') ? JSON.parse(res) : res;
            if (data.status === 'success') {
                alert('Image removed successfully');
            }
        }
    });
});



/* ===================== APPEND PREVIEWS ===================== */
function appendExistingPreviews() {
    existingAttachments.forEach(att => {
        if (!att.isImage) return;
        if ($('#previewImages').find(`[data-existing="${att.url}"]`).length) return;

        $('#previewImages').append(`
            <img src="${att.url}"
                 data-existing="${att.url}"
                 class="rounded border shadow-sm"
                 style="height:90px">
        `);
    });
}

function appendNewPreviews() {
    newFiles.forEach(f => {
        if (!f.isImage) return;
        if ($('#previewImages').find(`[data-id="${f.id}"]`).length) return;

        $('#previewImages').append(`
            <img src="${f.url}"
                 data-id="${f.id}"
                 class="rounded border shadow-sm"
                 style="height:90px">
        `);
    });
}

/* ===================== REMOVE NEW FILE ONLY ===================== */
$(document).on('click', '.remove-file', function () {
    let id = $(this).closest('li').data('id');

    newFiles = newFiles.filter(f => {
        if (f.id === id) {
            URL.revokeObjectURL(f.url);
            $('#previewImages').find(`[data-id="${id}"]`).remove();
            return false;
        }
        return true;
    });

    renderLists();
});
$('#createPostModal').on('shown.bs.modal', function () {
    syncMessagePreview();
});

function syncMessagePreview() {
    const msg = $('#message').val() || '';
    $('#previewMessage').text(msg);
    showPreviewIfNeeded();
}
/* ===================== EDIT POST ===================== */
$(document).on('click', '.edit-post', function (e) {
    e.preventDefault();

    let id = $(this).data('id');
    let channeltype = $(this).data('channel_type');

    $('#quickForm')[0].reset();
    $('#existingFileList').html('');
    $('#newFileList').html('');
    $('#previewImages').html('');
    $('#hi').hide();

    existingAttachments = [];
    newFiles = [];

    $('#single_send_button').text('Update');

    // 🔥 FORCE preview sync AFTER textarea value is set
   setTimeout(syncMessagePreview, 0);

    $.ajax({
        url: 'omnichannel_config/direct_message_function.php',
        type: 'POST',
        data: {
            action: 'get_post_details',
            id: id,
            channeltype: channeltype
        },
        success: function (response) {
            let data = JSON.parse(response);

            $('#edit_id').val(id);
            $('#message').val(data.message || '');

            // CHANNEL
            let channel = Array.isArray(data.channel_type)
                ? data.channel_type[0]
                : data.channel_type;
            // SCHEDULE PREFILL
            if (data.schedule_flag === "1" && data.schedule_time) {
                $('#scheduletime')
                    .prop('checked', true)
                    .prop('disabled', false);

                $('#hi').show();

                $('#pickdate')
                    .prop('disabled', false)
                    .val(data.schedule_time.replace(' ', ' '));
            } else {
                $('#scheduletime')
                    .prop('checked', false);

                $('#hi').hide();

                $('#pickdate')
                    .val('')
                    .prop('disabled', true);
            }

            $('#channelDropdown').val(channel).trigger('change');

            // EXISTING ATTACHMENTS
            if (Array.isArray(data.attachments)) {
                data.attachments.forEach(file => {
                    let isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(file);
                    existingAttachments.push({
                        url: file,
                        name: file.split('/').pop(),
                        isImage
                    });
                });
            }

            renderLists();
            appendExistingPreviews();

            // 🔒 DISABLE FILE INPUT IF LIMIT REACHED
            const maxFiles = IMAGE_LIMITS[channel] || 0;
            const existingImageCount = existingAttachments.filter(a => a.isImage).length;

            if (maxFiles && existingImageCount >= maxFiles) {
                $('#fileInput').prop('disabled', true);
            } else {
                $('#fileInput').prop('disabled', false);
            }

            $('#createPostModal').modal('show');
        },
        error: function () {
            alert('Failed to fetch post details');
        }
    });
});

// OPTIONAL: LIVE CHARACTER COUNTER
$('#message').on('input', function () {
    const max = $(this).attr('maxlength');
    const len = this.value.length;

    $('#charCount').text(`${len}/${max}`);
});

$(document).on('click', '#viewEdit', function (e) {
    e.preventDefault();

    let id = $(this).data('id');
    let channeltype = $(this).data('channel');

    // 🔁 Trigger old edit logic
    $('<a>')
        .addClass('edit-post')
        .attr('data-id', id)
        .attr('data-channel_type', channeltype)
        .appendTo('body')
        .trigger('click')
        .remove();

    // Close view modal (optional but recommended)
    $('#viewPostModal').modal('hide');
});
$(document).on('click', '.open-create-post', function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();

  $('#quickForm')[0].reset();

  // Clear hidden edit ID
  $('#edit_id').val('');

  // Clear Select2
  $('#selecttemplate').val(0).trigger('change.select2');

  // Clear attachments preview
  $('#fileList').html('');
  $('#channelDropdown').val('').trigger('change');

  // Hide schedule fields
  $('#scheduletime').prop('checked', false);
  $('#hi').hide();

    $('#createPostModal').modal('show');
    $('#postPreview').hide();    
      $('#previewMessage').html('');     
      
      $('#previewImages').html('');       
});
$(document).on('click', '.view-post', function (e) {
    e.preventDefault();

    let postText = $(this).data('post') || '';
    let images   = $(this).data('images') || [];

    let status   = String($(this).data('status'));
    let groupid  = String($(this).data('groupid'));
    let id       = $(this).data('id');
    let channel  = $(this).data('channel_type');

     // ---------- HEADER META ----------
    let createdAt   = $(this).data('created_at') || 'N/A';
    let statusText   = $(this).data('status_text') || 'N/A';
    let scheduleAt  = $(this).data('schedule_time') || '';
    let createdBy   = $(this).data('created_by') || 'N/A';

    // Build header HTML
    let headerHtml = `
      <div class="w-100 d-flex flex-wrap gap-3">
        <div><strong>Channel:</strong> ${channel} Post</div>
        <div><strong>Status:</strong> ${statusText}</div>
        <div><strong>Created By:</strong> ${createdBy}</div>
        <div><strong>Created On:</strong> ${createdAt}</div>
        ${
            scheduleAt && scheduleAt !== '0000-00-00 00:00:00'
            ? `<div><strong>Scheduled On:</strong> ${scheduleAt}</div>`
            : ''
        }
        </div>
            `;

    $('#viewPostHeader').html(headerHtml);

  
    // ---------- Render Post ----------
    let html = `
        <div class="post-box">
            <div class="post-content mb-3">
                <p style="white-space: pre-wrap;">${postText}</p>
            </div>`;

    if (Array.isArray(images) && images.length > 0) {
        html += `<div class="row">`;
        images.forEach(img => {
            html += `
                <div class="col-md-4 col-sm-6 mb-3">
                    <img src="${img}" class="img-fluid rounded border"/>
                </div>`;
        });
        html += `</div>`;
    } else {
        html += `<p class="text-muted fst-italic">No images attached.</p>`;
    }

    html += `</div>`;
    $('#postContentContainer').html(html);

    // ---------- Reset Buttons ----------
    $('#viewEdit, #viewDelete, #viewVerify').addClass('d-none');

    // ---------- Permission Logic ----------
    if (status === '0' || status === '2') {
        $('#viewEdit, #viewDelete').removeClass('d-none');
    }

    if (status === '4' && groupid !== '070000') {
        $('#viewEdit, #viewDelete, #viewVerify').removeClass('d-none');
    }

    if (status === '4' && groupid === '070000') {
        $('#viewEdit, #viewDelete').removeClass('d-none');
    }

    // ---------- Attach Button Data ----------
    $('#viewEdit').data({ id, channel });
    $('#viewDelete').data({ id, channel });
    $('#viewVerify').data({ id, channel, post: postText });

    $('#viewPostModal').modal('show');
});


//  remakr event  for adding remark to open modal [vastvikta][17-12-2025]
$(document).on('click', '.add-remark', function (e) {
    e.preventDefault();

    const remark = $(this).data('remark') || '';
    const id = $(this).data('id');
    const channel_type = $(this).data('channel_type');


    $('#remarkText').val(remark);
    $('#remarkRowId').val(id);
    $('#rowchannel_type').val(channel_type);

    $('#remarkModal').modal('show');
});
// calling  js code for adding remark [vastvikta ][17-12-2025]
$('#saveRemarkBtn').on('click', function () {

    const remark = $('#remarkText').val().trim();
    const id = $('#remarkRowId').val();
    const channel_type = $('#rowchannel_type').val();
    if (remark === '') {
        alert('Remark cannot be empty');
        return;
    }

    $.ajax({
        url: 'omnichannel_config/direct_message_function.php',
        type: 'POST',
        data: {
            action: 'add_remark',
            id: id,
            remark: remark,
            channel_type: channel_type,
        },
        success: function (res) {
            $('#remarkModal').modal('hide');
            location.reload(); // or DataTable reload
        },
        error: function () {
            alert('Failed to save remark');
        }
    });
});
let verifyData = {};

// function for verification of the  post [vastvikta][23-12-2025]
$(document).on('click', '.verify-post', function () {

    verifyData.id      = $(this).data('id');
    verifyData.channel = $(this).data('channel_type');
    verifyData.post    = $(this).data('post');

    $('#verifyPostContent').text(verifyData.post);
    $('#verifyPostModal').modal('show');
});



// function for the verification code to get the data [vastvikta][23-12-2025]
$(document).on('click', '#viewVerify', function () {

    let id      = $(this).data('id');
    let channel = $(this).data('channel');

    if (!id || !channel) {
        alert('Missing verification data');
        return;
    }

    // Optional safety confirm
    if (!confirm('Are you sure you want to verify this post?')) {
        return;
    }

    $.ajax({
        url: 'omnichannel_config/direct_message_function.php',
        type: 'POST',
        data: {
            action: 'verify_post',
            id: id,
            channel_type: channel
        },
        success: function (res) {
            alert('Verification Successful!');
            location.reload();
        },
        error: function () {
            alert('Failed to Verify');
        }
    });
});

$(document).on('click', '.view-approval-history', function () {

    let historyData = $(this).attr('data-history');

    try {
        let history = JSON.parse(historyData);
        let html = '';

        if (history.length > 0) {

            history.forEach(function(item) {

                html += `
                <tr>
                    <td>${item.user_id ?? ''}</td>
                    <td>${item.action ?? ''}</td>
                    <td>${item.channel ?? ''}</td>
                    
                    <td>${item.datetime ?? ''}</td>
                </tr>`;
            });

        } else {
            html = `<tr><td colspan="5" class="text-center">No Data Found</td></tr>`;
        }

        $('#remarksTable').html(html);

        // show modal
        let modal = new bootstrap.Modal(document.getElementById('remarksModal'));
        modal.show();

    } catch (e) {
        console.error('Invalid JSON:', e);
    }

});

function togglePostFields(enable) {

    $('#message').prop('disabled', !enable);
    $('#fileInput').prop('disabled', !enable);
    $('#scheduletime').prop('disabled', !enable);
    $('#pickdate').prop('disabled', !enable);

    $('#selecttemplate')
        .prop('disabled', !enable)
        .trigger('change.select2');
}

// 🔒 Disable everything initially
togglePostFields(false);

// 🔁 Channel selection handler
$('#channelDropdown').on('change', function () {

    let hasChannel = $(this).val() !== '';

    togglePostFields(hasChannel);

    // If channel is cleared → reset dependent fields
    if (!hasChannel) {
        $('#message').val('');
        $('#selecttemplate').val(0).trigger('change.select2');
        $('#scheduletime').prop('checked', false);
        $('#hi').hide();
        $('#pickdate').val('');

        // Clear attachments preview
        $('#existingFileList').html('');
        $('#newFileList').html('');
        newFiles = [];
    }
});

