<?= $this->extend("layouts/default") ?>
<?= $this->section("title") ?>Input Prices<?= $this->endSection() ?>

<?= $this->section("header") ?>
<link rel="stylesheet" href="<?= base_url('/js/jquery-ui-1.14.1/jquery-ui.min.css') ?>" />
<link rel="stylesheet" href="<?= base_url('/js/tabulator-master/dist/css/tabulator_simple.css') ?>" />

<script type='text/javascript' src="<?= base_url('/js/jquery/jquery-3.7.1.min.js') ?>"> </script>
<script type='text/javascript' src="<?= base_url('/js/jquery-ui-1.14.1/jquery-ui.min.js') ?>"> </script>
<script type='text/javascript' src="<?= base_url('/js/luxon.min.js') ?>"> </script>
<script type='text/javascript' src="<?=base_url('/js/tabulator-master/dist/js/tabulator.min.js');?>"></script>
<script type='text/javascript' src="<?=base_url('/js/daypilot-modal-confirm/js/daypilot-modal-3.15.1.min.js');?>"></script>
<link rel="stylesheet" href="<?=base_url('/js/daypilot-modal-confirm/themes/modal_rounded.css'); ?>" type="text/css">
<script type='text/javascript' src="<?=base_url('/js/htmx/htmx.min.js');?>"></script>
<?= $this->endSection() ?>

<?= $this->section("content") ?>

<input type="hidden" id="csrfcode" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>">
<div id="res"></div>

<?= view("layouts/bcr-nav",
    [
        "title" => "Input Prices for $input->InputName",
        "controller" => "InputCosts",
        "links" => [
            "Back" => ["url" => base_url("inputs/$inputid"), "auth_check" => false],
            "New" =>  ["url" => base_url("InputCosts/new/$inputid"), "auth_check" => true]
        ]
    ]
) ?>

<?= $this->include("layouts/tabulatorgrid") ?>

<script type='text/javascript'>

    var rowMenu = [{
        label:"<i class='fas fa-trash'></i> Delete Row",
        action:function(e, row){
            e.preventDefault();
            var cost = row.getCell('Cost').getValue();
            var validfrom  = row.getCell('ValidFromDate').getValue();
            DayPilot.Modal.confirm("DELETE Price "+cost+ " valid from " + validfrom +  " ?",
            { theme: "modal_rounded" }).then(function(args) {
//            console.log(args.result);
              var inputcostid = row.getCell('InputCostID').getValue();
            if(args.result){
                let csrfField = document.getElementById('csrfcode');
                let htmxpath = "<?= base_url("InputCosts/delete")?>";
                let csrfname = csrfField.name;
                let csrfval = csrfField.value;
                let success = 0;
                let vals = {};
                vals['InputCostID'] = inputcostid;
                vals[csrfname] = csrfval;
                htmx.ajax('POST',
                    htmxpath,
                    {
                        target: "#res",
                        swap: 'none',
                        handler: (_, response) => {
                            //console.log(response.xhr.response);
                            res = JSON.parse(response.xhr.response);

                            success = res.success;
                            $('#csrfcode').val(res.token);
                            if(success == 1){
                                //console.log(success);
                                row.delete();
                            }else{
                                DayPilot.Modal.alert("Something went wrong. I can't delete this price",
                                { theme: "modal_rounded" });
                            }
                        },
                        values: vals
                    }
                );
            }
        });
        }
    }];
    var table = new Tabulator('#wrapper',{
        data: [
            <?php foreach ($inputcosts as $inputcost): ?>
            <?="{" ?>
            <?="InputCostID:$inputcost->InputCostID," ?>
            <?="InputID:$inputcost->InputID," ?>
            <?="Cost:$inputcost->Cost," ?>
            <?="ValidFromDate:'$inputcost->ValidFromDate'," ?>
            <?="lastupdated:'$inputcost->lastupdated'," ?>
            <?="updatedby:'".addslashes($inputcost->username)."'," ?>
            <?="}," ?>
            <?= chr(13).chr(10) ?>
            <?php endforeach; ?>
        ],
        layout:"fitDataStretch",
        pagination: false,
        tooltips: true,
        rowContextMenu: rowMenu,
        columns: [{
                title: "InputCostID",
                field: "InputCostID",
                sorter: "number",
                //width: 150,
                visible: false,
            },{
                title: "InputID",
                field: "InputID",
                sorter: "number",
                //width: 150,
                visible: false,
            }, {
                title: "Valid From",
                field: "ValidFromDate",
                sorter: "datetime",
                hozAlign: "left",
                //width: "fit-content",
                formatter: "datetime",
                formatterParams: {
                    inputFormat: "yyyy-LL-dd TT",
                    outputFormat: "dd/MM/yyyy",
                    invalidPlaceholder: "(invalid date)",
                    timezone: "system",
                },
                sorter: "datetime",
                sorterParams: {
                    format: "yyyy-MM-dd HH:mm:ss",
                    alignEmptyValues: "top",
                }
            },{
                title: "Price/Kg",
                field: "Cost",
                sorter: "number",
                hozAlign: "right",
                //width: "fit-content",
                responsive:0,
                formatter: "money",
                formatterParams:{
                    decimal:".",
                    thousand:"",
                    symbol:"£",
                    symbolAfter:"",
                    negativeSign:true,
                    precision:2,
                }
            }, {
                title: "Record Updated",
                field: "lastupdated",
                sorter: "datetime",
                hozAlign: "left",
                //width: "fit-content",
                responsive:4,
                formatter: "datetime",
                formatterParams: {
                    inputFormat: "yyyy-LL-dd TT",
                    outputFormat: "dd/MM/yyyy HH:mm:ss",
                    invalidPlaceholder: "(invalid date)",
                    timezone: "system",
                },
                sorter: "datetime",
                sorterParams: {
                    format: "yyyy-MM-dd HH:mm:ss",
                    alignEmptyValues: "top",
                }
            }, {
                title: "Updated By",
                field: "updatedby",
                sorter: "string",
                hozAlign: "left",
                //width: "fit-content",
                headerFilter:"list",
                headerFilterParams:{valuesLookup:true, clearable:true},
                responsive:3,
            },
        ],
    }).on('rowClick', function(e, row) {
        window.location = '<?= base_url("InputCosts")."/"?>' + row.getCell('InputCostID').getValue() + '/edit';
    });
</script>


<?= $this->endSection() ?>

<?= $this->section("javascript") ?>
<?= $this->endSection() ?>

