<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) ?>')
      })


      $("#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();

          $('#machineSelect').append(`<option value="" disabled selected>Select the machine</option>`);
          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.machineSelected!=id){
                app.dashboard.machineSelectedName = name
                app.dashboard.machineSelected = id
              }
          }

      })



      $("#btn_show_data").on('click',function(e){
          e.preventDefault()
          if(app.dashboard.machineSelected==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: "Operation 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')

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

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

              setInfromation(response.data)
              setChartView(response.data)


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

            },
            error: () => {

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

            }
          })

      })



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

          if(app.dashboard.machineSelected==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.machineSelected,
              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
                });

                // resetMachineSelect()
                fetchNewData()

              }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 fetchNewData()
      {

          $.ajax({
            url: `${base_url}dashboard/machine`,
            type: 'GET',
            dataType: 'JSON',
            data: {
              id: app.dashboard.machineSelected,
              productionDate: app.dashboard.productionDate
            },
            success: (response) => {

              setInfromation(response.data)
              setChartView(response.data)

            },
            error: () => {

            }
          })
      }


      function setInfromation(data)
      {
            const operation_date        = data.operation_date
            const total_operation_time  = formatFix2(data.total_operation_time)
            const operation_time_today  = formatFix2(data.operation_time_today)
            const average_current_today  = formatFix2(data.average_current_today)
            const average_operation_daily  = formatFix2(data.average_operation_daily)
            const average_temperature_today  = formatFix2(data.average_temperature_today)
            const average_rpm_today  = formatFix2(data.average_rpm_today)
            const target_time  = formatFix2(data.target_time)
            const colorStatus  = data.status.toUpperCase()=="ON" ? 'bg-warning' : 'bg-secondary' 
            const labelStatus  = data.status.toUpperCase()=="ON" ? "ON" : 'OFF'

            $(".label-operation-date").html(operation_date)
            $(".label-total-operation-time").html(`${convertToHourMinute(total_operation_time)} h`)
            $(".label-total-operation-time-today").html(`${convertToHourMinute(operation_time_today)} h`)

            $(".label-average-temperature-today").html(`${average_temperature_today} C`)
            $(".label-average-rpm-today").html(`${average_rpm_today} rpm`)

            $(".label-average-current-today").html(`${average_current_today} amp`)
            $(".label-average-operation-daily").html(`${convertToHourMinute(average_operation_daily)} h`)

            $(".label-target-time").html(`<span class="badge rounded bg-success">${convertToHourMinute(target_time)} Hours</span>`)
            $(".label-time-now").html(`<span class="badge rounded bg-danger">${convertToHourMinute(total_operation_time)} Hours</span>`)
            $(".label-status-machine").html(`<span class="badge rounded ${colorStatus}">${labelStatus}</span>`)
      }

      function setChartView(data)
      {
        
        const history = data.history
        setChartInfromation(data)

        setCartLastedCurrent(history.current)
        setChartHistoryCurrent(history.current)

        setCartLastedRpm(history.rpm)
        setChartHistoryRpm(history.rpm)

        setCartLastedTemperature(history.temperature)
        setChartHistoryTemperature(history.temperature)


      }



      function setChartInfromation(data)
      {

          let goal        = parseFloat(data.target_time)
          let achived     = parseFloat(data.total_operation_time)
          let has = formatPercentage(((achived / goal) * 100) );
          let hasnt = formatPercentage( (100 - has) );
          
          if(achived>=goal){
            setAllert(true)
          }else{
            setAllert(false)
          }
          
          has   = Number(has)
          hasnt = Number(hasnt)

          if(app.dashboard.chartInfromation!=null){
            
            
            if(app.dashboard.goal!=goal||app.dashboard.achived!=achived){
              
              app.dashboard.goal = goal
              app.dashboard.achived = achived

              goal      = formatFix2(goal)
              achived   = formatFix2(achived)

              app.dashboard.chartInfromation.updateSeries([has,hasnt]);

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

            }
          }else{

            app.dashboard.goal = goal
            app.dashboard.achived = achived

            goal      = formatFix2(goal)
            achived   = formatFix2(achived)
            
            const chartOrderStatistics = document.querySelector('#achivedChart'),
            orderChartConfig = {
              chart: {
                height: 265,
                width: 230,
                type: 'donut'
              },
              labels: ['Time Now', 'Target Time'],
              series: [has, hasnt],
              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 has + '%';
                        }
                      }
                    }
                  }
                }
              }
            };
            app.dashboard.chartInfromation = new ApexCharts(chartOrderStatistics, orderChartConfig);
            app.dashboard.chartInfromation.render();

          }

      }



      function setCartLastedCurrent(data)
      {

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

            const value = parseFloat(data.lasted)
            app.dashboard.cartLastedCurrent.updateSeries([value * 2], true);
            app.dashboard.cartLastedCurrent.updateOptions({
                plotOptions: {
                    radialBar: {
                        dataLabels: {
                            value: {
                                formatter: function () {
                                    return value ;
                                }
                            }
                        }
                    }
                }
            })

          }else{
            const value = parseFloat(data.lasted)
            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.cartLastedCurrent!=null){
              app.dashboard.cartLastedCurrent.destroy()
            }

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


          }

      }

      function setCartLastedRpm(data)
      {

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

            const value = parseFloat(data.lasted)
            var persentase = (value / 2000) * 100;
            app.dashboard.cartLastedRpm.updateSeries([persentase], true);
            app.dashboard.cartLastedRpm.updateOptions({
                plotOptions: {
                    radialBar: {
                        dataLabels: {
                            value: {
                                formatter: function () {
                                  return value;
                                }
                            }
                        }
                    }
                }
            })

          }else{
            
            const value = parseFloat(data.lasted)
            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.cartLastedRpm!=null){
              app.dashboard.cartLastedRpm.destroy()
            }

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

          }
      }

      function setCartLastedTemperature(data)
      {


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

            const value = parseFloat(data.lasted)
            app.dashboard.cartLastedTemperature.updateSeries([value], true);
            app.dashboard.cartLastedTemperature.updateOptions({
                plotOptions: {
                    radialBar: {
                        dataLabels: {
                            value: {
                                formatter: function () {
                                  return value;
                                }
                            }
                        }
                    }
                }
            })

          }else{
            
            const value = parseFloat(data.lasted)
            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.cartLastedTemperature!=null){
              app.dashboard.cartLastedTemperature.destroy()
            }

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

          }

      }




      function setChartHistoryCurrent(data)
      {

          
          if(app.dashboard.chartHistoryCurrent!=null){
              
              // if(data.labels.length>0||data.values.length>0){
              //   app.dashboard.chartHistoryCurrent.destroy()
              //   return
              // }

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



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

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

          }else{
            
            const values = data.values.reverse()
            const labels = data.labels.reverse()
            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.chartHistoryCurrent!=null){
              app.dashboard.chartHistoryCurrent.destroy()
            }

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


          }
      }


      function setChartHistoryRpm(data)
      {        

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

            // if(data.labels.length>0||data.values.length>0){
            //   app.dashboard.chartHistoryRpm.destroy()
            //   return
            // }

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



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

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

        }else{
          
          const values = data.values.reverse()
          const labels = data.labels.reverse()
          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' // 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.chartHistoryRpm!=null){
            app.dashboard.chartHistoryRpm.destroy()
          }

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

        }

      }


      function setChartHistoryTemperature(data)
      {

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

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



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

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

          }else{
            

            const values = data.values.reverse()
            const labels = data.labels.reverse()     
            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.chartHistoryTemperature!=null){
              app.dashboard.chartHistoryTemperature.destroy()
            }

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

          }
      }








      function resetMachineSelect()
      {

        // reset lable infromation machine
        $(".label-machine-name").html('-')
        $(".label-machine-no").html('-')
        app.dashboard.lineSelected = null
        app.dashboard.machineSelected = null
        app.dashboard.machineSelectedName = null

        // reset production date
        $("input[name=production_date]").val('')


        // reset card information machine
        $(".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(`-`)
        $(".label-status-machine").html(`-`)

        // setAllert(false)
        app.dashboard.machineSelected = null

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


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


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


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


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


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


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

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

        }
        app.dashboard.isRealTime = null

      }


      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>
                            ${app.dashboard.machineSelectedName} 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="${app.dashboard.machineSelected}" 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.machineSelected,
                },
                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: () => {

                }
              });

            }
          });

      });




      function convertToHourMinute(decimalHour) {
          decimalHour = Number(decimalHour)

          let jam = Math.floor(decimalHour); // Ambil jam
          let menit = Math.round((decimalHour - jam) * 60); // Konversi sisa ke menit

          if (menit === 0) {
              return `${jam}`; // Jika menitnya 0, hanya tampilkan jam
          } else {
              return `${jam}.${menit.toString().padStart(2, "0")}`; // Format jam.menit
          }
      }


      function formatFix2(time)
      {
        time = parseFloat(time)
        return time % 1 === 0 ? time.toString() : time.toFixed(2);
      }


      function formatPercentage(value) {
          return value % 1 === 0 ? value.toString() : parseFloat(value.toFixed(2));
      }


      $(".btn_export").on('click',function(){
        if(app.dashboard.machineSelected==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
          // }

          const type = $(this).attr('data-type')

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


    </script>
