<script src="<?= base_url() ?>assets/libs/iziToast/iziToast.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?= base_url() ?>assets/libs/iziToast/iziToast.min.css">


    <script type="text/javascript">

      $(document).ready(function(){

          app.dashboard.lineSelect = NiceSelect.bind(document.getElementById("lineSelect"), { searchable: false });

          app.dashboard.machineSelect = NiceSelect.bind(document.getElementById("machineSelect"), { searchable: false });

          const result  = JSON.parse('<?= json_encode($result) ?>')

          // showAchivedChart()
          // showHistoryAmperChart()
          // showHistoryUsedChart()
      })


      $("#lineSelect").on('change',function(){

          const selected = $(this).find(':selected');
          const base64 = selected.attr('data-machine-parse');
          const machines = JSON.parse(atob(base64));

          app.dashboard.machineSelect.destroy()
          $('#machineSelect').empty();

          machines.forEach(item=>{
            $('#machineSelect').append(`<option value="${item.name}" data-id="${item.id}" data-name="${item.name}" data-no="${item.machine_no}" >${item.name}</option>`);
          })

          app.dashboard.machineSelect = NiceSelect.bind(document.getElementById("machineSelect"), { searchable: false });

          resetMachineSelect()
      })


      $("#machineSelect").on('change',function(){

          const selected = $(this).find(':selected');

          const id = selected.attr('data-id');
          const no = selected.attr('data-no');
          const name = selected.attr('data-name');
          resetMachineSelect()

          if($(this).val()!=undefined){
              $('.label-machine-no').html(no)
              $('.label-machine-name').html(name)

              if(app.dashboard.currentMachineSelected!=id){
                app.dashboard.machineSelectName = name
                app.dashboard.currentMachineSelected = id
              }
          }


      })


      $("#btn_show_data").on('click',function(e){
          e.preventDefault()
          if(app.dashboard.currentMachineSelected==null){
            iziToast.show({
              title: 'Error',
              message: "The machine hasn't been selected, pleas select the machine ",
              color: 'red',
              position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
            });
            return
          }


          if($('input[name="production_date"]').val()==""){
            iziToast.show({
              title: 'Error',
              message: "Production date can't empty, pleas set production date",
              color: 'red',
              position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
            });
            return
          }


          $(this).html(`<div class="d-flex justify-content-center align-items-center">
                    <div class="lds-ring me-2"><div></div><div></div><div></div><div></div></div>
                    <span>Load Data</span> 
                  </div>`)
          $(this).attr('disabled','disabled')


          $.ajax({
            url: `${base_url}dashboard/machine`,
            type: 'GET',
            dataType: 'JSON',
            data: {
              id: app.dashboard.currentMachineSelected,
              productionDate: $('input[name="production_date"]').val()
            },
            success: (response) => {


              $(this).html(`Show Data`)
              $(this).attr('disabled',false)


              const totalToday = Number(response.data.totalToday)
              $(".label-operation-date").html(formatDateID($('input[name="production_date"]').val()))
              $(".label-total-operation-time").html(convertSecondsToTime(parseInt(response.data.total))+' h')
              $(".label-total-operation-time-today").html(totalToday.toFixed(1)+' h')
              $(".label-average-current-today").html(`${response.data.averageAmp} amp`)
              $(".label-average-operation-daily").html(`${response.data.averageOperation} h`)
              $(".label-target-time").html(`<span class="badge rounded bg-success">${response.data.target} Hours</span>`)
              $(".label-time-now").html(`<span class="badge rounded bg-danger">${convertSecondsToTime(parseInt(response.data.total))} Hours</span>`)


                const goalSeconds = parseInt(response.data.target) * 3600
                const achivedSeconds = parseInt(response.data.total)
                
                const achiveddPercent = (achivedSeconds / goalSeconds) * 100
                const goalPercent     = 100 - achiveddPercent


                app.dashboard.machineInfromation.achiveddPercent = achiveddPercent
                app.dashboard.machineInfromation.goalPercent = goalPercent
                
                showAchivedChart(achiveddPercent, goalPercent)
                
                _achived_ = Math.round(achiveddPercent * 10) / 10;
                _goal_ = Math.round(goalPercent * 10) / 10;
                if(_achived_>=100){
                  setAllert(true,app.dashboard.currentMachineSelected,app.dashboard.machineSelectName)
                }else{
                  setAllert(false,app.dashboard.currentMachineSelected,app.dashboard.machineSelectName)

                }


                showHistoryAmperChart(response.data.visualData.machine.value)
                showHistoryUsedChart(response.data.visualData.machine.history)

                chartHistoryRpm(response.data.visualData.rpm.value)
                chartHistoryRpmUsed(response.data.visualData.rpm.history)

                chartHistoryTemperature(response.data.visualData.temperature.value)
                chartHistoryTemperatureUsed(response.data.visualData.temperature.history)


                app.dashboard.isRealTime = setInterval(() => {
                    getInformationAllData()
                }, 3000); 

            },
            error: () => {

              $(this).html(`Show Data`)
              $(this).attr('disabled',false)

            }
          })

      })


      $("#reset_filter").on('click',function(e){
        e.preventDefault()
        resetMachineSelect();
      })

      $("#btn_save_target").on('click',function(e){
        e.preventDefault()

          if(app.dashboard.currentMachineSelected==null){
            iziToast.show({
              title: 'Error',
              message: "The machine hasn't been selected, pleas select the machine ",
              color: 'red',
              position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
            });
            return
          }

          if($('input[name="goal"]').val()==""){
              iziToast.show({
                title: 'Error',
                message: "Can't save empty value, pleas enter the value ",
                color: 'red',
                position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
              });
              return
          }

          $(this).html(`<div class="d-flex justify-content-center align-items-center">
                    <div class="lds-ring me-2"><div></div><div></div><div></div><div></div></div>
                    <span>Saving Data</span> 
                  </div>`)
          $(this).attr('disabled','disabled')


          $.ajax({
            url: `${base_url}dashboard/save-goal`,
            type: 'POST',
            dataType: 'JSON',
            data: JSON.stringify({
              id: app.dashboard.currentMachineSelected,
              goal: $('input[name="goal"]').val()
            }),
            success: (response) => {

              $(this).html(`Submit`)
              $(this).attr('disabled',false)

              if(response.success){

                iziToast.show({
                  title: 'Success',
                  message: response.message,
                  color: 'green',
                  position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
                });

                loadUpdatedInformationMachine()

              }else{
                iziToast.show({
                  title: 'Error',
                  message: response.message,
                  color: 'red',
                  position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
                });
              }


            },
            error: () => {

              $(this).html(`Submit`)
              $(this).attr('disabled',false)

            }
          })


      })

      function loadUpdatedInformationMachine()
      {
          $.ajax({
            url: `${base_url}dashboard/machine`,
            type: 'GET',
            dataType: 'JSON',
            data: {
              id: app.dashboard.currentMachineSelected,
              productionDate: $('input[name="production_date"]').val()
            },
            success: (response) => {
              const totalToday = Number(response.data.totalToday)
              $(".label-operation-date").html(formatDateID($('input[name="production_date"]').val()))
              $(".label-total-operation-time").html(convertSecondsToTime(parseInt(response.data.total))+' h')
              $(".label-total-operation-time-today").html(totalToday.toFixed(1)+' h')
              $(".label-average-current-today").html(`${response.data.averageAmp} amp`)
              $(".label-average-operation-daily").html(`${response.data.averageOperation} h`)
              $(".label-target-time").html(`<span class="badge rounded bg-success">${response.data.target} Hours</span>`)
              $(".label-time-now").html(`<span class="badge rounded bg-danger">${convertSecondsToTime(parseInt(response.data.total))} Hours</span>`)


                const goalSeconds = parseInt(response.data.target) * 3600
                const achivedSeconds = parseInt(response.data.total)
                
                const achiveddPercent = (achivedSeconds / goalSeconds) * 100
                const goalPercent     = 100 - achiveddPercent
                
                app.dashboard.machineInfromation.achiveddPercent = achiveddPercent
                app.dashboard.machineInfromation.goalPercent = goalPercent

                showAchivedChart(achiveddPercent, goalPercent)

                _achived_ = Math.round(achiveddPercent * 10) / 10;
                _goal_ = Math.round(goalPercent * 10) / 10;
                if(_achived_>=100){
                  setAllert(true,app.dashboard.currentMachineSelected,app.dashboard.machineSelectName)
                }else{
                  setAllert(false,app.dashboard.currentMachineSelected,app.dashboard.machineSelectName)

                }


            },
            error: () => {

            }
          })

      }

      function resetMachineSelect()
      {

        $("input[name=production_date]").val('')
        $(".label-machine-name").html('-')
        $(".label-machine-no").html('-')

        $(".label-operation-date").html('-')
        $(".label-total-operation-time").html('-')
        $(".label-total-operation-time-today").html('-')
        $(".label-average-current-today").html(`-`)
        $(".label-average-operation-daily").html(`-`)
        $(".label-target-time").html(`-`)
        $(".label-time-now").html(`-`)

        setAllert(false)

        app.dashboard.currentMachineSelected = null
        if(app.dashboard.chartInfromationMachine!=null){
          app.dashboard.chartInfromationMachine.destroy()
        }
        app.dashboard.chartInfromationMachine = null


        if(app.dashboard.chartHistoryAmper!=null){
          app.dashboard.chartHistoryAmper.destroy()
        }
        app.dashboard.chartHistoryAmper = null


        if(app.dashboard.chartHistoryUsed!=null){
          app.dashboard.chartHistoryUsed.destroy()
        }
        app.dashboard.chartHistoryUsed = null


        if(app.dashboard.chartHistoryRpm!=null){
          app.dashboard.chartHistoryRpm.destroy()
        }
        app.dashboard.chartHistoryRpm = null


        if(app.dashboard.chartHistoryRpmUsed!=null){
          app.dashboard.chartHistoryRpmUsed.destroy()
        }
        app.dashboard.chartHistoryRpmUsed = null


        if(app.dashboard.chartHistoryTemperature!=null){
          app.dashboard.chartHistoryTemperature.destroy()
        }
        app.dashboard.chartHistoryTemperature = null


        if(app.dashboard.chartHistoryTemperatureUsed!=null){
          app.dashboard.chartHistoryTemperatureUsed.destroy()
        }
        app.dashboard.chartHistoryTemperatureUsed = null

        if(app.dashboard.isRealTime!=null){
          clearInterval(app.dashboard.isRealTime)

        }
        app.dashboard.isRealTime = null

      }


      function getInformationAllData()
      {
          if(app.dashboard.currentMachineSelected==null){
            return
          }


          if($('input[name="production_date"]').val()==""){
            return
          }


          $.ajax({
            url: `${base_url}dashboard/all-information`,
            type: 'GET',
            dataType: 'JSON',
            data: {
              id: app.dashboard.currentMachineSelected,
              productionDate: $('input[name="production_date"]').val()
            },
            success: (response) => {

              const totalToday = Number(response.data.totalToday)
              $(".label-operation-date").html(formatDateID($('input[name="production_date"]').val()))
              $(".label-total-operation-time").html(convertSecondsToTime(parseInt(response.data.total))+' h')
              $(".label-total-operation-time-today").html(totalToday.toFixed(1)+' h')
              $(".label-average-current-today").html(`${response.data.averageAmp} amp`)
              $(".label-average-operation-daily").html(`${response.data.averageOperation} h`)
              $(".label-target-time").html(`<span class="badge rounded bg-success">${response.data.target} Hours</span>`)
              $(".label-time-now").html(`<span class="badge rounded bg-danger">${convertSecondsToTime(parseInt(response.data.total))} Hours</span>`)


                const goalSeconds = parseInt(response.data.target) * 3600
                const achivedSeconds = parseInt(response.data.total)
                
                achiveddPercent = (achivedSeconds / goalSeconds) * 100
                goalPercent     = 100 - achiveddPercent
                


                _achived_ = Math.round(achiveddPercent * 10) / 10;
                _goal_ = Math.round(goalPercent * 10) / 10;

                if(_achived_>=100){
                  setAllert(true,app.dashboard.currentMachineSelected,app.dashboard.machineSelectName)
                }else{
                  setAllert(false,app.dashboard.currentMachineSelected,app.dashboard.machineSelectName)

                }



                if(app.dashboard.chartInfromationMachine!=null){
                  if(app.dashboard.machineInfromation.goalPercent!=goalPercent&&app.dashboard.machineInfromation.achiveddPercent!=achiveddPercent){

                    app.dashboard.machineInfromation.achiveddPercent = achiveddPercent
                    app.dashboard.machineInfromation.goalPercent = goalPercent

                    const achived___ = Math.round(app.dashboard.machineInfromation.achiveddPercent * 10) / 10;
                    const goal___ = Math.round(app.dashboard.machineInfromation.goalPercent * 10) / 10;
                    
                    app.dashboard.chartInfromationMachine.updateSeries([achived___, goal___]);

                    app.dashboard.chartInfromationMachine.updateOptions({
                      plotOptions: {
                          pie: {
                              donut: {
                                  labels: {
                                      total: {
                                          formatter: function (w) {
                                              return achived___ + '%';
                                          }
                                      }
                                  }
                              }
                          }
                      }
                  });

                  }
                }else{
                  showAchivedChart(achiveddPercent, goalPercent)
                }



                // MACHINE
                if(app.dashboard.chartHistoryAmper!=null){

                  app.dashboard.chartHistoryAmper.updateSeries([response.data.visualData.machine.value * 2], true);
                  app.dashboard.chartHistoryAmper.updateOptions({
                      plotOptions: {
                          radialBar: {
                              dataLabels: {
                                  value: {
                                      formatter: function () {
                                          return response.data.visualData.machine.value ;
                                      }
                                  }
                              }
                          }
                      }
                  })

                }else{
                  showHistoryAmperChart(response.data.visualData.machine.value)
                }


                if(app.dashboard.chartHistoryUsed!=null){

                    const values = response.data.visualData.machine.history.values
                    const historyData = response.data.visualData.machine.history;
                    const formattedData = historyData.labels.map((time, index) => {
                      return { 
                        x: time, 
                        y: parseFloat(historyData.values[index])
                      };
                    });



                    const maxVal = (Math.max(...values) + 5);
                    app.dashboard.chartHistoryUsed.updateOptions({
                      yaxis: {
                        labels: {
                          show: false
                        },
                        min: 0,
                        max: maxVal,
                        tickAmount: 4
                      }
                    });

                    app.dashboard.chartHistoryUsed.updateSeries([{
                      data: [...app.dashboard.chartHistoryUsed.w.config.series[0].data.slice(formattedData.length), ...formattedData]
                    }]);

                }else{
                  showHistoryUsedChart(response.data.visualData.machine.history)
                }


                // RPM
                if(app.dashboard.chartHistoryRpm!=null){

                  var persentase = (response.data.visualData.rpm.value / 2000) * 100;
                  app.dashboard.chartHistoryRpm.updateSeries([persentase], true);
                  app.dashboard.chartHistoryRpm.updateOptions({
                      plotOptions: {
                          radialBar: {
                              dataLabels: {
                                  value: {
                                      formatter: function () {
                                        return response.data.visualData.rpm.value;
                                      }
                                  }
                              }
                          }
                      }
                  })

                }else{
                  chartHistoryRpm(response.data.visualData.rpm.value)
                }



                if(app.dashboard.chartHistoryRpmUsed!=null){

                    const values = response.data.visualData.rpm.history.values
                    const historyData = response.data.visualData.rpm.history;
                    const formattedData = historyData.labels.map((time, index) => {
                      return { 
                        x: time, 
                        y: parseFloat(historyData.values[index])
                      };
                    });



                    const maxVal = (Math.max(...values) + 5);
                    app.dashboard.chartHistoryRpmUsed.updateOptions({
                      yaxis: {
                        labels: {
                          show: false
                        },
                        min: 0,
                        max: maxVal,
                        tickAmount: 4
                      }
                    });

                    app.dashboard.chartHistoryRpmUsed.updateSeries([{
                      data: [...app.dashboard.chartHistoryRpmUsed.w.config.series[0].data.slice(formattedData.length), ...formattedData]
                    }]);

                }else{
                  showHistoryUsedChart(response.data.visualData.rpm.history)
                }



                // TEMPRATURE
                if(app.dashboard.chartHistoryTemperature!=null){

                  app.dashboard.chartHistoryTemperature.updateSeries([response.data.visualData.temperature.value], true);
                  app.dashboard.chartHistoryTemperature.updateOptions({
                      plotOptions: {
                          radialBar: {
                              dataLabels: {
                                  value: {
                                      formatter: function () {
                                        return response.data.visualData.temperature.value;
                                      }
                                  }
                              }
                          }
                      }
                  })

                }else{
                  chartHistoryTemperature(response.data.visualData.temperature.value)
                }



                if(app.dashboard.chartHistoryTemperatureUsed!=null){

                    const values = response.data.visualData.temperature.history.values
                    const historyData = response.data.visualData.temperature.history;
                    const formattedData = historyData.labels.map((time, index) => {
                      return { 
                        x: time, 
                        y: parseFloat(historyData.values[index])
                      };
                    });



                    const maxVal = (Math.max(...values) + 5);
                    app.dashboard.chartHistoryTemperatureUsed.updateOptions({
                      yaxis: {
                        labels: {
                          show: false
                        },
                        min: 0,
                        max: maxVal,
                        tickAmount: 4
                      }
                    });

                    app.dashboard.chartHistoryTemperatureUsed.updateSeries([{
                      data: [...app.dashboard.chartHistoryTemperatureUsed.w.config.series[0].data.slice(formattedData.length), ...formattedData]
                    }]);

                }else{
                  chartHistoryTemperatureUsed(response.data.visualData.temperature.history)
                }



            },
            error: () => {

            }
          })


      }



      function showAchivedChart(achived,goal)
      {

          if(app.dashboard.chartInfromationMachine!=null){
            app.dashboard.chartInfromationMachine.destroy()
            app.dashboard.chartInfromationMachine = null
          }
          achived = Math.round(achived * 10) / 10;
          goal = Math.round(goal * 10) / 10;
          const chartOrderStatistics = document.querySelector('#achivedChart'),
          orderChartConfig = {
            chart: {
              height: 265,
              width: 230,
              type: 'donut'
            },
            labels: ['Time Now', 'Target Time'],
            series: [achived, goal],
            colors: ["#ff3e1d","#009966"],
            stroke: {
              width: 5,
              colors: "#fff"
            },
            dataLabels: {
              enabled: false,
              formatter: function (val, opt) {
                return parseInt(val) + '%';
              }
            },
            legend: {
              show: false
            },
            grid: {
              padding: {
                top: 0,
                bottom: 0,
                right: 15
              }
            },
            plotOptions: {
              pie: {
                donut: {
                  size: '60%',
                  labels: {
                    show: true,
                    value: {
                      fontSize: '1.5rem',
                      fontFamily: 'Public Sans',
                      color: "#566a7f",
                      offsetY: -15,
                      formatter: function (val) {
                        return parseInt(val) + '%';
                      }
                    },
                    name: {
                      offsetY: 20,
                      fontFamily: 'Public Sans'
                    },
                    total: {
                      show: true,
                      fontSize: '0.8125rem',
                      color: "#a1acb8",
                      label: 'Time Now',
                      formatter: function (w) {
                        return achived + '%';
                      }
                    }
                  }
                }
              }
            }
          };
          app.dashboard.chartInfromationMachine = new ApexCharts(chartOrderStatistics, orderChartConfig);
          app.dashboard.chartInfromationMachine.render();
      }


      // value machine
      function showHistoryAmperChart(value = 0)
      {

        var options = {
            series: [value*2],
            chart: {
                type: 'radialBar',
                height: 250,
                animations: {
                    enabled: true,
                    easing: 'easeinout', // Efek transisi
                    speed: 800, // Kecepatan animasi dalam milidetik
                    animateGradually: {
                        enabled: true,
                        delay: 150, // Delay antara perubahan nilai
                    },
                    dynamicAnimation: {
                        enabled: true,
                        speed: 1000, // Kecepatan perubahan nilai
                    }
                }
            },
            plotOptions: {
                radialBar: {
                    max: 50,
                    startAngle: -140,
                    endAngle: 140,
                    track: {
                        background: "#e5e7eb",
                        strokeWidth: '97%',
                    },
                    dataLabels: {
                        name: {
                            show: true,
                            fontSize: '16px',
                            offsetY: -10,
                            color: '#009966' // Warna label 'Current'
                        },
                        value: {
                            fontSize: '22px',
                            offsetY: 5,
                            formatter: function(val) {
                                return value
                            }
                        }
                    }
                }
            },
            fill: {
                colors: ['#009966'], // Warna hijau
            },
            labels: ['A'],
        };

        if(app.dashboard.chartHistoryAmper!=null){
          app.dashboard.chartHistoryAmper.destroy()
        }

        app.dashboard.chartHistoryAmper = new ApexCharts(document.querySelector("#historyAmper"), options);
        app.dashboard.chartHistoryAmper.render();
      }


      // value rpm
      function chartHistoryRpm(value = 0)
      {

          var persentase = (value / 2000) * 100;
          var options = {
            series: [persentase],
            chart: {
                type: 'radialBar',
                height: 250,
            },
            plotOptions: {
                radialBar: {
                    max: 50,
                    startAngle: -140,
                    endAngle: 140,
                    track: {
                        background: "#e5e7eb",
                        strokeWidth: '97%',
                    },
                    dataLabels: {
                        name: {
                            show: true,
                            fontSize: '16px',
                            offsetY: -10,
                            color: '#009966' // Warna label 'Current'
                        },
                        value: {
                            fontSize: '22px',
                            offsetY: 5,
                            formatter: function(val) {
                                return value
                            }
                        }
                    }
                }
            },
            fill: {
                colors: ['#009966'], // Warna hijau
            },
            labels: ['Rpm'],
        };

        if(app.dashboard.chartHistoryRpm!=null){
          app.dashboard.chartHistoryRpm.destroy()
        }

        app.dashboard.chartHistoryRpm = new ApexCharts(document.querySelector("#chartHistoryRpm"), options);
        app.dashboard.chartHistoryRpm.render();
      }



      // value temperature
      function chartHistoryTemperature(value = 0)
      {

          var options = {
            series: [value],
            chart: {
                type: 'radialBar',
                height: 250,
            },
            plotOptions: {
                radialBar: {
                    max: 50,
                    startAngle: -140,
                    endAngle: 140,
                    track: {
                        background: "#e5e7eb",
                        strokeWidth: '97%',
                    },
                    dataLabels: {
                        name: {
                            show: true,
                            fontSize: '16px',
                            offsetY: -10,
                            color: '#009966' // Warna label 'Current'
                        },
                        value: {
                            fontSize: '22px',
                            offsetY: 5,
                            formatter: function(val) {
                                return value; // Satuan Ampere
                            }
                        }
                    }
                }
            },
            fill: {
                colors: ['#009966'], // Warna hijau
            },
            labels: ['°C'],
        };

        if(app.dashboard.chartHistoryTemperature!=null){
          app.dashboard.chartHistoryTemperature.destroy()
        }

        app.dashboard.chartHistoryTemperature = new ApexCharts(document.querySelector("#chartHistoryTemperature"), options);
        app.dashboard.chartHistoryTemperature.render();
      }



      // history machine
      function showHistoryUsedChart({labels,values})
      {
        
        
        const incomeChartEl = document.querySelector('#historyUsed'),
          incomeChartConfig = {
            series: [
              {
                data: values
              }
            ],
            chart: {
              height: 215,
              parentHeightOffset: 0,
              parentWidthOffset: 0,
              toolbar: {
                show: false
              },
              type: 'area'
            },
            dataLabels: {
              enabled: false
            },
            stroke: {
              width: 2,
              curve: 'straight' // smooth
            },
            legend: {
              show: false
            },
            markers: {
              size: 6,
              colors: 'transparent',
              strokeColors: 'transparent',
              strokeWidth: 4,
              discrete: [
                {
                  fillColor: config.colors.white,
                  seriesIndex: 0,
                  dataPointIndex: 9,
                  strokeColor: "#009966",
                  strokeWidth: 2,
                  size: 6,
                  radius: 8
                }
              ],
              hover: {
                size: 7
              }
            },
            colors: ["#009966"],
            fill: {
              type: 'gradient',
              gradient: {
                shade: undefined,
                shadeIntensity: 0.6,
                opacityFrom: 0.5,
                opacityTo: 0.25,
                stops: [0, 95, 100]
              }
            },
            grid: {
              borderColor: "#eceef1",
              strokeDashArray: 3,
              padding: {
                top: -20,
                bottom: -8,
                left: -10,
                right: 8
              }
            },
            xaxis: {
              categories: labels,
              axisBorder: {
                show: false
              },
              axisTicks: {
                show: false
              },
              labels: {
                show: true,
                style: {
                  fontSize: '13px',
                  colors: "#a1acb8"
                }
              }
            },
            yaxis: {
              labels: {
                show: false
              },
              min: 0,
              max: (Math.max(...values) + 5),
              tickAmount: 4
            }
          };

          if(app.dashboard.chartHistoryUsed!=null){
            app.dashboard.chartHistoryUsed.destroy()
          }

          app.dashboard.chartHistoryUsed = new ApexCharts(incomeChartEl, incomeChartConfig);
          app.dashboard.chartHistoryUsed.render();

      }


      // history remperature
      function chartHistoryTemperatureUsed({labels,values})
      {
        
        const incomeChartEl = document.querySelector('#chartHistoryTemperatureUsed'),
          incomeChartConfig = {
            series: [
              {
                data: values
              }
            ],
            chart: {
              height: 215,
              parentHeightOffset: 0,
              parentWidthOffset: 0,
              toolbar: {
                show: false
              },
              type: 'area'
            },
            dataLabels: {
              enabled: false
            },
            stroke: {
              width: 2,
              curve: 'straight'
            },
            legend: {
              show: false
            },
            markers: {
              size: 6,
              colors: 'transparent',
              strokeColors: 'transparent',
              strokeWidth: 4,
              discrete: [
                {
                  fillColor: config.colors.white,
                  seriesIndex: 0,
                  dataPointIndex: 9,
                  strokeColor: "#009966",
                  strokeWidth: 2,
                  size: 6,
                  radius: 8
                }
              ],
              hover: {
                size: 7
              }
            },
            colors: ["#009966"],
            fill: {
              type: 'gradient',
              gradient: {
                shade: undefined,
                shadeIntensity: 0.6,
                opacityFrom: 0.5,
                opacityTo: 0.25,
                stops: [0, 95, 100]
              }
            },
            grid: {
              borderColor: "#eceef1",
              strokeDashArray: 3,
              padding: {
                top: -20,
                bottom: -8,
                left: -10,
                right: 8
              }
            },
            xaxis: {
              categories: labels,
              axisBorder: {
                show: false
              },
              axisTicks: {
                show: false
              },
              labels: {
                show: true,
                style: {
                  fontSize: '13px',
                  colors: "#a1acb8"
                }
              }
            },
            yaxis: {
              labels: {
                show: false
              },
              min: 0,
              max: (Math.max(...values) + 5),
              tickAmount: 4
            }
          };

          if(app.dashboard.chartHistoryTemperatureUsed!=null){
            app.dashboard.chartHistoryTemperatureUsed.destroy()
          }

          app.dashboard.chartHistoryTemperatureUsed = new ApexCharts(incomeChartEl, incomeChartConfig);
          app.dashboard.chartHistoryTemperatureUsed.render();

      }


      // history rpm
      function chartHistoryRpmUsed({labels,values})
      {
        
        const incomeChartEl = document.querySelector('#chartHistoryRpmUsed'),
          incomeChartConfig = {
            series: [
              {
                data: values
              }
            ],
            chart: {
              height: 215,
              parentHeightOffset: 0,
              parentWidthOffset: 0,
              toolbar: {
                show: false
              },
              type: 'area'
            },
            dataLabels: {
              enabled: false
            },
            stroke: {
              width: 2,
              curve: 'straight'
            },
            legend: {
              show: false
            },
            markers: {
              size: 6,
              colors: 'transparent',
              strokeColors: 'transparent',
              strokeWidth: 4,
              discrete: [
                {
                  fillColor: config.colors.white,
                  seriesIndex: 0,
                  dataPointIndex: 9,
                  strokeColor: "#009966",
                  strokeWidth: 2,
                  size: 6,
                  radius: 8
                }
              ],
              hover: {
                size: 7
              }
            },
            colors: ["#009966"],
            fill: {
              type: 'gradient',
              gradient: {
                shade: undefined,
                shadeIntensity: 0.6,
                opacityFrom: 0.5,
                opacityTo: 0.25,
                stops: [0, 95, 100]
              }
            },
            grid: {
              borderColor: "#eceef1",
              strokeDashArray: 3,
              padding: {
                top: -20,
                bottom: -8,
                left: -10,
                right: 8
              }
            },
            xaxis: {
              categories: labels,
              axisBorder: {
                show: false
              },
              axisTicks: {
                show: false
              },
              labels: {
                show: true,
                style: {
                  fontSize: '13px',
                  colors: "#a1acb8"
                }
              }
            },
            yaxis: {
              labels: {
                show: false
              },
              min: 0,
              max: (Math.max(...values) + 5),
              tickAmount: 4
            }
          };

          if(app.dashboard.chartHistoryRpmUsed!=null){
            app.dashboard.chartHistoryRpmUsed.destroy()
          }

          app.dashboard.chartHistoryRpmUsed = new ApexCharts(incomeChartEl, incomeChartConfig);
          app.dashboard.chartHistoryRpmUsed.render();

      }


      function convertSecondsToTime(seconds)
      {
          let hours = Math.floor(seconds / 3600);
          let minutes = Math.floor((seconds % 3600) / 60); 

          return `${hours}.${minutes}`;
      }


      function formatDateID(tanggal) {
          let bagian = tanggal.split("-");
          return `${bagian[2]}-${bagian[1]}-${bagian[0]}`; 
      }


      $(".btn_export").on('click',function(){
        if(app.dashboard.currentMachineSelected==null){
            iziToast.show({
              title: 'Error',
              message: "The machine hasn't been selected, pleas select the machine ",
              color: 'red',
              position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
            });
            return
          }


          if($('input[name="production_date"]').val()==""){
            iziToast.show({
              title: 'Error',
              message: "Production date can't empty, pleas set production date",
              color: 'red',
              position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
            });
            return
          }

          window.open(`<?= base_url() ?>dashboard/export?id=${app.dashboard.currentMachineSelected}&production_date=${$('input[name="production_date"]').val()}`,'_blank');
      })

      function setAllert(isShow, id, name)
      {
        if(isShow){
          $("#danger_information").html(`<div class="row p-0 m-0 w-100">
                        <div class="col-12 col-lg-8">
                            <b>Alert! </b><br>
                            ${name} has reached or exceeded its operational limits. <br>
                            Please perform maintenance immediately and click the reset button on the side after the repairs have been completed.
                        </div>
                        <div class="col-12 col-lg-4 d-flex justify-content-end align-items-end">
                            <button data-id="${id}" class="btn-reset-machine btn btn-sm btn-danger">Reset</button>
                        </div>
                    </div>`)
          $("#danger_information").fadeIn(255)

        }else{
          $("#danger_information").fadeOut(255)
        }
      }


      $("#danger_information").delegate('.btn-reset-machine', 'click', function(event) {
          
        Swal.fire({
          title:"Reset Machine?",
          text:"Do you want to reset this machine",
          icon:"question",
          showCancelButton:!0,
          confirmButtonColor:"#009966",
          cancelButtonText:"Cancel",
          confirmButtonText:"Reset"
        }).then((result) => {
                
          if (result.isConfirmed) {
              
            $.ajax({
              url: `${base_url}dashboard/reset`,
              type: 'GET',
              dataType: 'JSON',
              data: {
                id: app.dashboard.currentMachineSelected,
              },
              success: (response) => {

                if(response.success){

                  setAllert(false)

                  iziToast.show({
                    title: 'Success',
                    message: response.message,
                    color: 'green',
                    position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
                  });

                  setTimeout(()=>{
                    location.reload()
                  },1024)

                }else{
                  iziToast.show({
                    title: 'Error',
                    message: response.message,
                    color: 'red',
                    position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
                  });
                }

              },
              error: () => {

              }
            });

          }
        });

      });

    </script>
