<script type='text/javascript'>
    var packagingapproved = false;
    var cuppingapproved = false;
    var weightapproved = false;

    function showRoastName()
    {
        console.log('showRoastName');
        v = document.getElementById('colour_analysis').value;
        f = $('#roastfromnumber').text();
        t = $('#roasttonumber').text();
        var cuppingvisible = $('.showhidecupping').is(':visible');
        console.log('from '+f+' to '+t+' actual '+v);
        if(v >= f && v <= t){
            $('.showhidecupping').hide();
            if(cuppingvisible){
                enableFinalQC();
            }
        }else{
            $('.showhidecupping').show();
            if(!cuppingvisible){
                enableFinalQC();
            }
        }
        $("#roast_colour_name").html('');
        <?php foreach($roastcolours as $roastcolour): ?>
            fromnumber = parseInt("<?= $roastcolour->FromNumber ?>");
            tonumber = parseInt("<?= $roastcolour->ToNumber ?>");
            roastcolourname = "<?= $roastcolour->RoastColourName ?>";
            if(v >= fromnumber && v < tonumber){
                $("#roast_colour_name").html(roastcolourname);
            }
        <?php endforeach; ?>
    }

    function getCertsForCoffee(id) {
        if(id === null   || (typeof id === 'undefined')){
            return false;
        }
        console.log('id is '+id);
        // id = green_coffee1
        var coffeename = document.getElementById(id).value;

        console.log('coffeename is '+coffeename);
        // id = green_coffee1
        var rownum = id.substring(12);
        //alert(rownum);
        let done = false;
        if (coffeename != '') {
            //alert(coffeename);

            let csrfField = document.getElementById('csrfcode');
            let htmxpath = "<?= base_url("production/getcertsforcoffee") ?>";
            let csrfname = csrfField.name;
            let csrfval = csrfField.value;
            let success = 0;
            let vals = {};
            vals['coffeename'] = coffeename;
            vals[csrfname] = csrfval;
            vals['rownum'] = rownum;
            htmx.ajax('POST',
                htmxpath, {
                    target: "#res",
                    swap: 'none',
                    handler: (_, response) => {
                        console.log(response.xhr.responseText);
                        // Returned from Ajax call
                        res = JSON.parse(response.xhr.response);
                        success = res.success;

                        newid = Number(rownum);
                        newid = newid + 1;
                        certid = '#cert-row' + newid;

                        // Update Hidden csrf token input with new value
                        $('#csrfcode').val(res.token);
                        if (success == 1) {
                            certcheckbox = res.certcheckbox;
                            console.log(certcheckbox);
                            $(certid).replaceWith(certcheckbox);
                            done = true;
                            return true;
                        } else {
                            DayPilot.Modal.alert("Something went wrong. I can't get the Certifications", {
                                theme: "modal_rounded"
                            });
                            done = false;
                            return false;
                        }
                    },
                    values: vals
                }
            );
        }
        return false;
    }

    function cancelqcapproval() {
        console.log('cancelqcapproval');
        var newtext =`<div id="finalqcid" style="display:grid; gap:0; grid-template-columns: 70% 20% 10%;">
                        <div style="grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;">
                            <a id="btnfinalqcapproval" class="button v-small" style="width:-webkit-fill-available; color:white;" href="#" onclick="finalqcapproval();">Click to Approve</a>
                        </div>
                    </div>`;

        $('#finalqcid').replaceWith(newtext);
        enableFinalQC();
    }

    function finalqcapproval() {
        DayPilot.Modal.confirm("Do you Approve the final quality check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =`<div id='finalqcid' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;'>
                            <input type='hidden' name='final_qc_approval' id='final_qc_approval'
                            value='<?= esc(auth()->user()->username) ?>' >
                            <input type='text' name='final_qc_approval_display' id='final_qc_approval_display'
                            class='grid-column:1; grid-cell' style='padding:0; margin:0;height:100%;border-style:solid; border-color:dimgray;text-align:center;'
                            value='<?= esc(auth()->user()->username) ?>' disabled>
                        </div>
                        <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                            <a id='cancelfinalqcapproval'
                            href='#'
                            onclick='cancelqcapproval();'
                            style='align-content:center; justify-self:center; text-align:center; width:100%; height:100%; border-style: solid; border-radius:5px; background-color:dimgrey; color:white; display:block;'
                            >x</a>
                        </div>
                    </div>`;
                $('#finalqcid').replaceWith(newtext);
                //$('#submit_btn').click();
            }
        });
    }

    function cancelpackagingapproval() {
        $('#packagingid').replaceWith("<div id='packagingid' style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'><a id='btnpackaging_qc_by' class='button v-small' style='width:-webkit-fill-available; color:white;' href='#' onclick='packagingapproval();'>Click to Approve</a></div>");
        packagingapproved = false;
        enableFinalQC();
    }

    function packagingapproval() {
        DayPilot.Modal.confirm("Do you Approve the Packaging quality check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =
                `<div id='packagingid' style='display:grid; gap:0; grid-template-columns: 80% 10% 10%;'>
                    <div style='grid-column:1; grid-row:1; padding:0; margin:0;'>
                        <input type='hidden' name='packaging_qc_by' id='packaging_qc_by'
                        value='<?= esc(auth()->user()->username) ?>'>
                        <input type='text' name='packaging_qc_by_display' id='packaging_qc_by_display'
                        style='padding:0; margin:0;height:100%; width:100%; border-style:solid; border-color:dimgray;text-align:center;'
                        value='<?= esc(auth()->user()->username) ?>' disabled>
                    </div>
                    <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                        <a id='cancelpackaging_qc_by' href='#' onclick='cancelpackagingapproval();' style='align-content:center; justify-self:center; text-align:center; width:100%; height:100%; border-style: solid; border-radius:5px; background-color:dimgrey; color:white; display:block;'>x</a>
                    </div>
                </div>`;
                $('#packagingid').replaceWith(newtext);
                packagingapproved = true;
                enableFinalQC();
            }
        });
    }

    function cancelcuppedby() {
        $('#cuppedbyid').replaceWith(`<div id='cuppedbyid' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
            <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
            <a id='btncuppedby'
                class='button v-small' style='width:-webkit-fill-available; color:white;'
                href='#'
                onclick='cuppedbyapproval();'>
            Click to Approve
            </a>
            </div>
            </div>`);
        cuppingapproved = false;
        enableFinalQC();

    }

    function cuppedbyapproval() {
        DayPilot.Modal.confirm("Do you Approve the Cupped by check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =
                `<div id='cuppedbyid' style='display:grid; gap:0; grid-template-columns: 80% 5% 15%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;'>
                            <input type='hidden' name='cupped_by' id='cupped_by'
                            value='<?= esc(auth()->user()->username) ?>'>
                            <input type='text' name='cupped_by_display' id='cupped_by_display'
                            class='grid-column:1; grid-cell' style='padding:0; margin:0;height:100%;border-style:solid; border-color:dimgray;text-align:center;'
                            value='<?= esc(auth()->user()->username) ?>'
                            disabled='disabled'>
                        </div>
                        <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                            <a id='cancelcuppedby'
                            class='disableifapproved'
                            href='#'
                            onclick='cancelcuppedby();'
                            style='align-content:center; justify-self:center; text-align:center; width:100%; height:100%; border-style: solid; border-radius:5px; background-color:dimgrey; color:white; display:block;'
                            >x</a>
                        </div>
                    </div>`;
                $('#cuppedbyid').replaceWith(newtext);
                cuppingapproved = true;
                enableFinalQC();
            }
        });
    }

    function cancel_weight_operator() {
        $('#weight_operator_id').replaceWith("<div id='weight_operator_id' style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'><a id='weight_operator_btn' class='button v-small' style='width:-webkit-fill-available; color:white;' href='#' onclick='weight_operator();'>Click to Approve</a></div>");
        enableFinalQC();
    }

    function weight_operator() {
        DayPilot.Modal.confirm("As the Operator do you Approve the Weight check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =
                `<div id='weight_operator_id' style='display:grid; gap:0; grid-template-columns: 80% 10% 10%;'>
                    <div style='grid-column:1; grid-row:1; padding:0; margin:0;'>
                        <input type='hidden' name='weight_operator' id='weight_operator'
                        value='<?= esc(auth()->user()->username) ?>'>
                        <input type='text' name='weight_operator_display' id='weight_operator_display'
                        style='padding:0; margin:0;height:100%; width:100%; border-style:solid; border-color:dimgray;text-align:center;'
                        value='<?= esc(auth()->user()->username) ?>' disabled>
                    </div>
                    <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                        <a id='cancel_weight_operator' href='#' onclick='cancel_weight_operator();' style='align-content:center; justify-self:center; text-align:center; width:100%; height:100%; border-style: solid; border-radius:5px; background-color:dimgrey; color:white; display:block;'>x</a>
                    </div>
                </div>`;
                $('#weight_operator_id').replaceWith(newtext);
                enableFinalQC();
            }
        });
    }


    function cancel_weight_leader() {
        $('#weight_leader_id').replaceWith("<div id='weight_leader_id' style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'><a id='weight_leader_btn' class='button v-small' style='width:-webkit-fill-available; color:white;' href='#' onclick='weight_leader();'>Click to Approve</a></div>");
        weightapproved = false;
        enableFinalQC();
    }

    function weight_leader() {
        DayPilot.Modal.confirm("As the Team Leader do you Approve the Weight check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =
                `<div id='weight_leader_id' style='display:grid; gap:0; grid-template-columns: 80% 10% 10%;'>
                    <div style='grid-column:1; grid-row:1; padding:0; margin:0;'>
                        <input type='hidden' name='weight_leader' id='weight_leader'
                        value='<?= esc(auth()->user()->username) ?>'>
                        <input type='text' name='weight_leader_display' id='weight_leader_display'
                        style='padding:0; margin:0;height:100%; width:100%; border-style:solid; border-color:dimgray;text-align:center;'
                        value='<?= esc(auth()->user()->username) ?>' disabled>
                    </div>
                    <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                        <a id='cancel_weight_leader' href='#' onclick='cancel_weight_leader();' style='align-content:center; justify-self:center; text-align:center; width:100%; height:100%; border-style: solid; border-radius:5px; background-color:dimgrey; color:white; display:block;'>x</a>
                    </div>
                </div>`;
                $('#weight_leader_id').replaceWith(newtext);
                weightapproved = true;
                enableFinalQC();
            }
        });
    }

    function showRangeValue(rangeId, markerId) {
        var val = document.getElementById(rangeId).value;
        document.getElementById(markerId).innerHTML = val;
    }

    function blurqty_requested()
    {
        var qty_requested = $('#qty_requested').val();
        var ratiototal = parseFloat($("#ratiototal").text());
        var wastepercent = parseFloat($('#wastepercent').text());
        var waste = 100 + wastepercent;  // Done this to save mulitplying by 100 below for rounding
        var ratio;
        for (let index = 1; index < 6; index++) {
            selectedcoffee = $('#green_coffee'+index).val();
            if(selectedcoffee.trim() != '' ){
                ratio = parseFloat($("#ratio"+index).text());
                if(ratiototal > 0){
                    $('#qty_used'+index).val(  Math.round(((ratio / ratiototal) * qty_requested) * waste) / 100);
                }
            }else{
                $('#qty_used'+index).val('');
            }
        }
        $('.qtychange').css('background-color','gold');
        var t = setTimeout(()=>{
            clearInterval(t);
            $('.qtychange').css('background-color','');
        },2000);
    }

    function getGreenCoffees() {
        var coffeename = document.getElementById('coffee_name').value;
        //var productionid = "<?= isset($production->ProductionID) ? $production->ProductionID : 0  ?>";
        let csrfField = document.getElementById('csrfcode');
        let csrfname = csrfField.name;
        let csrfval = csrfField.value;
        let vals = {};
        vals['coffeename'] = coffeename;
        vals[csrfname] = csrfval;
        var url = "<?= base_url('production/getgreencoffees') ?>";
        htmx.ajax('POST',
            url, {
                target: "#res",
                swap: 'none',
                handler: (_, response) => {
                    res = JSON.parse(response.xhr.responseText);
                    // Update Hidden csrf token input with new value
                    $('#csrfcode').val(res.token);
                    var sel =  res.selects; //  data['selects'];
                    var cer =  res.certchecks; // data['certchecks'];
                    var qty =res.qty; //  data['qty'];
                    var recipeinfo =  res.recipeinfo; //  data['recipeinfo'];
                    var certs = res.certifications; // data['certifications'];
                    //console.log('FromNumber');
                    //console.log(recipeinfo['FromNumber']);
                    console.log('getGreenCoffees');
                    $('#roastfromnumber').text(recipeinfo['FromNumber']);
                    $('#roasttonumber').text(recipeinfo['ToNumber']);
                    $('#wastepercent').text(recipeinfo['WastePercent']);
                    $('#profile_used').val(recipeinfo['RecipeCode']);
                    $('#weight_pack').val(recipeinfo['PackQty']);
                    $('#roastcolournodisplay').text(recipeinfo['RoastColourNo']);
                    $('#roastcolourno').val(recipeinfo['RoastColourNo']);


                    $('#recipe-image-img').attr("src",recipeinfo['ImageName']);
                    $('#recipe-image-a').attr("href",recipeinfo['ImageName']);

                    for (const key in cer) {
                        //    ele = cer[key];
                        $('#' + key).replaceWith(cer[key]);
                    }

                    // checkboxes in top certification section
                    $('#certifications').replaceWith(certs.certcheckbox);
                    for (key in sel) {
                        str = sel[key];
                        for(k in str ){
                            $('#' + k).replaceWith(str[k]);
                        }
                    }
                    var selectedcoffee
                    var ratiototal = 0;
                    for (let index = 1; index < 6; index++) {
                        selectedcoffee = $('#green_coffee'+index).val();
                        ratiototal += parseInt(qty[selectedcoffee]);
                        $('#ratio'+index).text(qty[selectedcoffee]);
                        $('#ratiototal').text(ratiototal);
                    }

                    blurqty_requested();

                    showRoastName();

                    $('.inputchange').css('background-color','gold');
                    var t = setTimeout(()=>{
                        clearInterval(t);
                        $('.inputchange').css('background-color','');
                    },2000);
                },
                values: vals
            }
        );
    }

    function initCoffees() {
        var coffeename = document.getElementById('coffee_name').value;
        if (coffeename.trim() == '') {
            return;
        }
        var url = "<?= base_url('production/getgreencoffees') ?>";
        let csrfField = document.getElementById('csrfcode');
        let csrfname = csrfField.name;
        let csrfval = csrfField.value;
        let vals = {};
        vals['coffeename'] = coffeename;
        vals[csrfname] = csrfval;
        htmx.ajax('POST',
            url, {
                target: "#res",
                swap: 'none',
                handler: (_, response) => {
                    res = JSON.parse(response.xhr.responseText);
                    // Update Hidden csrf token input with new value
                    $('#csrfcode').val(res.token);
                    var sel =  res.selects; //  data['selects'];
                    var cer =  res.certchecks; // data['certchecks'];
                    var qty =res.qty; //  data['qty'];
                    var recipeinfo =  res.recipeinfo; //  data['recipeinfo'];
                    var certs = res.certifications; // data['certifications'];

                    for (const key in cer) {
                        //    ele = cer[key];
                        $('#' + key).replaceWith(cer[key]);
                    }

                    $('#roastfromnumber').text(recipeinfo.FromNumber);
                    $('#roasttonumber').text(recipeinfo.ToNumber);
                    showRoastName();

                    // checkboxes in top certification section
                    $('#certifications').replaceWith(certs.certcheckbox);

                    $('#wastepercent').text(recipeinfo['WastePercent']);
                    var selectedcoffee
                    var ratiototal = 0;
                    for (let index = 1; index < 6; index++) {
                        selectedcoffee = $('#green_coffee'+index).val();
                        ratiototal += parseInt(qty[selectedcoffee]);
                        $('#ratio'+index).text(qty[selectedcoffee]);
                        $('#ratiototal').text(ratiototal);
                    }
                },
                values: vals
            }
        );
    }

    $().ready(() => {
        // On Page Ready

    initCoffees();

    var all_approved = false;
    <?php if(auth()->user()->can_edit('Coffee Quality Control Checklist') == false) : ?>
        all_approved = true;
        console.log('User can NOT edit - all_appoved is true');
    <?php else: ?>
        <?php if( (null == $production->final_qc_approval || empty($production->final_qc_approval) ||
            null == $production->packaging_qc_by   || empty($production->packaging_qc_by)   ||
            null == $production->weight_leader   || empty($production->weight_leader) ) ): ?>

            console.log('User can edit and at least one of the approvals is false so allapproved is false');
            all_approved = false;


        <?php else: ?>
            console.log('User ');
            if($('.showhidecupping').is(':visible')){
                console.log('cupping is visible');
                <?php if(null == $production->cupped_by || empty($production->cupped_by)): ?>
                    // Cupping not approved
                    console.log('Cupping not approved');
                    all_approved = false;
                <?php else: ?>
                    // Cupping Approved
                    console.log('Cupping approved');
                    all_approved = true;
                <?php endif; ?>
            }else{
                all_approved = false;
            }

        <?php endif; ?>
    <?php endif; ?>

    if(all_approved == false) {
        // Can be edited / approved but not all approvals have been given yet
        console.log('Can be edited / approved but not all approvals have been given yet');
        // Packaging approval
        <?php if (null == $production->packaging_qc_by   || empty($production->packaging_qc_by) ): ?>
            packagingapproved = false;
        <?php else: ?>
            packagingapproved = true;
        <?php endif; ?>


        // Cupping Approval
        // Cupping Section can be hidden and not used if Agtron number within bounds of recipe agtron number limits
        if($('.showhidecupping').is(':visible')){
            <?php if(null == $production->cupped_by || empty($production->cupped_by)) : ?>
                cuppingapproved = false;
            <?php else: ?>
                cuppingapproved = true;
            <?php endif; ?>
        }else{
            // Cuuping is not required so assume true
            cuppingapproved = true;
        }


        // Do not disable controls if admin or approved by is empty
//        initCoffees();
        $(".disableifapproved").prop("disabled", false);

        <?php if(null == $production->weight_leader || empty($production->weight_leader)) : ?>
            weightapproved = false;
        <?php else: ?>
            weightapproved = true;
            $(".weightdisableifapproved").prop("disabled", true);
        <?php endif; ?>

        // Since not all the other sections have been approved yet then the finalqc is disabled
        console.log('Since not all the other sections have been approved yet then the finalqc is disabled');
        newtext = `<div id='finalqcid' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                    <div id='btnfinalqcapproval' class='button v-small' style='width:-webkit-fill-available; background-color: darkgray;  color:white;' disabled>Final Approval</div>
                </div>
            </div>`;

        $('#finalqcid').replaceWith(newtext);

    } else {

        console.log('Everything has been approved so disable all controls');
        // Everything has been approved so disable all controls
        //
        // disbale controls becasuse form is sapproved
        packagingapproved = true;
        cuppingapproved = true;
        weightapproved = true;
        $(".disableifapproved").prop("disabled", true);
        $(".weightdisableifapproved").prop("disabled", true);
        $("a.disableifapproved").hide();
        $("#submit_btn").hide();
        $("#cancel_btn").html('Back');
        <?php if(auth()->user()->can_edit('Coffee Quality Control Checklist') == false) : ?>
            // disable final qc approval if user cannot edit
            $('#btnpackaging_qc_by').prop("disabled", true);
            $('#btncuppedby').prop("disabled", true);
            $('#btnfinalqcapproval').prop("disabled", true);
            $('#weight_operator_btn').prop("disabled", true);
            $('#weight_leader_btn').prop("disabled", true);

            console.log('disabled btns');
        <?php endif; ?>
    }
    }
    );

    function enableFinalQC() {
        var newtext;
        var cuppingvisible;
        cuppingvisible = $('.showhidecupping').is(':visible');
        if ((cuppingvisible && (cuppingapproved == false || packagingapproved  == false || weightapproved == false)) || (cuppingvisible == false && (packagingapproved == false || weightapproved == false))) {
            console.log('enableFinalQC - set final not approved');
            console.log(cuppingvisible);
            console.log(packagingapproved);
            console.log(weightapproved);

            <?php if(null == $production->final_qc_approval || empty($production->final_qc_approval)): ?>
                // final qc has some text in it - so it must be disabled
                //$('#finalqcid').prop("disabled", true);
                newtext = `<div id='finalqcid' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                            <div id='btnfinalqcapproval' class='button v-small' style='width:-webkit-fill-available; background-color: darkgray;  color:white;' disabled>Final Approval</div>
                        </div>
                    </div>`;

            <?php else: ?>

            //                $('#finalqcid').prop("disabled", false);
            newtext =`<div id="finalqcid" style="display:grid; gap:0; grid-template-columns: 70% 20% 10%;">
                            <div style="grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;">
                                <a id="btnfinalqcapproval" class="button v-small" style="width:-webkit-fill-available; color:white;" href="#" onclick="finalqcapproval();">Click to Approve</a>
                            </div>
                        </div>`;
            $('#finalqcid').replaceWith(newtext);

            <?php endif; ?>

            // newtext =`<div id="finalqcid" style="display:grid; gap:0; grid-template-columns: 70% 20% 10%;">
            //                 <div style="grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;">
            //                     <a id="btnfinalqcapproval" class="button v-small" style="width:-webkit-fill-available; color:white;" href="#" onclick="finalqcapproval();">Click to Approve</a>
            //                 </div>
            //             </div>`;

        }else{
            console.log('enableFinalQC - set final IS approved');
            //$('#finalqcid').prop("disabled", true);

            newtext = `<div id='finalqcid' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                    <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                        <div id='btnfinalqcapproval' class='button v-small' style='width:-webkit-fill-available; background-color: darkgray;  color:white;' disabled>Final Approval</div>
                    </div>
                </div>`;

        }
        $('#finalqcid').replaceWith(newtext);
    }


    function batch_changed() {
        var batchno = $('#batch_number').val();
        //if($('#weight_batch_code').val() == ''){
            $('#weight_batch_code').val(batchno);
        //}
    }

</script>

<script src="<?= base_url('js/lightbox2/dist/js/lightbox.js') ?>"></script>
