<script type='text/javascript'>
    var operator_approval = false;
//    var teamleader_approval = 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 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;
        console.log('disable controls '+disablecontrols());
        vals['isdisabled'] = disablecontrols();
        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['isdisabled'] = disablecontrols();
        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
            }
        );
    }

    function remove_operator_approval() {
        var newtext;
        newtext =  `<div id='operator_approval_id' style='display:grid; gap:0; grid-template-columns: 80% 5% 15%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                            <a id='btn_operator_approval' class='button v-small' style='width:-webkit-fill-available; color:white;' onclick='set_operator_approval();'>
                                Click to Approve
                            </a>
                            <input name='operator_approval' type='hidden' id='operator_approval'>
                        </div>
                    </div>`;
        $('#operator_approval_id').replaceWith(newtext);
        submitPost('operator_approval','');
        operator_approval = false;
        enable_teamleader_approval();
    }



    function set_operator_approval() {
        if(!checkEntries()){
            return;
        }

        DayPilot.Modal.confirm("As the Operator do you approve this quality check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =
                `<div id='operator_approval_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='operator_approval' id='operator_approval'
                        value='<?= esc(auth()->user()->username) ?>'>
                        <input type='text' name='operator_approval_display' id='operator_approval_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>`;
                    <?php if (auth()->user()->inGroup('admin')): ?>
                    newtext = newtext + `<div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                        <a id='cancel_operator_approval' href='#' onclick='remove_operator_approval();' 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>`;
                <?php endif; ?>
                newtext = newtext + `</div>`;
                $('#operator_approval_id').replaceWith(newtext);
                submitPost('operator_approval','<?= esc(auth()->user()->username) ?>');
                operator_approval = true;
                enable_teamleader_approval();
            }
        });
    }


    function remove_teamleader_approval() {
        var newtext;
        newtext = `<div id='teamleader_approval_id' style='display:grid; gap:0; grid-template-columns: 80% 5% 15%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                            <a id='btn_operator_approval' class='button v-small' style='width:-webkit-fill-available; color:white;' onclick='set_teamleader_approval();'>
                                Click to Approve
                            </a>
                            <input type='hidden' name='teamleader_approval' id='teamleader_approval' value=''>
                        </div>
                    </div>`;
        $('#teamleader_approval_id').replaceWith(newtext);
        submitPost('teamleader_approval','');
    }

    function set_teamleader_approval() {
        if(!checkEntries()){
            return;
        }

        DayPilot.Modal.confirm("As the Teamleader do you approve this quality check?", {
            theme: "modal_rounded"
        }).then(function(args) {
            if (args.result) {
                var newtext =
                `<div id='teamleader_approval_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='teamleader_approval' id='teamleader_approval'
                        value='<?= esc(auth()->user()->username) ?>'>
                        <input type='text' name='teamleader_approval_display' id='teamleader_approval_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_teamleader_approval' href='#' onclick='remove_teamleader_approval();' 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>`;
                $('#teamleader_approval_id').replaceWith(newtext);
                $(".disableifapproved").prop("disabled", true);
                //submitPost('teamleader_approval','<?= esc(auth()->user()->username) ?>');
                $('#submit_btn').click();
            }
        });
    }

    function enable_teamleader_approval()
    {
        var newtext;
        <?php if(auth()->user()->can_edit('Coffee Quality Control Checklist')) : ?>
            if(operator_approval){
                <?php if(null == $production->teamleader_approval   || empty($production->teamleader_approval)): ?>
                    // Operator approval but NO teamleader approval yet, display enabled teamleader approval button
                    console.log('Operator approval but NO teamleader approval yet, display enabled teamleader approval button');
                    newtext =  `<div id='teamleader_approval_id' style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                                    <a id='btn_teamleader_approval' class='button v-small' style='width:-webkit-fill-available; color:white;' href='#' onclick='set_teamleader_approval();'>
                                        Click to Approve
                                    </a>
                                </div>`;
                <?php else: ?>
                    // There is Operator Approval and there is Teamleader approval so display name and disable everything
                    console.log('There is Operator Approval and there is Teamleader approval so display name and disable everything');
                    newtext =  `<div id='teamleader_approval_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='teamleader_approval' id='teamleader_approval'
                                            value='<?= esc($production->teamleader_approval) ?>'>
                                        <input type='text' name='teamleader_approval_display' id='teamleader_approval_display'
                                            style='padding:0; margin:0;height:100%; width:100%; border-style:solid; border-color:dimgray;text-align:center;'
                                            value='<?= esc($production->teamleader_approval) ?>' disabled>
                                    </div>`;

                                <?php if (auth()->user()->inGroup('admin')): ?>
                                    newtext = newtext + `<div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                                        <a id='cancel_teamleader_approval'
                                            class='disableifapproved'
                                            href='#'
                                            onclick='remove_teamleader_approval();'
                                            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>`;
                                <?php endif; ?>
                                newtext = newtext + `</div>`;
                <?php endif; ?>
            }else{
                <?php if(null == $production->teamleader_approval   || empty($production->teamleader_approval)): ?>
                // No Operator Approval yet and there is no teamleader approval so disable teamleader button
                console.log('No Operator Approval yet and there is no teamleader approval so disable teamleader button');
                newtext = `<div id='teamleader_approval_id' 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='btn_teamleader_approval' class='button v-small' style='width:-webkit-fill-available; background-color: darkgray;  color:white;' disabled>
                            Click to Approve
                        </div>
                    </div>
                </div>`;
            <?php else: ?>
                // No Operator Approval but there is Teamleader approval - this shouldn't be possible
                console.log('No Operator Approval but there is Teamleader approval - this shouldnt be possible');
                newtext =  `<div id='teamleader_approval_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='teamleader_approval' id='teamleader_approval'
                                        value='<?= esc($production->teamleader_approval) ?>'>
                                    <input type='text' name='teamleader_approval_display' id='teamleader_approval_display'
                                        style='padding:0; margin:0;height:100%; width:100%; border-style:solid; border-color:dimgray;text-align:center;'
                                        value='<?= esc($production->teamleader_approval) ?>' disabled>
                                </div>
                                <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                                    <a id='cancel_teamleader_approval'
                                        class='disableifapproved'
                                        href='#'
                                        onclick='remove_teamleader_approval();'
                                        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>`;
            <?php endif; ?>
            }
        <?php endif; ?>
        $('#teamleader_approval_id').replaceWith(newtext);
    }

    function checkEntries(){
        $coffeename = $('#coffee_name').val();
        if(!$coffeename){
            DayPilot.Modal.alert("Please select a coffee first", {
                theme: "modal_rounded"
            });
            return false;
        }
        $batchnumber = $('#batch_number').val();
        if(!$batchnumber){
            DayPilot.Modal.alert("Please enter a batch number first", {
                theme: "modal_rounded"
            });
            return false;
        }
        $qtyrequested = $('#qty_requested').val();
        if(!$qtyrequested){
            DayPilot.Modal.alert("Please enter quantity requested first", {
                theme: "modal_rounded"
            });
            return false;
        }
        $checkedby = $('#checked_by').val();
        if(!$checkedby){
            DayPilot.Modal.alert("Please enter checked by first", {
                theme: "modal_rounded"
            });
            return false;
        }
        $checkdate = $('#check_date').val();
        if(!$checkdate){
            DayPilot.Modal.alert("Please enter check date first", {
                theme: "modal_rounded"
            });
            return false;
        }
        return true;
    }

    $().ready(() => {
        // On Page Ready
        initCoffees();
        <?php if(null == $production->operator_approval || empty($production->operator_approval)): ?>
            // No Operator Approval yet
            //console.log('No Operator Approval yet');
            operator_approval = false;
        <?php else: ?>
            // Operator Approved
            //console.log('Operator Approved');
            operator_approval = true;
        <?php endif; ?>
        enable_teamleader_approval();

        $disable = disablecontrols() == 'yes' ? true : false;

        $(".disableifapproved").prop("disabled", $disable);

        }
    );


    function disablecontrols(){
        <?php if(auth()->user()->can_edit('Coffee Quality Control Checklist')): ?>
            <?php if(null == $production->teamleader_approval || empty($production->teamleader_approval)): ?>
                return 'no';
            <?php else: ?>
                return 'yes';
            <?php endif; ?>
        <?php else: ?>
            return 'yes';
        <?php endif; ?>
    }



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

    function submitPost(inputname, inputvalue) {
        <?php if(null == $production->ProductionID || empty($production->ProductionID)): ?>
            $('#submit_btn').click();
            return;
        <?php endif; ?>

        var productionid = "<?= isset($production->ProductionID) ? $production->ProductionID : 0  ?>";
        let csrfField = document.getElementById('csrfcode');
        let csrfname = csrfField.name;
        let csrfval = csrfField.value;
        let vals = [];
        let formvals = $( "form" ).serializeArray();

        for (var i = formvals.length - 1; i >= 0; i--) {
            // console.log(formvals[i]);
            vals[formvals['name']] = formvals['value'];
        }


        vals[inputname] = inputvalue;
        vals[csrfname] = csrfval;

console.log(csrfval);

        // for (var i = vals.length - 1; i >= 0; i--) {
        //     console.log(vals[i]);
        // }
        var url = "<?= base_url('production/' . $production->ProductionID) .'/update' ?>";
        htmx.ajax('POST',
            url, {
                target: "#res",
                swap: 'none',
                handler: (_, response) => {
                    console.log(response.xhr.responseText);
                    res = JSON.parse(response.xhr.responseText);
                    // Update Hidden csrf token input with new value
                    $('#csrfcode').val(res.token);
                    console.log($('#csrfcode').val());
                    if(res.success){
                        console.log(res.success);
                        if(res.success != 'SUCCESS')
                            alert(res.success);
                    }
                },
                values: vals
            }
        );
    }


</script>

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