/**
 * QA FORM SCRIPT (Email QA / Social QA / Calls QA)
 * ----------------------------------------------------
 * Features:
 * Calculates score live
 * YES/NO exclusive selection per question
 * Submits QA form to DB (quality_score table)
 * Supports 3 types:
 *    - emailqa
 *    - socialmedia
 *    - callinbound
 *
 * Developer     : Farhan Akhtar
 * Last Modified : 14-01-2026
 */

/**
 * SCORE CALCULATIONS (GLOBAL)
 */

// Email QA
function updateEmailScore() {
    let totalScore = 0;
    let yesCount = 0;
    let noCount = 0;

    const weights = {
        'email_q1': 5, 'email_q2': 5, 'email_q3': 5,
        'email_q4': 3, 'email_q5': 5, 'email_q6': 7, 'email_q7': 5,
        'email_q8': 10, 'email_q9': 12, 'email_q10': 8,
        'email_q11': 3, 'email_q12': 5, 'email_q13': 4, 'email_q14': 3,
        'email_q15': 2, 'email_q16': 3, 'email_q17': 3, 'email_q18': 2
    };

    for (let i = 1; i <= 18; i++) {
        const baseName = `email_q${i}`;
        const isYes = $(`input[name="${baseName}"]:checked`).length > 0;
        const isNo  = $(`input[name="${baseName}_no"]:checked`).length > 0;

        if (isYes) {
            totalScore += weights[baseName];
            yesCount++;
        }
        if (isNo) noCount++;
    }

    $('#emailTotalScore').text(totalScore);
    $('#emailYesCount').text(`${yesCount}/18`);
    $('#emailNoCount').text(`${noCount}/18`);
}

// Social QA
function updateSocialScore() {
    let totalScore = 0;
    let yesCount = 0;
    let noCount = 0;

    const weights = {
        'social_q1': 15, 'social_q2': 20, 'social_q3': 15,
        'social_q4': 20, 'social_q5': 10, 'social_q6': 10, 'social_q7': 10
    };

    for (let i = 1; i <= 7; i++) {
        const baseName = `social_q${i}`;
        const isYes = $(`input[name="${baseName}"]:checked`).length > 0;
        const isNo  = $(`input[name="${baseName}_no"]:checked`).length > 0;

        if (isYes) {
            totalScore += weights[baseName];
            yesCount++;
        }
        if (isNo) noCount++;
    }

    $('#socialTotalScore').text(totalScore);
    $('#socialYesCount').text(`${yesCount}/7`);
    $('#socialNoCount').text(`${noCount}/7`);
}

// Calls QA
function updateCallsScore() {
    let totalScore = 0;
    let yesCount = 0;
    let noCount = 0;

    const weights = {
        'calls_q1': 5, 'calls_q2': 15, 'calls_q3': 5,
        'calls_q4': 15, 'calls_q5': 15, 'calls_q6': 20, 'calls_q7': 15, 'calls_q8': 10
    };

    for (let i = 1; i <= 8; i++) {
        const baseName = `calls_q${i}`;
        const isYes = $(`input[name="${baseName}"]:checked`).length > 0;
        const isNo  = $(`input[name="${baseName}_no"]:checked`).length > 0;

        if (isYes) {
            totalScore += weights[baseName];
            yesCount++;
        }
        if (isNo) noCount++;
    }

    $('#callsTotalScore').text(totalScore);
    $('#callsYesCount').text(`${yesCount}/8`);
    $('#callsNoCount').text(`${noCount}/8`);
}

/**
 * Load saved QA scoring preview using interaction_id + qa_form_type
 * ---------------------------------------------------------------
 * It will tick Yes/No checkboxes and update score counts.
 */
function loadSavedQaPreview(qa_form_type) {

    const interactionId = window.currentInteractionId || "";
    if (!interactionId) return;

    $.ajax({
        url: "omnichannel_config/get_quality_score.php",
        type: "POST",
        dataType: "json",
        data: {
            interaction_id: interactionId,
            qa_form_type: qa_form_type
        },
        success: function (res) {

            if (!res.status || !res.found) {
                // nothing to preview
                return;
            }

            const saved = res.data;

            // apply checkbox values based on form type
            if (qa_form_type === "email") {
                applySavedChecklist("email", 18, saved);
                updateEmailScore();
                $("#emailScorecardId").text(saved.scorecard_id || "");
                $("#emailScorecardBox").show();
                $("#emailRemark").val(saved.remark || "");
                $("#emailForm input[type='checkbox'], #emailRemark, #submitEmailBtn").prop("disabled", true);
            }

            if (qa_form_type === "socialmedia") {
                applySavedChecklist("social", 7, saved);
                updateSocialScore();
                $("#socialScorecardId").text(saved.scorecard_id || "");
                $("#socialScorecardBox").show();
                $("#socialRemark").val(saved.remark || "");
                $("#socialForm input[type='checkbox'], #socialRemark, #submitSocialBtn").prop("disabled", true);
            }

            if (qa_form_type === "inboundcall") {
                applySavedChecklist("calls", 8, saved);
                updateCallsScore();
                $("#callsScorecardId").text(saved.scorecard_id || "");
                $("#callsScorecardBox").show();
                $("#callsRemark").val(saved.remark || "");
                $("#callsForm input[type='checkbox'], #callsRemark, #submitCallsBtn").prop("disabled", true);
            }


            setTimeout(() => {
                if (qa_form_type === "email") updateEmailScore();
                if (qa_form_type === "socialmedia") updateSocialScore();
                if (qa_form_type === "inboundcall") updateCallsScore();
            }, 50);


            // Optional message
            console.log("Loaded saved QA:", saved.scorecard_id);
        }
    });
}

/**
 * Apply saved checklist f-values to checkboxes
 * -------------------------------------------
 * value rule:
 * 1 => Yes checkbox checked
 * 0 => No checkbox checked
 * NULL => no selection
 */
function applySavedChecklist(prefix, totalQuestions, savedData) {

    for (let i = 1; i <= totalQuestions; i++) {

        const fieldKey = "f" + i;
        const value = savedData[fieldKey];

        const yesName = `${prefix}_q${i}`;
        const noName  = `${prefix}_q${i}_no`;

        // reset first
        $(`input[name="${yesName}"]`).prop("checked", false);
        $(`input[name="${noName}"]`).prop("checked", false);

        if (value === "1" || value === 1) {
            $(`input[name="${yesName}"]`).prop("checked", true);
        }

        if (value === "0" || value === 0) {
            $(`input[name="${noName}"]`).prop("checked", true);
        }
    }
}

$(document).ready(function () {

    /* =========================================
       Bootstrap Modals
    ========================================= */
    const emailQAModal  = new bootstrap.Modal(document.getElementById('emailQAModal'));
    const socialQAModal = new bootstrap.Modal(document.getElementById('socialQAModal'));
    const callsQAModal  = new bootstrap.Modal(document.getElementById('callsQAModal'));

    /* =========================================
       Helpers
    ========================================= */
    function generateScorecardId(prefix = "QA") {
        return prefix + "-" + Date.now();
    }

    // YES => 1, NO => 0, not selected => ''
    function getYesNoValue(yesSelector, noSelector) {
        if ($(yesSelector).is(":checked")) return 1;
        if ($(noSelector).is(":checked")) return 0;
        return "";
    }

    // Build f1-f30 mapping automatically
    function buildChecklistPayload(prefix, totalQuestions) {
        const payload = {};

        // default blank
        for (let i = 1; i <= 30; i++) payload["f" + i] = "";

        // fill based on questions
        for (let i = 1; i <= totalQuestions; i++) {
            const yesName = `${prefix}_q${i}`;
            const noName = `${prefix}_q${i}_no`;

            payload["f" + i] = getYesNoValue(
                `input[name="${yesName}"]`,
                `input[name="${noName}"]`
            );
        }

        return payload;
    }

    /**
     * Disable submit button to prevent duplicate inserts
     */
    function lockSubmitButton(btnId, isLock = true) {
        const $btn = $("#" + btnId);
        if (isLock) {
            $btn.prop("disabled", true);
            $btn.text("Submitting...");
        } else {
            $btn.prop("disabled", false);
            $btn.text($btn.data("original-text"));
        }
    }

    /**
     * Generate unique request token (for duplicate protection)
     */
    function generateRequestToken() {
        return "REQ-" + Date.now() + "-" + Math.floor(Math.random() * 999999);
    }

    function getRemarkValue(modalType) {
    if (modalType === "email") return ($("#emailRemark").val() || "").trim();
    if (modalType === "socialmedia") return ($("#socialRemark").val() || "").trim();
    if (modalType === "inboundcall") return ($("#callsRemark").val() || "").trim();
    return "";
    }

    function getSummary(modalType) {
        if (modalType === "email") {
            return {
                score: parseFloat($("#emailTotalScore").text()) || 0,
                yes: $("#emailYesCount").text(),
                no: $("#emailNoCount").text()
            };
        }

        if (modalType === "socialmedia") {
            return {
                score: parseFloat($("#socialTotalScore").text()) || 0,
                yes: $("#socialYesCount").text(),
                no: $("#socialNoCount").text()
            };
        }

        if (modalType === "inboundcall") {
            return {
                score: parseFloat($("#callsTotalScore").text()) || 0,
                yes: $("#callsYesCount").text(),
                no: $("#callsNoCount").text()
            };
        }

        return { score: 0, yes: "0/0", no: "0/0" };
    }

    function saveQaEvaluation(options) {

        const {
            qa_form_type,
            overall_score,
            prefix,
            totalQuestions,
            remark,
            onDone
        } = options;

        const checklistPayload = buildChecklistPayload(prefix, totalQuestions);

        const payload = {
            scorecard_id: generateScorecardId(qa_form_type.toUpperCase()),
            request_token: generateRequestToken(), // IMPORTANT
            qa_form_type: qa_form_type,
            overall_score: overall_score,
            interaction_id: window.currentInteractionId || "",
            interaction_at: window.currentInteractionAt || "",
            agentid: window.currentAgentId || "",
            remark: remark,


            // optional
            company_id: "",
            wow_call: "",
            qa_result: "",

            ...checklistPayload
        };

        $.ajax({
            url: "omnichannel_config/save_quality_score.php",
            type: "POST",
            data: payload,
            dataType: "json",
            success: function (data) {

                if (data.status) {
                    alert("✅ " + data.msg);
                     $('#emailQAModal').modal('hide');
                     $('#socialQAModal').modal('hide');
                     // document.getElementById('emailQAModal').hide();
                    //  var modal = new bootstrap.Modal(document.getElementById('socialQAModal'));
                    // modal.hide();
                    return;
                }

                // Already scored
                if (data.already_scored) {
                    alert("⚠️ Already scored with Scorecard ID: " + data.scorecard_id);
                    return;
                }

                alert("❌ " + (data.msg || "Failed to save QA"));
                
            },
            error: function (xhr) {
                alert("❌ Server error");
                console.log(xhr.responseText);
            },
            complete: function () {
                if (typeof onDone === "function") onDone();
            }
        });
    }

    function validateAllQuestions(prefix, totalQuestions, formSelector) {

        let missing = [];

        // remove old highlights
        $(formSelector + " .criterion-row").removeClass("qa-missing");

        for (let i = 1; i <= totalQuestions; i++) {

            const yesName = `${prefix}_q${i}`;
            const noName  = `${prefix}_q${i}_no`;

            const yesChecked = $(`${formSelector} input[name="${yesName}"]`).is(":checked");
            const noChecked  = $(`${formSelector} input[name="${noName}"]`).is(":checked");

            if (!yesChecked && !noChecked) {
                missing.push(i);

                // highlight exact question row
                $(`${formSelector} input[name="${yesName}"], ${formSelector} input[name="${noName}"]`)
                    .closest(".criterion-row")
                    .addClass("qa-missing");
            }
        }

        if (missing.length > 0) {
            alert("⚠️ Please answer all questions (YES/NO mandatory).\nMissing Question(s): " + missing.join(", "));

            // scroll to first missing question row
            const firstQ = missing[0];
            const firstInput = $(`${formSelector} input[name="${prefix}_q${firstQ}"]`);

            if (firstInput.length) {
                firstInput.closest(".criterion-row")[0].scrollIntoView({
                    behavior: "smooth",
                    block: "center"
                });
            }

            return false;
        }

        return true;
    }



    /* =========================================
    YES/NO Exclusive Checkbox Behavior
    ========================================= */

    // EMAIL
    $(document).on("change", "#emailForm input[type='checkbox']", function () {
        const name = $(this).attr("name");

        // base question name: email_q1
        const base = name.replace("_no", "");

        // if clicked yes => uncheck no
        if (name.indexOf("_no") === -1) {
            $(`input[name="${base}_no"]`).prop("checked", false);
        } else {
            // clicked no => uncheck yes
            $(`input[name="${base}"]`).prop("checked", false);
        }

        // remove error highlight once answered
        $(this).closest(".criterion-row").removeClass("qa-missing");

        updateEmailScore();
    });

    // SOCIAL
    $(document).on("change", "#socialForm input[type='checkbox']", function () {
        const name = $(this).attr("name");
        const base = name.replace("_no", "");

        if (name.indexOf("_no") === -1) {
            $(`input[name="${base}_no"]`).prop("checked", false);
        } else {
            $(`input[name="${base}"]`).prop("checked", false);
        }

        // remove error highlight once answered
        $(this).closest(".criterion-row").removeClass("qa-missing");

        updateSocialScore();
    });

    // CALLS
    $(document).on("change", "#callsForm input[type='checkbox']", function () {
        const name = $(this).attr("name");
        const base = name.replace("_no", "");

        if (name.indexOf("_no") === -1) {
            $(`input[name="${base}_no"]`).prop("checked", false);
        } else {
            $(`input[name="${base}"]`).prop("checked", false);
        }
        
        // remove error highlight once answered
        $(this).closest(".criterion-row").removeClass("qa-missing");

        updateCallsScore();
    });


    /* =========================================
       SUBMIT HANDLERS (SAVE TO DB)
    ========================================= */

    $("#submitEmailBtn").on("click", function () {

        const btnId = "submitEmailBtn";
        if (!$("#" + btnId).data("original-text")) {
            $("#" + btnId).data("original-text", $("#" + btnId).text());
        }

        if ($("#" + btnId).prop("disabled")) return;

        if (!validateAllQuestions("email", 18, "#emailForm")) return;


        //  Remark validation
        const remark = getRemarkValue("email");
        if (!remark) {
            alert("⚠️ Assessor's Notes is mandatory.");
            $("#emailRemark").focus();                 // focus
            $("#emailRemark")[0].scrollIntoView({      // optional smooth scroll
                behavior: "smooth",
                block: "center"
            });
            return;
        }

        // Confirmation Box Summary
        const summary = getSummary("email");
        const confirmMsg =
            "Please confirm before submitting:\n\n" +
            "YES Count: " + summary.yes + "\n" +
            "NO Count: " + summary.no + "\n" +
            "Total Score: " + summary.score + "/100\n\n" +
            "Do you want to submit this evaluation?";

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

        lockSubmitButton(btnId, true);

        saveQaEvaluation({
            qa_form_type: "email",
            overall_score: summary.score,
            prefix: "email",
            totalQuestions: 18,
            remark: remark,
            onDone: function () {
                lockSubmitButton(btnId, false);
            }
        });
    });


    $("#submitSocialBtn").on("click", function () {

        const btnId = "submitSocialBtn";
        if (!$("#" + btnId).data("original-text")) {
            $("#" + btnId).data("original-text", $("#" + btnId).text());
        }

        if ($("#" + btnId).prop("disabled")) return;
        if (!validateAllQuestions("social", 7, "#socialForm")) return;


        const remark = getRemarkValue("socialmedia");
        if (!remark) {
            alert("⚠️ Assessor's Notes is mandatory.");
            $("#socialRemark").focus();
            $("#socialRemark")[0].scrollIntoView({
                behavior: "smooth",
                block: "center"
            });
            return;
        }

        const summary = getSummary("socialmedia");
        const confirmMsg =
            "Please confirm before submitting:\n\n" +
            "YES Count: " + summary.yes + "\n" +
            "NO Count: " + summary.no + "\n" +
            "Total Score: " + summary.score + "/100\n\n" +
            "Do you want to submit this evaluation?";

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

        lockSubmitButton(btnId, true);

        saveQaEvaluation({
            qa_form_type: "socialmedia",
            overall_score: summary.score,
            prefix: "social",
            totalQuestions: 7,
            remark: remark,
            onDone: function () {
                lockSubmitButton(btnId, false);
            }
        });
    });


    $("#submitCallsBtn").on("click", function () {

        const btnId = "submitCallsBtn";
        if (!$("#" + btnId).data("original-text")) {
            $("#" + btnId).data("original-text", $("#" + btnId).text());
        }

        if ($("#" + btnId).prop("disabled")) return;
        if (!validateAllQuestions("calls", 8, "#callsForm")) return;


        const remark = getRemarkValue("inboundcall");
        if (!remark) {
            alert("⚠️ Assessor's Notes is mandatory.");
            $("#callsRemark").focus();
            $("#callsRemark")[0].scrollIntoView({
                behavior: "smooth",
                block: "center"
            });
            return;
        }

        const summary = getSummary("inboundcall");
        const confirmMsg =
            "Please confirm before submitting:\n\n" +
            "YES Count: " + summary.yes + "\n" +
            "NO Count: " + summary.no + "\n" +
            "Total Score: " + summary.score + "/100\n\n" +
            "Do you want to submit this evaluation?";

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

        lockSubmitButton(btnId, true);

        saveQaEvaluation({
            qa_form_type: "inboundcall",
            overall_score: summary.score,
            prefix: "calls",
            totalQuestions: 8,
            remark: remark,
            onDone: function () {
                lockSubmitButton(btnId, false);
            }
        });
    });



    /* =========================================
       INIT
    ========================================= */
    updateEmailScore();
    updateSocialScore();
    updateCallsScore();

    
});


/**
 * Open QA Modal & Load Interaction Preview + Recording
 * ------------------------------------------------------
 * Logic:
 * - modalType=email   => open Email QA modal
 * - modalType=calls   => open Calls QA modal (autoplay audio)
 * - modalType=social  => open Social QA modal
 *
 * Developer     : Farhan Akhtar
 * Last Modified : 14-01-2026
 */

$(document).on('click', '.openQaModal', function () {

    const modalType     = $(this).data('modal'); // email/social/calls
    const interactionId = $(this).data('interactionid');
    const viewUrl       = $(this).data('viewurl');
    const audioUrl      = $(this).data('audio');
    const ticketid     = $(this).data("ticketid") || "";
    const product     = $(this).data("product") || "";
    const requestType = $(this).data("requesttype") || "";

    function buildIframeUrl(url) {
        if (!url) return "";
        const glue = url.includes("?") ? "&" : "?";
        return url + glue +
            "ticketid=" + encodeURIComponent(ticketid) +
            "&product=" + encodeURIComponent(product) +
            "&request_type=" + encodeURIComponent(requestType);
    }

    // Reset all QA forms before loading preview

    // reset checkboxes
    $("#emailForm input[type='checkbox'], #socialForm input[type='checkbox'], #callsForm input[type='checkbox']")
        .prop("disabled", false)
        .prop("checked", false);

    // reset assessor notes (remark textarea)
    $("#emailForm textarea[name='remark'], #socialForm textarea[name='remark'], #callsForm textarea[name='remark']")
        .prop("disabled", false)
        .val("");

    // reset submit buttons
    $("#submitEmailBtn").prop("disabled", false).text("Submit");
    $("#submitSocialBtn").prop("disabled", false).text("Submit");
    $("#submitCallsBtn").prop("disabled", false).text("Submit");

    //  hide scorecard display by default
    $("#emailScorecardBox, #socialScorecardBox, #callsScorecardBox").hide();
    $("#emailScorecardId, #socialScorecardId, #callsScorecardId").text("");


    window.currentInteractionId = interactionId;
    window.currentAgentId       = $(this).data("agentid") || "";
    window.currentInteractionAt = $(this).data("interactionat") || "";

    // Reset audio
    $('#callAudioBox').hide();
    $('#callAudioSource').attr('src', '');

    const audioPlayer = document.getElementById('callAudioPlayer');
    if (audioPlayer) {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
        audioPlayer.load();
    }

    if (modalType === 'email') {

        $('#emailInteractionFrame').attr('src', buildIframeUrl(viewUrl));
        new bootstrap.Modal(document.getElementById('emailQAModal')).show();

        //  load saved scoring preview
        loadSavedQaPreview("email");

    } else if (modalType === 'calls') {

        $('#callsInteractionFrame').attr('src', buildIframeUrl(viewUrl));

        if (audioUrl && audioPlayer) {

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

            //  set audio URL directly
            audioPlayer.src = audioUrl;

            audioPlayer.load();

            setTimeout(() => {
                audioPlayer.play().catch(() => {});
            }, 200);

        } else {
            $('#callAudioBox').hide();
        }

        new bootstrap.Modal(document.getElementById('callsQAModal')).show();
        loadSavedQaPreview("inboundcall");
    } else {

        $('#socialInteractionFrame').attr('src', buildIframeUrl(viewUrl));
        new bootstrap.Modal(document.getElementById('socialQAModal')).show();

        //  load saved scoring preview
        loadSavedQaPreview("socialmedia");
    }
});

/**
 * Stop Call Audio (close button, footer close, ESC, backdrop click)
 */

function stopAudio() {
    const audioPlayer = document.getElementById("callAudioPlayer");
    if (!audioPlayer) return;

    audioPlayer.pause();
    audioPlayer.currentTime = 0;

    //  strongest stop
    audioPlayer.src = "";
    $("#callAudioSource").attr("src", "");
    audioPlayer.load();

    $("#callAudioBox").hide();
}

/* Close buttons (X and Close button) */
$(document).on("click", "#callsQAModal .btn-close, #callsQAModal [data-bs-dismiss='modal']", function () {
    stopAudio();
});

/* ESC + backdrop click */
$(document).on("keydown", function (e) {
    if (e.key === "Escape") stopAudio();
});

$(document).on("click", function (e) {
    if ($(e.target).hasClass("modal")) stopAudio();
});


