<?php
require_once("../Connection.php");

class Nomina10001 extends Connection
{
   // private $response;
   // function __construct() {
   //    $this->response = $this->DefaultResponse();
   // }

   function Index($ejercicio) {
      $response = $this->DefaultResponse();

      try {
         $query = "SELECT codigoempleado, nombre, apellidopaterno, apellidomaterno, UPPER(CONCAT(rfc,CONVERT(varchar,fechanacimiento,12),homoclave)) AS rfc, UPPER(CONCAT(curpi,CONVERT(varchar,fechanacimiento,12),curpf)) AS curp, fechaalta
         FROM nom10001
         WHERE estadoempleado IN ('A','R');";
         // AND CONVERT(char(4), DATEPART (Year, fechaalta)) = '$ejercicio';";
         $result = $this->Select($query,true);
         $response = $this->CorrectResponse();
         $response["message"] = "Peticion satisfactoria | registros encontrados.";
         $response["data"] = $result;
         $this->Close();

      } catch (Exception $e) {
         $this->Close();
         $mensaje_error = "Error: ".$e->getMessage();
         $response = $this->CatchResponse($mensaje_error);
      }
      die(json_encode($response));
   }

   function SyncInfo($CONN_OBJ,$data) {
      $response = $this->DefaultResponse();

      try {
         $query = "SELECT * FROM USR_Compaq";
         $registersInDBConfig = $this->Select($query, true);
         $query = "INSERT INTO USR_Compaq(codigoEmpleado, nombreE, apellidoP, apellidoM, Rfc, Curp, fechaAlta) VALUES ";

         $toInsert = [];
         $values = false;

         if (empty($registersInDBConfig)) {
            /** Registar todo */
            foreach ($data as $reg) {
               array_push($toInsert, $reg);
               $add = true;
            }
         } else {
            /** Registrar los que no existan */
            $toUpdate = [];
            $toDelete = [];
            foreach ($data as $reg) {
               $add = true;
               // $update = false;
               // $delete = true;
               // echo "reg: $reg[codigoEmpleado]";
               foreach ($registersInDBConfig as $regDBInfo) {
                  /** si el registro existe, no se agrega */
                  if ($reg["codigoEmpleado"] == $regDBInfo["codigoEmpleado"]) {
                     $add = false;
                     /** pero si existe, checamos su estado para ver si se actualiza */
                     // if ($reg["estadoempleado"] != $regDBInfo["estadoempleado"]) {
                     //    $update = true;
                     // }
                     continue;
                  }
               }
               if (!empty($add)) array_push($toInsert, $reg);
               // elseif ($update) array_push($toUpdate, $reg);
               // elseif ($delete) array_push($toDelete, $reg["codigoEmpleado"]);
            }
         }
         if (!empty($toInsert)) {
            $count=0; 
            foreach ($toInsert as $reg) {
               $count += 1;
               $query .= "('$reg[codigoEmpleado]','$reg[nombreE]','$reg[apellidoP]','$reg[apellidoM]','$reg[Rfc]','$reg[Curp]','$reg[fechaAlta]'),";
               $values = true;
               if ($count == 1000) {
                  $query = rtrim($query,",");
                  $query .= ";";
                  $result = $this->ExecuteQuery($query, array());
                  $this->Close();
                  $count=0; 
                  $query = "INSERT INTO USR_Compaq(codigoEmpleado, nombreE, apellidoP, apellidoM, Rfc, Curp, fechaAlta) VALUES ";
               }
            }
            if ($count > 0 && $count < 1000) {
               $query = rtrim($query,",");
               $query .= ";";
               $conn = new Connection($CONN_OBJ);
               $result = $conn->ExecuteQuery($query, array());
            }            
         }
         $response = $this->CorrectResponse();
         $text = "Se sincronizaron ".number_format(count($toInsert))." registros.";
         if (count($toInsert) == 0) {
            $text = "Los registros de ésta tabla ya están sincronizados.";
            $response["alert_icon"] = "info";
         }
         $response["message"] = "Peticion satisfactoria | registros sincronizados.";
         $response["alert_text"] = $text;
         $response["data"] = [];
         $this->Close();

      } catch (Exception $e) {
         $this->Close();
         $mensaje_error = "Error: ".$e->getMessage();
         $response = $this->CatchResponse($mensaje_error);
      }
      die(json_encode($response));
   }



// CONSULTAS PARA EL PUNTO 2
// --SELECT * FROM USR_Compaq
// --group by codigoEmpleado;

//  --truncate table USR_Compaq;

   // select * from USR_Compaq where Rfc not in(SELECT DISTINCT (CONCAT( Rfc,Homoclave)) FROM DECL_DatosGenerales where Homoclave is not null and Rfc is not null) order by fechaAlta;

   // select * from DECL_DatosGenerales where PrimerApellido='MARIN' AND SegundoApellido='GUTIERREZ'; -- Rfc='MAGM750928159';
// CONSULTAS PARA EL PUNTO 2
}