/**
 * ============================================================
 * File Name   : popUp.js  (or your actual file name)
 * Module      : HELB Helpdesk - Student Search & Ticket Creation
 * ============================================================
 *
 * Summary:
 * This script handles the frontend operations for the HELB Helpdesk portal:
 * - Student search using multiple identifiers (Loan No / Phone / Email / National ID)
 * - Populating student details into the ticket creation form
 * - Creating cases/tickets via AJAX (HelbServices.php)
 * - Loading Student Interactions and Case History inside Bootstrap accordions
 * - Auto-updating case title based on Product + Enquiry Type
 * - Loading dependent dropdowns (Department + Enquiry Type) dynamically
 * - Utility UI features: Loader overlay, expand/collapse descriptions, show more/less sections
 *
 * Key Features:
 * - Prevents unnecessary repeated API calls using cached load flags:
 *   interactionLoaded, caseHistoryLoaded
 * - Validates mandatory form fields before submitting create-ticket request
 * - Shows loader overlay during API requests
 * - Handles success/error feedback messages properly on ticket creation
 *
 * Backend Endpoints Used:
 * - helpdesk/HelbServices.php
 *     action: search_student
 *     action: create_ticket
 *     action: get_interactions
 *     action: get_case_history
 *
 * - helpdesk/web_ticket_function.php
 *     action: getdepartment
 *     action: getenquiry
 *
 * Author        : Farhan Akhtar
 * Last Modified : 16-Mar-2026
 * ============================================================
 */

$(document).ready(function () {

    let interactionLoaded = false;
    let caseHistoryLoaded = false;

    // hard reset on load
    $("#visitorNameBlock").hide();
    $("#loaneeSearchBlock").hide();

    // Hide search block initially
    $("#loaneeSearchBlock").hide();

    // Disable search initially
    $("#student_search").prop("disabled", true);
    $("#searchType").prop("disabled", true);

    $("#visitorType").on("change", function () {

        const type = $(this).val();

        interactionLoaded = false;
        caseHistoryLoaded = false;

        if (type === "") {
            $("#visitorNameBlock").hide();
            $("#loaneeSearchBlock").hide();
            $("#accordionExample").hide();
            return;
        }

        $("#visitorNameBlock").show();

        if (type === "loanee") {

            // SHOW SEARCH BLOCK
            $("#loaneeSearchBlock").show();
            $("#accordionExample").show();

            $("#student_search").prop("disabled", false);
            $("#searchType").prop("disabled", false);

            // CLEAR + LOCK FIELDS
            $("#loaneeno,#nationalid,#first_name,#last_name,#email").prop("readonly", true);

        } else {

            // NON-LOANEE / EMPLOYER

            $("#loaneeSearchBlock").hide();
            $("#accordionExample").hide();

            $("#student_search").prop("disabled", true);
            $("#searchType").prop("disabled", true);

            // MAKE FIELDS EDITABLE
            $("#email,#phone,#loaneeno,#nationalid").prop("readonly", false);

            // SET DEFAULT VALUES
            // $("#nationalid").val("00000000");
            // $("#loaneeno").val("00000000");
            // $("#phone").val("00000000");
            // $("#email").val("");

            // DEFAULT NAME
            $("#first_name").val("Non");
            $("#last_name").val("Loanee");

            // NAME SHOULD REMAIN LOCKED
            $("#first_name,#last_name").prop("readonly", true);
        }
    });

    // Hide error when visitor type changes
    $("#visitorType").on("change", function () {
        $("#visitorTypeError").hide();
    });

    // Hide error while typing visitor name
    $("#visitorName").on("input", function () {
        if ($(this).val().trim() !== "") {
            $("#visitorNameError").hide();
        }
    });

    // When accordion is about to expand
    $('#collapseInteraction').on('show.bs.collapse', function (e) {

        if (interactionLoaded) return;  // stop extra calls
        interactionLoaded = true;

        var loaneeno = $("#loaneeno").val();
        var phone = $("#phone").val();
        var email = $("#email").val();
        var nationalid = $("#nationalid").val();

        // Validate before expansion
        if (!loaneeno && !phone && !email && !nationalid) {
            alert("Please enter at least one student identifier (Loan No, Phone, Email, or National ID).");

            // Stop accordion from expanding
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        // Proceed with AJAX only when expanding
        $.ajax({
            url: 'helpdesk/HelbServices.php',
            type: 'POST',
            data: {
                action: 'get_interactions',
                loaneeno: loaneeno,
                phone: phone,
                email: email,
                nationalid: nationalid
            },
            beforeSend: function () {
                showLoader();
                $("#interaction_result").html("<div class='text-center text-muted py-3'>Loading student activity...</div>");
            },
            success: function (data) {
                $("#interaction_result").html(data).show();
            },
            error: function (xhr, desc, err) {
                $("#interaction_result").html("<div class='alert alert-danger'>Error fetching interactions!</div>");
                console.error("Error: " + desc + "\n" + err);
            },
            complete: function () {
                hideLoader();
            }
        });
    });

    // Handle Case History accordion expansion
    $('#collapseCaseHistory').on('show.bs.collapse', function (e) {

        if (caseHistoryLoaded) return;
        caseHistoryLoaded = true;

        var loaneeno = $("#loaneeno").val();

        if (!loaneeno) {
            alert("Please enter Loan Number to view Call History.");
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        $.ajax({
            url: 'helpdesk/HelbServices.php',
            type: 'POST',
            data: {
                action: 'get_case_history',
                loaneeno: loaneeno
            },
            beforeSend: function () {
                showLoader();
                $("#case_result").html("<div class='text-center text-muted py-3'>Loading call history...</div>");
            },
            success: function (data) {
                $("#case_result").html(data).show();
            },
            error: function (xhr, desc, err) {
                $("#case_result").html("<div class='alert alert-danger'>Error fetching call history!</div>");
                console.error("Error: " + desc + "\n" + err);
            },
            complete: function () {
                hideLoader();
            }
        });
    });


});

// form submit ajax call create ticket
$("#customer_form").on('submit', function (e) {

    e.preventDefault();

    console.log('validate_form_submit-updated');

    var visitorType = $("#visitorType").val();

    // ===============================
    // Visitor Type Validation
    // ===============================
    if (visitorType.toLowerCase() === "loanee") {
        $("#visitorTypeError").hide();
    } else if (visitorType === "") {
        $("#visitorTypeError").show();
        $("#visitorType").focus();
        return false;
    } else {
        $("#visitorTypeError").hide();
    }

    // ===============================
    // Visitor Name (Required for Non-Loanee & Employer)
    // ===============================
    // if (visitorType !== "loanee") {


    // }

    // ===================================================
    // LOANEE VALIDATION
    // ===================================================
    // if (visitorType === "loanee") {

        var loaneeno = $('#loaneeno').val().trim();
        var nationalid = $('#nationalid').val().trim();
        var firstname = $('#first_name').val().trim();
        var lastname = $('#last_name').val().trim();
        var phone = $('#phone').val().trim();
        var email = $('#email').val().trim();

        if (loaneeno === "") {
            alert("Please Search and Select a Loanee!");
            $('#student_search').focus();
            return false;
        }

        if (nationalid === "") {
            alert("National ID missing!");
            return false;
        }

        if (firstname === "") {
            alert("First Name missing!");
            return false;
        }

        if (lastname === "") {
            alert("Last Name missing!");
            return false;
        }

        if (phone === "") {
            alert("Phone Number missing!");
            return false;
        }

        // Email validation only if entered
        if (email !== "") {
            var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailPattern.test(email)) {
                alert("Please enter a valid Email ID!");
                $('#email').focus();
                return false;
            }
        }
    // }

    // ===================================================
    // NON-LOANEE / EMPLOYER VALIDATION
    // ===================================================
    // else {

    //     var loaneeno = $('#loaneeno').val().trim();
    //     var nationalid = $('#nationalid').val().trim();
    //     var phone = $('#phone').val().trim();

    //     if (loaneeno !== "00000000" ||
    //         nationalid !== "00000000" ||
    //         phone !== "00000000") {

    //         alert("System error: Visitor identifiers modified. Please reselect Visitor Type.");
    //         return false;
    //     }
    // }

    // ===================================================
    // COMMON CASE VALIDATIONS
    // ===================================================

    var product = $('#product').val();
    if (product.trim() == 0) {
        alert("Please Select Product!");
        $('#product').focus();
        return false;
    }

    var requesttype = $('#requesttype').val();
    if (requesttype.trim() == 0) {
        alert("Please Select Request Type!");
        $('#requesttype').focus();
        return false;
    }

    var department = $('#department').val();
    if (department.trim() == 0) {
        alert("Please Select Department!");
        $('#department').focus();
        return false;
    }

    var enquirytype = $('#enquirytype').val();
    if (enquirytype.trim() == 0) {
        alert("Please Select Enquiry Type!");
        $('#enquirytype').focus();
        return false;
    }

    var type = $('#type').val();
    if (type.trim() == 0) {
        alert("Please Select Service Category!");
        $('#type').focus();
        return false;
    }

    var vCaseType = $('#vCaseType').val();
    if (vCaseType.trim() == 0) {
        alert("Please Select FCR / Non FCR!");
        $('#vCaseType').focus();
        return false;
    }

    var case_title = $('#case_title').val().trim();
    if (case_title === "") {
        alert("Please Enter Case Title!");
        $('#case_title').focus();
        return false;
    }

    var description = $('#description').val().trim();
    if (description === "") {
        alert("Please Enter Description!");
        $('#description').focus();
        return false;
    }

    // ===================================================
    // AJAX CALL
    // ===================================================

    $("#customer_form :input").prop('disabled', false);

    $("#create_ticket").prop('disabled', true);
    $("#create_ticket").val('Please Wait...');

    $.ajax({
        url: "helpdesk/HelbServices.php",
        type: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,

        success: function (response) {

            try {
                var data = JSON.parse(response);

                if (data.success) {

                    $("#docket_no_new").val(data.ticket_no);

                    $('.successmanual')
                        .text('CASE ID :: ' + data.ticket_no)
                        .show();

                    $('.errormanual').hide();

                    $("#create_ticket")
                        .prop('disabled', true)
                        .val('Case Created');

                    // setTimeout(function () {
                    //     const token = btoa('web_helpdesk');
                    //     window.location.href = "helpdesk_index.php?token=" + token;
                    // }, 4000);

                } else {

                    $('.errormanual')
                        .text(data.message)
                        .show();

                    $('.successmanual').hide();

                    $("#create_ticket")
                        .prop('disabled', false)
                        .val('Create Ticket');
                }

                $("html, body").animate({
                    scrollTop: 0
                }, "slow");

            } catch (e) {
                console.error("Invalid JSON response:", response);
                $("#create_ticket")
                    .prop('disabled', false)
                    .val('Create Ticket');
            }
        },

        error: function (xhr, status, error) {
            console.error("AJAX Error:", error);
            $("#create_ticket")
                .prop('disabled', false)
                .val('Create Ticket');
        }
    });

});

function toggleDescription(id) {
    var el = document.getElementById(id);
    el.style.display = (el.style.display === "none" || el.style.display === "") ? "block" : "none";
}

function search_student(val) {

    var visitorType = $("#visitorType").val();
    if (visitorType === "") {
        alert("Please select Type of Visitor first!");
        return;
    }

    if (val.length >= 3) {
        var type = $("#searchType").val(); // get dropdown value

        // Show animated spinner
        $("#search_result").css("display", "block").html(`
            <div style="text-align:center; padding:10px;">
                <div class="spinner"></div>
            </div>
        `);

        $.ajax({
            url: 'helpdesk/HelbServices.php',
            type: 'POST',
            data: {
                'key': val,
                'searchType': type,
                'action': 'search_student'
            },
            success: function (data) {
                $("#search_result").css("display", "block").html(data);
            },
            error: function (xhr, desc, err) {
                $("#search_result").css("display", "block").html("<div style='color:red;'>Error fetching records!</div>");
                console.error("Error: " + desc + "\n" + err);
            }
        });
    } else {
        $("#search_result").hide();
    }
}

// Loader helper functions
function showLoader() {
    document.getElementById('loader-overlay').classList.add('show');
}

function hideLoader() {
    document.getElementById('loader-overlay').classList.remove('show');
}

// Populate form + fetch interactions when row clicked
function showStudentDetails(student) {
    var student_array = student.split("||");

    var fullName = student_array[0].trim();
    var nameParts = fullName.split(" ");

    var firstName = nameParts[0] || "";
    var lastName = nameParts.slice(1).join(" ") || "";

    $("#first_name").val(firstName);
    $("#last_name").val(lastName);

    var loaneeno = student_array[1];
    var phone = student_array[2];
    var email = student_array[3];
    var nationalid = student_array[4];

    $("#loaneeno").val(loaneeno);
    $("#phone").val(phone);
    $("#email").val(email);
    $("#nationalid").val(nationalid);

    $("#search_result").hide();

    // $.ajax({
    //     url: 'helpdesk/HelbServices.php',
    //     type: 'POST',
    //     data: {
    //         action: 'get_interactions',
    //         loaneeno: loaneeno,
    //         phone: phone,
    //         email: email,
    //         nationalid: nationalid
    //     },
    //     beforeSend: function() {
    //         showLoader(); // show loader before request
    //     },
    //     success: function(data) {
    //         $("#interaction_result").html(data).show();
    //     },
    //     error: function(xhr, desc, err) {
    //         $("#interaction_result").html("<div class='alert alert-danger'>Error fetching interactions!</div>");
    //         console.error("Error: " + desc + "\n" + err);
    //     },
    //     complete: function() {
    //         hideLoader(); // hide loader after request completes
    //     }
    // });
}


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

    if ($('#product').val() !== '0' && $('#enquirytype').val() !== '0') {
        if (product !== "" && enquiryType !== "") {
            $('#case_title').val(product + " - " + enquiryType);
        } else {
            $('#case_title').val('');
        }
    } else {
        $('#case_title').val('');
    }
}

// Bind change event for dropdowns
$('#product, #enquirytype').on('change', updateCaseTitle);


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);
        }
    });
}

function updatePlaceholder() {
    var type = document.getElementById("searchType").value;
    var input = document.getElementById("student_search");

    if (type === "email") {
        input.placeholder = "Search Student by Email ID";
    } else if (type === "loanee") {
        input.placeholder = "Search Student by Loanee Number";
    } else if (type === "phone") {
        input.placeholder = "Search Student by Phone Number";
    } else if (type === "national") {
        input.placeholder = "Search Student by National ID";
    }
}

// On dropdown change
$("#searchType").on("change", function () {
    var placeholderText = $(this).find("option:selected").text();
    $("#student_search").val(""); // Clear search input
    $("#student_search").attr("placeholder", "Search by " + placeholderText); // Update placeholder
    $("#search_result").hide(); // Hide previous results
});


document.addEventListener("DOMContentLoaded", function () {
    console.log("DOM fully loaded and parsed");

    const phoneInput = document.getElementById("phone");
    const whatsappInput = document.getElementById("whatsapp_number");
    const smsHandleInput = document.getElementById("smshandle");

    if (phoneInput && whatsappInput && smsHandleInput) {
        console.log("All input elements found");

        phoneInput.addEventListener("input", function () {
            let phoneNumber = this.value;
            console.log("Phone input changed:", phoneNumber);

            whatsappInput.value = phoneNumber;
            console.log("Updated WhatsApp number to:", whatsappInput.value);

            smsHandleInput.value = phoneNumber;
            console.log("Updated SMS handle to:", smsHandleInput.value);
        });
    } else {
        console.warn("One or more input elements not found in the DOM");
    }
});

$(document).on('click', '.toggle', function (event) {
    event.preventDefault();

    var target = $(this).data('target');
    $('#' + target).toggleClass('hide');
});


const chatHistory = document.getElementById('chatHistory');
const showMoreBtn = document.getElementById('showMoreBtn');

showMoreBtn.addEventListener('click', function () {
    // Toggle the 'hidden' class to reveal more content
    if (chatHistory.style.maxHeight === 'none') {
        chatHistory.style.maxHeight = '200px';
        showMoreBtn.innerHTML = 'Show More<span class="dots">...</span>';
    } else {
        chatHistory.style.maxHeight = 'none'; // Expand to full height
        showMoreBtn.innerHTML = 'Show Less<span class="dots">...</span>';
    }
});

