(function() {
  'use strict';

  angular
    .module('vetApp')
    .controller('reportesCuponesController', reportesCuponesController);

  reportesCuponesController.$inject = ['$scope', '$http', '$window'];
  function reportesCuponesController($scope, $http, $window) {
    $scope.mostrarTablaConResultados = false
    $scope.boolCargando = false

    activate();

    function activate() {
      initializeDatePicker()
      consultarCupones()
    }

    $scope.consultarCupones = async () => {
      $scope.mostrarTablaConResultados = false
      $scope.boolCargando = true
      const parametros = { cual: 'consultarUsuarioCupon' }
      $scope.reporte?.fec_inicio !== undefined && (parametros.fec_inicio = moment($scope.reporte.fec_inicio).format('Y-MM-DD'))
      $scope.reporte?.fec_fin !== undefined && (parametros.fec_fin = moment($scope.reporte.fec_fin).format('Y-MM-DD'))
      $scope.reporte?.des_cupon !== undefined && (parametros.des_cupon = $scope.reporte.des_cupon)

      console.log(parametros)
      const msg = await $http.post('app/ws/ws_api.php', JSON.stringify(parametros))
      $scope.cupones = msg.data.cupones
      $scope.mostrarTablaConResultados = true
      $scope.boolCargando = false
    }

    $scope.descargarReporte = () => {
      let and = '?'
      let filtros = ''

      if ($scope.reporte?.fec_inicio !== undefined) {
        filtros += `${and}fec_inicio=${moment($scope.reporte.fec_inicio).format('Y-MM-DD')}`
        and = '&'
      }

      if ($scope.reporte?.fec_fin !== undefined) {
        filtros += `${and}fec_fin=${moment($scope.reporte.fec_fin).format('Y-MM-DD')}`
        and = '&'
      }

      if ($scope.reporte?.des_cupon !== undefined) {
        filtros += `${and}des_cupon=${$scope.reporte.des_cupon}`
        and = '&'
      }

      $window.open(`app/excel/bbdd_coupons.php${filtros}`)
    }

    async function consultarCupones () {
      const parametros = { cual: 'consultarCupon' }
      const msg = await $http.post('app/ws/ws_api.php', JSON.stringify(parametros))
      $scope.cupones_select = msg.data?.cupones ?? []
    }

    function initializeDatePicker () {
      // sin usar jquery ja
      document.addEventListener('DOMContentLoaded', function () {
        const elems = document.querySelectorAll('.datepicker');
        const instances = M.Datepicker.init(elems, options);
      });
    }
  }
})();