/**
 * ============================================================
 * File Name   : backoffice.js
 * Module      : Case Details - Backoffice (CRM)
 * ============================================================
 *
 * Description:
 * This script manages all client-side interactions on the
 * Case Details Backoffice page, including:
 *
 * - Click-to-call handling and agent status verification
 * - Case validation, rejection, and feedback visibility
 * - Add / update case interactions and remarks
 * - Callback date-time validation
 * - Dynamic loading of Request Types and Enquiry Types
 * - Auto-generation of Case Title using Product + Enquiry Type
 * - Detection of Customer (Student) and Case field changes
 * - Conditional Student update and Case update API calls
 * - Unified handling of Case detail updates and status updates
 *   (resolve / reopen)
 * - Merge / Unmerge ticket operations
 * - Disposition handling
 * - Omni-channel actions (Email, SMS, WhatsApp, Instagram, Messenger)
 *
 * Update Flow Summary:
 * 1) Capture original form values on page load
 * 2) On Update Case click:
 *    - Validate required fields
 *    - Detect changed fields
 *    - Update Student info (if changed)
 *    - Update Case info and/or Status
 *    - Show final success message and reload page
 *
 * Developer        : Farhan Akhtar
 * Last Modified On : 25-Feb-2026
 *
 * ============================================================
 */


//*******************************************Code Start case details backoffice page*********************************
// get agent status from autodial_live_agent starts
function clickcall_c2c(mobile, cid, trunk, agent) {
   $.ajax({
      url: "../../../universus/checkAgentStatus.php",
      type: "POST",
      data: {
         'user': agent,
      },
      async: true,
      crossDomain: true,
      success: function(result) {
         console.log('Agent status:' + result);
         if (result != "READY" && result != "REST") {
            var userWidth = screen.availWidth;
            var userHeight = screen.availHeight;
            var popW;
            var popH;
            var leftPos;
            var topPos;
            popW = 500;
            popH = 260;
            settings =
               'modal,scrollBars=no,resizable=no,toolbar=no,menubar=no,location=no,directories=no,';
            leftPos = (userWidth - popW) / 2,
               topPos = (userHeight - popH) / 2;
            settings += 'left=' + leftPos + ',top=' + topPos + ',width=' + popW + ', height=' +
               popH + '';
            window.open("../../universus/clicktocall_popup.php?V_Dial_Number=" + mobile + "&cid=" +
               cid + "&trunk=" + trunk + "&agent=" + agent, "Clicktocall", settings, 'true');
         } else {
            alert("You can't make call in READY mode or in Rest Break\n\nPlease chose Preview mode  to initiate a Dial Out");
       
         }
      }
      // get agent status from autodial_live_agent ends
   });
}
function Rejected() {
   //document.getElementById('div1').style.display ='none';
   document.getElementById('div1').style.display = 'block';
   $("#back_office_action").hide();
   $("#suggested_follow").hide();
   $("#OverAllRemark_div").show();
   $("#div2").show();
}
function Validated() {
   document.getElementById('div1').style.display = 'block';
   $("#back_office_action").show();
   $("#suggested_follow").show();
   $("#OverAllRemark_div").hide();
   $("#div2").hide();
}
// take feed from customer if agent resolve the case 
// Vijay : 30-11-2020
function getfeedback(complaint_status) {
   if (complaint_status == '8') {
      $("#feedbackdiv").show();
   } else {
      $("#feedbackdiv").hide();
   }
}
function cl121(nval, val) {
   document.getElementById('rec_f').innerHTML = "<embed height='40' width='100%' src='" + nval +
      "' type='audio/mpeg'>";
   return false;
}


function sendpdf_form() {
   var emails = $("input#case").val();
   var quotation = $("input#quotation").val();
   if (emails == "") {
      alert('Please Select Suggested Follow');
      return false;
   }
   var uri = "suggested_followup_mail.php?quotation=" + quotation + "&case=" + emails;
   var uri = encodeURI(uri)
   // document.getElementById("myForm").target = "_blank";
   window.open(uri);
   // window.location.href =uri;
}
function add_remove_emails(email_id) {
   console.log('hkajhdjka');
   var id = 'suggested_follow_' + email_id;
   var newemails = '';
   if ($("#" + id).is(":checked")) {
      console.log('emails in if case addddddddd');

      var emails = $("input#case").val();
      if (emails == '') {
         $("#case").val(email_id);
      } else {
         emails += ',' + email_id;
         $("#case").val(emails);
      }
   } else {
      console.log('emails in else case remove ');

      // var email_id = 'suggested_follow_'+email_id;
      var emails = $("#case").val();
      res = emails.split(',');

      for (var i = 0; i < res.length; i++) {
         if (res[i] != email_id) {
            newemails += res[i] + ',';
         }
      }
      newemails = newemails.substr(0, newemails.length - 1);
      $("#case").val(newemails);
   }
}

/* Add More Interaction case wise store Values docked_id, customer_id, source */
function addmore_interaction(docked_id, customer_id, source, rowid) {
   if (docked_id != '') {
      $("#docket_no").val(docked_id);
      $("#rowid").val(rowid);
      // $("#source_id").val(source);
      $("#customer_id").val(customer_id);

      $("#ticket_no").val(docked_id);
      $("#feed_source_id").val(source);
      $("#feed_customer_id").val(customer_id);

      $("#addInteraction_form").show();
   }
}
//for change status code
function change_new_status(status) {
   // console.log('current_status');
   // console.log(status);
   $("#save_current_status").val(status);
}
//for set status code
function set_status_values(feedback_val) {
   if (feedback_val == '0') {
      $("select#current_status_type_").val('5');
      $("#feed_current_status_type_").val('5');
      $("#save_current_status").val(5);
   }
   if (feedback_val == '2') {
      $("select#current_status_type_").val('8');
      $("#feed_current_status_type_").val('8');
      $("#save_current_status").val(8);
   }
   if (feedback_val == '1') {
      $("select#current_status_type_").val('3');
      $("#feed_current_status_type_").val('3');
      $("#save_current_status").val(3);
   }

   // console.log('feedback_val '+ feedback_val);
}


/* Add new Interaction Form */
$("#addInteraction_form").on('submit', (function(e) {
  e.preventDefault();
  console.log('ok Going to process addInteraction_form');
  
  var remark = $("#interaction_remark").val();
  if (remark == '') {
     alert('Please Enter Remark');
     $("#interaction_remark").focus();
     return false;
  }
   //   updated the code for the alert on the call back time [vastvikta][24-03-2025]
  var isCallbackChecked = $("#callbk").is(":checked");
  var callbackTime = $("#cb_date").val(); // Date entered in DD-MM-YYYY HH:mm:ss

  if (isCallbackChecked) {
      if (callbackTime === '') {
         alert('Please Enter Callback Time');
         $("#cb_date").focus();
         return false;
      }

      // Convert selected callbackTime from DD-MM-YYYY HH:mm:ss to a proper JavaScript Date object
      var dateParts = callbackTime.split(" "); // Splitting date and time
      var dateOnly = dateParts[0].split("-"); // Splitting DD-MM-YYYY
      var timeOnly = dateParts[1].split(":"); // Splitting HH:mm:ss

      var inputDate = new Date(dateOnly[2], dateOnly[1] - 1, dateOnly[0], timeOnly[0], timeOnly[1]); // YYYY, MM (0-based), DD, HH, MM

      // Get current date and time
      var currentDate = new Date();

      // Remove seconds and milliseconds for comparison
      inputDate.setSeconds(0, 0);
      currentDate.setSeconds(0, 0);

      console.log("Current Date:", currentDate);
      console.log("Input Date:", inputDate);

      // Compare only Date & Time (ignoring seconds & milliseconds)
      if (inputDate < currentDate) {
         alert('Callback time cannot be a backdate.');
         $("#cb_date").focus();
         return false;
      }
   }
  $("#remark_button").prop('disabled', true);
  $("#remark_button").val('Please Wait...');
  $.ajax({
     url: 'helpdesk/web_ticket_function.php',
     type: "POST",
     data: new FormData(this),
     dataType: 'json',
     contentType: false,
     cache: false,
     processData: false,
     success: function(data) {
        console.log('data response');
        console.log(data);
        $("#remark_button").prop('disabled', false);
        $("#remark_button").val('Save New Remark');
        var last_docket = $('#docket_no').val();
        if (data.status == "fail") {
           $("#responseMessage2").text(data.message).css('color', 'red');
        } else {
           $("#responseMessage2").text(data.message).css('color', 'green');
           // change value of status 
           var c_st = $("#save_current_status").val();
           $('select#current_status_type_').val(c_st);
           $('select#status_type_').val(c_st);
           if (c_st == '8') {
              $("#feedback_form").show();
              var rowid = $("#rowid").val();
           }
           $("html, body").animate({
              scrollTop: 0
           }, "slow");
            $("#show_ticket").empty();
            $("#show_ticket").text(data.message);
            $("#show_ticket").show();
            // change value of status 
            var c_st = $("#save_current_status").val();
            $('select#current_status_type_').val(c_st);
            $('select#status_type_').val(c_st);
            if (c_st == '8') {
               $("#feedback_form").show();
               var rowid = $("#rowid").val();
            }
            setTimeout(function() {
               $('#addInteraction_form').hide();
               var encodedToken = btoa('web_case_detail');
               var docket= btoa(last_docket);
               var redirectURL = "helpdesk_index.php?token=" + encodeURIComponent(encodedToken)+"&id=" + encodeURIComponent(docket);
               // window.location.href = redirectURL; 

               window.location.reload();
               console.log(redirectURL);  
            }, 1000);
        }
     },
     error: function(error) {
        $("#remark_button").prop('disabled', false);
        $("#remark_button").val('Save New Remark');
        console.log('Error');
        console.log(error);
     },
     complete: function() {
        $("#search-docket").prop('disabled', false);
        $("#search_btn").prop('disabled', false);
        setTimeout(function() {
           $("#interaction_remark").val('');
           $("#responseMessage2").text('');
        }, 2000);

     }
  });
}));

$("#edit_button").click(function(event) {
   event.preventDefault();
   $('.inputDisabled').prop("disabled", false); // Element(s) are now enabled.
   $("#edit_button").hide();
   $("#save_button").show();

});

function loadRequestTypes(department) {

    // reset child dropdowns
    $("#requesttype").html('<option value="0">Select</option>');
    $("#enquirytype").html('<option value="0">Select</option>');

    if (department === "0" || department === "") return;

    $.ajax({
        url: "helpdesk/web_ticket_function.php",
        type: "POST",
        data: { action: "getrequesttype", department: department },
        dataType: "json",
        success: function(response) {

            let options = '<option value="0">Select</option>';

            if (response.success && response.data.length > 0) {
                response.data.forEach(function(row) {
                    options += `<option value="${row.requestType}">${row.requestType}</option>`;
                });
            } else {
                options = '<option value="0">N/A</option>';
            }

            $("#requesttype").html(options);
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
        }
    });
}


// Also call after enquiry types are loaded dynamically
function loadEnquiryType(requestType) {
    if (requestType === "0" || requestType === "") {
        $("#enquirytype").html('<option value="0">Select</option>');
        updateCaseTitle(); // reset case title if nothing
        return;
    }

    $.ajax({
        url: "helpdesk/web_ticket_function.php",
        type: "POST",
        data: { action: "getenquiry", requestType: requestType },
        dataType: "json",
        success: function(response) {
            let options = '';
            if (response.success && response.data.length > 0) {
                response.data.forEach(function(dept) {
                    options += `<option value="${dept.enquiryType}">${dept.enquiryType}</option>`;
                });
            } else {
                options = '<option value="0">N/A</option>';
            }
            $("#enquirytype").html(options);

            updateCaseTitle(); //  update case title after loading enquiry types
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
        }
    });
}

/* Collect Email To show Which Diratment Assigned   */
function get_assigne_email(department_id) {
   //alert(type);
   console.log('department_id == ' + department_id);
   // console.log('catid == ' + catid);
   var option = '';
   var sel = '';
   $.ajax({
      url: 'helpdesk/web_ticket_function.php',
      type: 'post',
      data: {
         'department_id': department_id,
         'action':'ajax_Assign_Department'
      },
      // dataType: 'json',
      success: function(data, status) {
         $("#show_emails").empty();
         $("#show_emails").html('<span>' + data + '</span>').css('color', 'green');

      },
      error: function(xhr, desc, err) {},
      complete: function() {}
   });
}
function get_department(category_id) {
   //alert('get_department ' +category_id);
   //console.log('type == ' + category_id);
   // console.log('catid == ' + catid);
   var option = '';
   var sel = '';
   $.ajax({
      url: 'helpdesk/web_ticket_function.php',
      type: 'post',
      data: {
         'category_id2': category_id,
         'action':'ajax_department'
      },
      dataType: 'json',
      success: function(data, status) {
         console.log('Department');
         console.log(data);
         option = '<option value="0">Select Department</option>';
         $.each(data, function(index, value) {
            option += '<option value=' + value.pId + ' selected >' + value.vProjectName + '</option>';
            get_assigne_email(value.pId);
         });


         $("#group_assign").empty();
         $("#group_assign").html(option);
      },
      error: function(xhr, desc, err) {
         console.log('err');
         console.log(err);
      },
      complete: function() {}
   });
}


function RemoveCaseIssues(issue_id) {
   //alert(issue_id);
   $("#Remark" + issue_id).css('display', 'none');
   $("#issueslist_" + issue_id).val('');
}


function checkme(val, dbval) {
   if (val == 'Partner') {
      $("#dir_in_email").html(
         '<input name="opticianemail" id="opticianemail" type="hidden" value="" class="input-style1">');
   } else {
      $('#dir_in_email').html(
         '<label style="padding:0px 25px 0 0;""></label><input type="hidden" name="opticianemail" id="opticianemail" class="input-style1" value="' +
         dbval + '">');
   }
}


/* Add new Interaction Form */
$("#viewproblemfrm").on('submit', (function(e) {
   e.preventDefault();
   $("#update_btn").prop('disabled', true);
   $("#update_btn").val('Please Wait...');
   $.ajax({
      url: 'helpdesk/web_helpdesk_function.php',
      type: "POST",
      data: new FormData(this),
      dataType: 'json',
      contentType: false,
      cache: false,
      processData: false,
      success: function(data) {
         console.log('data response');
         console.log(data);
            $("#update_btn").prop('disabled', false);
            $("#update_btn").val('Update');
            $("#show_ticket").text(data);
            $("#show_ticket").show();
            $("html, body").animate({
               scrollTop: 0
            }, "slow");
            setTimeout(function() {
               window.location.reload();
            }, 2000);
      },
      error: function(error) {
         $("#update_btn").prop('disabled', false);
         $("#update_btn").val('Save New Remark');
         $("#show_ticket").text('Error');
         console.log('Error');
         console.log(error);
      }
   });   
}));


// For same category ticket merge code
function addMergeTicket(ticket_id, customer, i_source, status_type){
   $('#myModal').modal('show');
   $.ajax({
      url: 'helpdesk/merge_ticket.php',
      type: 'post',
      data: {
         'ticket_id': ticket_id,
         'customer': customer,
         'action': 'fetch_ticket'
      },
      dataType: 'json',
      success: function(data) {
         $("#marge_select").html(data);
         $("#marge_source").val(i_source);
         $("#marge_status_type").val(status_type);
         $("#marge_customerr").val(customer);
         $("#marge_ticket").val(ticket_id);
      }
   });
}
//updated code for ticket merge detail view [vastvikta][04-12-2025]
$(document).on('change', '#marge_select', function() {
    let ticket_no = $(this).val();

    if(ticket_no == 0){
        $("#ticket_details").hide();
        return;
    }

    $.ajax({
        url: 'helpdesk/merge_ticket.php',
        type: 'POST',
        data: {
            'action': 'fetch_ticket_details',
            'ticket_no': ticket_no
        },
        dataType: 'json',
        success: function(res) {
            $("#show_enquiry").text(res.enquiryType);
    $("#show_source").text(res.source_name);   // updated
            $("#ticket_details").show();
        }
    });
});

// For same category ticket unmerge code
function UnMergeTicket(ticket_id,customer,i_source,status_type){
   if (confirm("Are you sure to Unmerge this ticket ?")) {
      $.ajax({
         url: 'helpdesk/merge_ticket.php',
         type: 'post',
         data: {
            'ticket_id': ticket_id,'customer':customer,'action':'Unfetch_ticket','status_type':status_type,'source_id':i_source,
         },
         dataType: 'json',
         success: function(data) {
            window.location.reload(true);
         }
      });
   }
}
// For same category ticket merge code
function handleMergeSubmit(){
   var ticket_id = $('#marge_select').val();
   var remarks = $('#merge_remarks').val();
   var source_id= $("#marge_source").val();
   var status_type = $("#marge_status_type").val();
   var customerr = $("#marge_customerr").val();
   var marge_ticket = $('#marge_ticket').val();
   $.ajax({
      url: 'helpdesk/merge_ticket.php',
      type: 'post',
      data: {
         'ticket_id': ticket_id,'customer':customerr,'remarks':remarks,'status_type':status_type,'source_id':source_id,'action':'submit_merge','marge_ticket':marge_ticket},
      dataType: 'json',
      success: function(data) {
         console.log(data);
         if(data){
            $('#myModal').modal('hide');
            window.location.reload(true);
         }else{
         }
      }
   });
}
/* Disposition Start--- */
$("#callbk").change(function() {
// Check if the checkbox is checked
if ($(this).is(":checked")) {
 console.log("Callback checkbox is checked")
 $(".cb").show()
} else {
 console.log("Callback Checkbox is unchecked")
 $(".cb").hide()
 }
});
function validate_dispose() {
    var now_date_time = Date.now();
    console.log('now_date_time ' + now_date_time);
    var typeVal = $("input[name='callbk']:checked").val();
    console.log('typeVal ' + typeVal);
    if (typeVal != undefined) {
        var cb_date = $("#cb_date").val();
        console.log('cb_date ' + cb_date);
        /*if(cb_date =='' || cb_date ==undefined){
            alert("Please Select Disposition Date");$("#cb_date").focus();return false;
        }*/
        /*if(new Date(cb_date) <= new Date(now_date_time)){
            alert("Please Select Correct Disposition Date");$("#cb_date").focus();return false;
         //compare end <=, not >=
          //your code here
         }*/
    }
    var disposition = $("#disposition").val();
    if (disposition == '0') {
        alert("Please Select Disposition backoffice");
        $("#disposition").focus();
        return false;
    }
    var remark = $("#remark").val();
    if (remark == '') {
        alert("Please Enter Remark");
        $("#remark").focus();
        return false;
    }
    return true;
}
// added code for compose message on case detail backoffice [vastvikta][03-04-2025]
// Email button click event
$('.emailConMess').click(function() {
   let email = $("#email").val().trim();
   let customer_id = $("#customer_id").val();
   let caseid = $("#docket_no").val();
   if(email == ""){
      alert('Please Enter Email ID');
      // Dismiss the modal with ID 'staticBackdrop'
      $('#staticBackdrop').modal('hide');
   }else{
      
   // If the email is not empty, open the new window
   window.open('omnichannel_config/web_send_email_reply.php?action="content-messaging"&reply_to='+email+'&customerid='+customer_id+'&caseid='+caseid,
      '_blank', 
      'height=550, width=900,scrollbars=0');
   }

});
// instagram reply  code [vastvikta][15-04-2025]
$('.instagramConMess').click(function() {
   // Get the trimmed values of first and last names
   let instagramhandle = $("#instagramhandle").val().trim();

   let customer_id = $("#customer_id").val();
   let caseid = $("#docket_no").val();

   if(instagramhandle == ""){
      alert('Please Enter Instagram Handle');
      // Dismiss the modal with ID 'staticBackdrop'
      $('#staticBackdrop').modal('hide');
   }else{
      // If the email is not empty, open the new window
      window.open('omnichannel_config/contentMess_instagram.php?action="content-messaging"&instagramhandle='+instagramhandle+'&customerid='+customer_id+'&caseid='+caseid,
         '_blank', 
         'height=500, width=800,scrollbars=0');
   }

});
// SMS button click event
$('.smsConMess').click(function() {
   // Get the trimmed values of first and last names
   let firstName = $("#first_name").val().trim();
   let lastName = $("#last_name").val().trim();
   let customer_id = $("#customer_id").val();
   let caseid = $("#docket_no").val();
  
   // Combine first and last name with a space in between
   let name = firstName + " " + lastName;
   let phone = $("#phone").val().trim();

   if(phone == ""){
      alert('Please Enter Registrer Noss');
      // Dismiss the modal with ID 'staticBackdrop'
      $('#staticBackdrop').modal('hide');
   }else{
      // If the email is not empty, open the new window
      window.open('omnichannel_config/contentMess_sms.php?action="content-messaging"&name='+name+'&phone='+phone+'&customerid='+customer_id+'&caseid='+caseid,
         '_blank', 
         'height=500, width=800,scrollbars=0');
   }

});

// Whatsapp button click event
$('.whatsappConMess').click(function() {
   // Logic for WhatsApp interaction
   let phone = $("#whatsapphandle").val();
   let customer_id = $("#customer_id").val();
   let caseid = $("#docket_no").val();
   if(phone == ""){
      alert('Please Enter Whatsapp No');
      // Dismiss the modal with ID 'staticBackdrop'
      $('#staticBackdrop').modal('hide');
   }else{
      // If the email is not empty, open the new window
      window.open('omnichannel_config/contentMess_whatsapp.php?action="content-messaging"&phone='+phone+'&customerid='+customer_id+'&caseid='+caseid,
         '_blank', 
         'height=500, width=800,scrollbars=0');
   }
});

// Messenger button click event
$('.fbmessConMess').click(function() {
   // Logic for Facebook Messenger interaction
    let facebookid = $("#messengerhandle").val();
    let customer_id = $("#customer_id").val();
    let caseid = $("#docket_no").val();
   
    if(facebookid == ""){
       alert('Please Enter Messenger Handle');
       // Dismiss the modal with ID 'staticBackdrop'
       $('#staticBackdrop').modal('hide');
    }else{
       // If the email is not empty, open the new window
       window.open('omnichannel_config/contentMess_messenger.php?action="content-messaging"&facebookid='+facebookid+'&customerid='+customer_id+'&caseid='+caseid,
          '_blank', 
          'height=500, width=800,scrollbars=0');
    }
});
// code end
$("#disposeAction").on("submit",function (event) {
   event.preventDefault()
   let validate = validate_dispose()
   if(validate == true){
     $("#processModel").show()
     $("#dispose").val('Please Wait...')
     //AJAX request
     $.ajax({
       url : 'helpdesk/web_ticket_function.php',
       type: "POST",
       data: new FormData(this),
       dataType: 'json',
       contentType: false,
       cache: false,
       processData: false,
      //  updated the success part so that alert can be displayed[vastvikta][27-03-2025]
       success: function (data) {
    
         setTimeout(() => {
            $("#processModel").hide();
            $("html, body").animate({scrollTop: 0}, "slow");
         }, 1000);

         if (data.status === "success") {
           
            $(".alert").css({"background": "#00CC66", "display": "block"}).text(data.message);
            $("#dispose").hide();
            setTimeout(() => {
                  window.location.href = data.url;
            }, 4000);
         } else {
           
            $(".alert").css({"background": "crimson", "display": "block"}).text(data.message);
            alert(data.message);
            setTimeout(() => {
                  $(".alert").css("display", "none");
            }, 2000);
            $("#dispose").val("DISPOSE").show();
         }
      },
      error: function (error) {
         console.log("AJAX error:", error);
         $("#processModel").hide();
         $("#dispose").val("DISPOSE").show();
      }

     });
   }else{
     return false
   }
});


/**
 * Case & Student Update Handler
 *
 * Description:
 * - Auto-generates Case Title using: Product + Enquiry Type
 *   (Product dropdown may be disabled, so title updates when Enquiry Type changes + on page load)
 *
 * - Captures original Customer (Student) + Incident (Case) form values on page load
 *
 * - On "Update Case" button click:
 *    1) Validates required fields (Phone, Email format, Case fields)
 *    2) Detects changes by comparing current values vs original snapshot
 *    3) Shows spinner + disables update button
 *    4) Calls Student Update API first (only if customer data changed)
 *    5) Calls Case Update API (only if case data changed)
 *    6) Shows one final success/error message
 *    7) Reloads page after successful update
 *
 * Notes:
 * - Uses full payload submission style for both Student and Case update APIs.
 * - If no fields changed, update request is skipped.
 *
 * Developer: Farhan Akhtar
 * Last Modified: 15-Jan-2026
 */


/* ================= UI HELPERS ================= */

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email);
}

function showUpdateSpinner() {
  $('#updateSpinner').show();
  $('#updateCaseBtn').prop('disabled', true);
}

function hideUpdateSpinner(enableBtn = true) {
  $('#updateSpinner').hide();
  $('#updateCaseBtn').prop('disabled', !enableBtn);
}

function showFinalSuccess() {
  alert('Case updated successfully.');
  location.reload();
}

// Function to auto-update case title
function updateCaseTitle() {
    var product = $('#product option:selected').text().trim();
    var enquiryType = $('#enquirytype option:selected').text().trim();

    // If product is disabled but has a value, allow it
    if ($('#product').val() !== '0' && $('#enquirytype').val() !== '0') {
        $('#case_title').val(product + " - " + enquiryType);
    } else {
        $('#case_title').val('');
    }
}

// Only enquirytype change is enough if product is disabled
$('#enquirytype').on('change', updateCaseTitle);

/* ================= ORIGINAL SNAPSHOTS ================= */

let originalCustomer = {};
let originalIncident = {};

$(document).ready(function () {

   updateCaseTitle();

  $('#phone').on('input', function () {
    this.value = this.value.replace(/\D/g, '');
  });

  $('#email').on('keyup', function () {
    const email = $(this).val().trim();

    if (!email || !email.includes('@')) {
      $(this).removeClass('input-error');
      $('#emailError').hide();
      return;
    }

    if (!isValidEmail(email)) {
      $(this).addClass('input-error');
      $('#emailError').show();
    } else {
      $(this).removeClass('input-error');
      $('#emailError').hide();
    }
  });

  originalCustomer = {
    phone: $('#phone').val(),
    email: $('#email').val(),
    priority: $('input[name="priority"]:checked').val()
  };

  originalIncident = {
    requesttype: $('#requesttype').val(),
    department: $('#department').val(),
    enquirytype: $('#enquirytype').val(),
    case_title: $('#case_title').val(),
    description: $('#v_remark_type').val()
  };

     $.post("helpdesk/get_student_activity.php", {
      email: $('#email').val(),
      phone: $('#phone').val(),
      nationalid: $('#nationalid').val(),
      loaneeno: $('#loaneeno').val()
   }, function (res) {

      if (!res.success) {
         $("#activityContainer")
            .html("<div class='alert alert-danger'>" + res.message + "</div>");
         return;
      }

      if (res.data.length === 0) {
         $("#activityContainer")
            .html("<div class='alert alert-warning'>No interactions found.</div>");
         return;
      }

      let html = `
      <div class="table-responsive">
         <table class="tableview tableview-2">
            <thead class="background">
               <tr>
                  <td>S.No.</td>
                  <td>Activity Type</td>
                  <td>Subject</td>
                  <td>Priority</td>
                  <td>Status</td>
                  <td>Created On</td>
               </tr>
            </thead>
            <tbody>
      `;

      res.data.forEach((row, i) => {

         let createdOn = row.createdOn
            ? new Date(row.createdOn).toLocaleString()
            : '';

         let desc = row.description || 'No details available';

         html += `
            <tr>
               <td>${i + 1}</td>
               <td>${row.activityType || 'N/A'}</td>
               <td>
                 <a href="javascript:void(0);" onclick="toggleDescription('desc${i}')">
                    ${row.subject || 'N/A'}
                 </a>
                 <div id="desc${i}" style="display:none" class="activity-description mt-2 p-2 border rounded bg-light small">
                    <b>Description:</b><br>${desc}
                 </div>
               </td>
               <td>${row.priority || 'N/A'}</td>
               <td>${row.status || 'N/A'}</td>
               <td>${createdOn}</td>
            </tr>
         `;
      });

      html += `</tbody></table></div>`;

      $("#activityContainer").html(html);

   }, "json");
});

/* ================= UPDATE BUTTON ================= */

$('#updateCaseBtn').on('click', function () {

  showUpdateSpinner();

  const phoneVal        = $('#phone').val().trim();
  const emailVal        = $('#email').val().trim();
  const caseTitleVal    = $('#case_title').val().trim();
  const descriptionVal  = $('#v_remark_type').val();
  const priorityCode    = $('input[name="priority"]:checked').val();
  const actionType      = $('#actionType').val(); // resolve | reopen | ""

  /* -------------------------
     BASIC VALIDATION
  ------------------------- */

  if ($('#email').hasClass('input-error')) {
    hideUpdateSpinner(true);
    alert('Please enter a valid email address.');
    return;
  }

  if (!phoneVal) {
    hideUpdateSpinner(true);
    alert('Phone number is required.');
    return;
  }

  if (
    $('#requesttype').val() === '0' ||
    $('#department').val() === '0' ||
    $('#enquirytype').val() === '0' ||
    !caseTitleVal
  ) {
    hideUpdateSpinner(true);
    alert('Please complete all required case fields.');
    return;
  }

  /* -------------------------
     CHANGE DETECTION
  ------------------------- */

  const customerChanged =
    phoneVal !== originalCustomer.phone ||
    emailVal !== originalCustomer.email;

  const incidentChanged =
    $('#requesttype').val() !== originalIncident.requesttype ||
    $('#department').val()  !== originalIncident.department ||
    $('#enquirytype').val() !== originalIncident.enquirytype ||
    caseTitleVal            !== originalIncident.case_title ||
    descriptionVal          !== originalIncident.description ||
    priorityCode            !== originalCustomer.priority;

  const statusChanged = actionType && actionType !== '';

  if (!customerChanged && !incidentChanged && !statusChanged) {
    hideUpdateSpinner(true);
    alert('No changes to update.');
    return;
  }

  /* -------------------------
     CONFIRM STATUS CHANGE
  ------------------------- */

  if (statusChanged) {
    const confirmMsg =
      actionType === 'resolve'
        ? 'Are you sure you want to resolve this case?'
        : 'Are you sure you want to reopen this case?';

    if (!confirm(confirmMsg)) {
      hideUpdateSpinner(true);
      return;
    }
  }

  /* -------------------------
     BUILD PAYLOADS
  ------------------------- */

  const studentPayload = {
    action: 'update_student_info',
    accountNumber: $('#accountNumber').val(),
    name: $('#name').val(),
    idNumber: $('#idNumber').val(),
    mobileNumber: phoneVal,
    email: emailVal
  };

  const casePayload = {
    action: 'update_case_info',
    ticketNumber: $('#ticketNumber').val(),
    actionType: actionType, 
    name: $('#name').val(),   
    vcasetype : $('#vcasetype').val(),           
    requesttype: $('#requesttype').val(),
    department: $('#department').val(),
    enquirytype: $('#enquirytype').val(),
    source: $('#source').val(),
    case_title: caseTitleVal,
    description: descriptionVal,
    priority: priorityCode,
    email: emailVal
  };

  /* -------------------------
     EXECUTE FLOW
  ------------------------- */

  executeUpdateFlow(
    studentPayload,
    casePayload,
    customerChanged
  );
});


/* ================= UPDATE FLOW ================= */

function executeUpdateFlow(studentPayload, casePayload, customerChanged) {

  if (customerChanged) {

    $.post('helpdesk/HelbServices.php', studentPayload, function (res) {

      if (!res || res.success !== true) {
        hideUpdateSpinner(true);
        alert(res && res.message ? res.message : 'Student update failed.');
        return;
      }

      updateCase(casePayload);

    }, 'json').fail(function () {
      hideUpdateSpinner(true);
      alert('Student update failed.');
    });

  } else {
    updateCase(casePayload);
  }
}


/* ================= CASE UPDATE ================= */

function updateCase(casePayload) {

  $.post('helpdesk/HelbServices.php', casePayload, function (res) {

    if (!res || res.success !== true) {
      hideUpdateSpinner(true);
      alert(res && res.message ? res.message : 'Case update failed.');
      return;
    }

    showFinalSuccess();

  }, 'json').fail(function () {
    hideUpdateSpinner(true);
    alert('Case update failed.');
  });
}


/* ================= ACTION DROPDOWN ================= */

$('#action_status').on('change', function () {
  $('#actionType').val($(this).val());
});


function toggleDescription(id) {

   // Close other open descriptions (optional but cleaner UX)
   $(".activity-description").not("#" + id).slideUp(150);

   // Toggle selected one
   $("#" + id).slideToggle(150);
}