🌹🏠🌹？》《》？《》？<?php

class Pdcabe extends Base
{
public $empresa;
public $tdoc;
public $letra;
public $sucur;
public $numero;
public $codigo_cliente;
public $letra_fc;
public $sucur_fc;
public $nro_factura;
public $fecha_fc;
public $sucursal_cliente;
public $vendedor;
public $nro_oc;
public $ultimo_estado;
public $fecha_doc;
public $fecha_ing;
public $fecha_disp;
public $fecha_difer;
public $fecha_ini_comp;
public $fecha_prev_ent;
public $fecha_conf_ent;
public $fecha_difer_cliente;
public $fecha_entrega;
public $interior;
public $tte;
public $espera;
public $espera_logistica;
public $espera_acceso;
public $contado;
public $retira;
public $turno;
public $fecha_pedido_turno;
public $fecha_turno;
public $estado;
public $bultos;
public $unidades;
public $volumen;
public $otros;
public $valor_declarado;
public $edificio;
public $obser;
public $usuario;
public $fecha_proc;
public $impreso;
public $etiquetado;
public $hora_pactada;
public $hora_entrega;
public $codigo_cliente_final;
public $prioridad;
public $cons_final;
public $fc_concepto;
public $directo;
public $nro_pd;
public $tipo_rm; // S: lleva cot ( blanco ) N: no lleva cot
public $sector;
public $documentado; // en N y cuando llega el remito fisico firmado pasa a S ( mas para interior )
public $empresa_cuit;

public $tdoc_retiro; // COL o RET
public $concepto_or; // 35 o 34
public $concepto_or_stk; // R02 / R03

// clientes_emp
public $cod_dest;
public $cliente;
public $direccion;
public $pais = "200";
public $provincia;
public $localidad;
public $cod_postal;
public $mail;
public $cuit;
public $tel;
public $codigo_cliente_ext;

public $cliente_final;
public $direccion_final;
public $pais_final = "200";
public $provincia_final;
public $localidad_final;
public $cod_postal_final;

// Solo detalle para OR.
public $d_articulo;
public $d_bultos;
public $d_unidades;
public $d_volumen;
public $d_otros;
public $d_estado;

// pdcabe_obser
public $o_obser;
public $o_obser_gl;

// Solo ped_ccr prop_ccr
public $d_condicion;
public $d_secuencia;
public $d_nro_item;
public $d_cod_cliente; // cod.cliente ped_ccr
public $d_cliente;
public $d_direccion;
public $d_provincia;
public $d_localidad;
public $d_cod_postal;
public $d_nro_lote;
public $d_serie;
public $d_concepto;
public $d_fecha_p_ent;
public $d_precio;

// cot_remito
public $cot_hruta_d;
public $cot;
public $cot_resultado;
public $cot_fecha_resp;
public $cot_hora_resp;
public $cot_estado;
public $cot_usuario;
public $cot_carga;

// Para ctrlremitos
public $campo = "";
public $valor_ant = "";
public $valor_act = "";
public $usuario_modif = "";
public $fecha_modif = "";
public $transf = 'S';
public $error = 0; // falso
public $msg_error;

// SigTrac
public $nro_track;
public $nro_track_int;
public $tipo_pedido;
public $usa_trackeo;

public $st_operacion; // I: ingreso pedido P: preparacion D: expedicion E: Entregado
public $st_titulo;
public $st_nota;
public $st_condicion;
public $st_encuesta;
public $st_mail_comprador;
public $st_mail_vendedor;
public $st_contenido;

function __construct($r_empresa,$r_tdoc,$r_letra,$r_sucur,$r_numero)
{  
//$this->conexion        = $r_base;
$this->empresa     = $r_empresa;
$this->tdoc        = $r_tdoc;
$this->letra       = $r_letra;
$this->sucur       = $r_sucur;
$this->numero      = $r_numero;
$this->nro_factura = 0;
$this->nro_pd      = $r_numero;
$this->bultos      = 0;
$this->unidades    = 0;
$this->volumen     = 0;
$this->otros       = 0;
$this->estado      = 2;
$this->impreso     = 0;
$this->d_secuencia = 1;
$this->ultimo_estado = 1; // ref_valores ultimo_estado
$this->prioridad     = 'N';
$this->espera_acceso = 'N';
$this->tipo_rm     = 'S';
$this->transf      = 'S';
$this->directo     = 'N';
// GBA y Bonafide no tiene Distr. Local
if ($r_empresa == 199 || $r_empresa == 213 ){
    $this->directo = 'S';
}
$this->d_condicion = 'C'; // inicializo en pendiente;
$this->nro_track_int   =  str_pad($r_empresa,3,'0',STR_PAD_LEFT).
                          $r_letra.
                          str_pad($r_sucur,5,'0',STR_PAD_LEFT).
                          str_pad($r_numero,10,'0',STR_PAD_LEFT);
$this->nro_track       = $this->nro_track_int;
$this->tipo_pedido = 'N'; // E con retiro en otro lado
$this->tdoc_retiro = 'OR';
$this->usa_trackeo = 'N';
$this->sector      = 1;
$this->documentado = 'N';

} 

function r_select_pdcabe()
{ 
$this->error     = 0;
$this->msg_error = "";
$p_sql_p="select * from pdcabe     
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}'";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
  $this->error     = 2;
  $this->msg_error = "01- Error. No se pudo leer [pdcabe] !! ";
  return;
}
$row=odbc_fetch_array($resultado);
if (!$row){
  $this->error     = 1;
  $this->msg_error = "02- Error. No se pudo leer [pdcabe] !!";
  return;
}
$this->nro_factura    = $row['nro_factura'];
$this->codigo_cliente = $row['codigo_cliente'];
$this->sucursal_cliente = $row['sucursal_cliente'];
$this->vendedor       = trim($row['vendedor']);
$this->nro_oc         = trim($row['nro_oc']);
$this->ultimo_estado  = $row['ultimo_estado'];
$this->fecha_doc      = date("d-m-Y",strtotime($row['fecha_doc']));
$this->fecha_ing      = date("d-m-Y",strtotime($row['fecha_ing']));
$this->fecha_disp     = "";
if (strlen($row['fecha_disp']) > 0 && $row['fecha_disp'] != '1900-01-01'){
  $this->fecha_disp     = date("d-m-Y",strtotime($row['fecha_disp']));  
}
$this->fecha_difer    = "";
if (strlen($row['fecha_difer']) > 0 && $row['fecha_difer'] != '1900-01-01'){
  $this->fecha_difer    = date("d-m-Y",strtotime($row['fecha_difer']));
}
$this->fecha_ini_comp = "";
if (strlen($row['fecha_ini_comp']) > 0 && $row['fecha_ini_comp'] != '1900-01-01'){
  $this->fecha_ini_comp = date("d-m-Y",strtotime($row['fecha_ini_comp']));
}
$this->fecha_prev_ent = "";
if (strlen($row['fecha_prev_ent']) > 0  && $row['fecha_prev_ent'] != '1900-01-01'){
  $this->fecha_prev_ent = date("d-m-Y",strtotime($row['fecha_prev_ent']));
}
$this->fecha_conf_ent = "";
if (strlen($row['fecha_conf_ent']) > 0 && $row['fecha_conf_ent'] != '1900-01-01'){
  $this->fecha_conf_ent = date("d-m-Y",strtotime($row['fecha_conf_ent']));  
}
$this->fecha_difer_cliente = "";
if (strlen($row['fecha_difer_cliente']) > 0 && $row['fecha_difer_cliente'] != '1900-01-01'){
  $this->fecha_difer_cliente = date("d-m-Y",strtotime($row['fecha_difer_cliente']));
}
$this->fecha_entrega = "";
if (strlen($row['fecha_entrega']) > 0 && date("Y", strtotime($row['fecha_entrega'])) > 1970 ){
  $this->fecha_entrega = date("d-m-Y",strtotime($row['fecha_entrega']));
}
$this->interior      = $row['interior'];
$this->tte           = trim($row['tte']);
$this->sector        = trim($row['sector']);
$this->espera        = $row['espera'];
$this->espera_logistica = $row['espera_logistica'];
$this->espera_acceso = $row['espera_acceso'];
$this->contado       = $row['contado'];
$this->retira        = $row['retira'];
$this->turno         = $row['turno'];
$this->fecha_pedido_turno = "";
if (strlen($row['fecha_pedido_turno']) > 0 && $row['fecha_pedido_turno'] != '1900-01-01'){
  $this->fecha_pedido_turno = date("d-m-Y",strtotime($row['fecha_pedido_turno']));
}
$this->fecha_turno   = "";
if (strlen($row['fecha_turno']) > 0 && $row['fecha_turno'] != '1900-01-01'){
  $this->fecha_turno   = date("d-m-Y",strtotime($row['fecha_turno']));
}
$this->estado        = $row['estado'];
$this->bultos        = $row['bultos'];
$this->unidades      = $row['unidades'];
$this->volumen       = sprintf("%0.6f",$row['volumen']);
$this->otros         = $row['otros'];
$this->valor_declarado = $row['valor_declarado'];
$this->edificio      = $row['edificio'];
$this->obser         = trim($row['obser']);
$this->impreso       = $row['impreso'];
$this->etiquetado    = $row['etiquetado'];
$this->hora_pactada  = $row['hora_pactada'];
$this->hora_entrega  = $row['hora_entrega'];
$this->codigo_cliente_final = $row['codigo_cliente_final'];
$this->prioridad     = $row['prioridad'];
$this->fc_concepto   = $row['fc_concepto'];
$this->nro_track     = $row['nro_track'];
$this->directo       = $row['directo'];
$this->nro_pd        = $row['nro_pd'];
$this->tipo_rm       = $row['tipo_rm'];
$this->sector        = $row['sector'];
$this->documentado   = $row['documentado'];
$this->empresa_cuit  = trim($row['cuit']);

$this->r_veo_tipo_pedido();

odbc_free_result($resultado);

$this->letra_fc = 'X';
$this->sucur_fc = 0;
$this->cons_final = 'N';
if ($this->tdoc != 'OR'){
   $p_sql_p = "select * from ing_ped 
       where empresa  = '{$this->empresa}'
         and letped   = '{$this->letra}'
         and sucped   = '{$this->sucur}'
         and nroped   = '{$this->numero}' ";
   $resultado=@odbc_exec($this->conexion,$p_sql_p);
   if (!$resultado){
      $this->error     = 2;
      $this->msg_error = "03- Error. No se pudo leer [ing_ped] !!";
      return;
   }
   $row=odbc_fetch_array($resultado);
   if ($row) {
      $this->letra_fc = $row['letdoc'];
      $this->sucur_fc = $row['sucdoc'];
      $this->cons_final = $row['cons_final'];
      $this->fecha_fc   = date("Ymd",strtotime($row['fecha_fc']));
   }
   odbc_free_result($resultado);
}

$this->o_obser    = "";
$this->o_obser_gl = "";
$p_sql_p="select * from pdcabe_obser
       where empresa  = '{$this->empresa}'
         and tdoc     = '{$this->tdoc}'
         and letra    = '{$this->letra}'
         and sucur    = '{$this->sucur}'
         and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
  $this->error     = 2;
  $this->msg_error = "04- Error. No se pudo leer [pdcabe_obser] !!";
  return;
}
$row=odbc_fetch_array($resultado);
if ($row){
  $this->o_obser    = trim($row['obser']);
  $this->o_obser_gl = trim($row['obser_gl']);
}

return;
}

function r_insert_cab() 
{
$this->error     = 0;
$this->msg_error = "";

$this->fecha_doc  = date("Ymd",strtotime($this->fecha_doc));
$this->fecha_ing  = date("Ymd",strtotime($this->fecha_ing));
$this->fecha_proc = date("Ymd H:i:s",strtotime($this->fecha_proc));
if (strlen($this->fecha_difer) > 0 ) $this->fecha_difer = date("Ymd",strtotime($this->fecha_difer));
if (strlen($this->fecha_turno) > 0 ) $this->fecha_turno = date("Ymd",strtotime($this->fecha_turno));
if (strlen($this->fecha_pedido_turno) > 0 ) $this->fecha_pedido_turno = date("Ymd",strtotime($this->fecha_pedido_turno));
if (strlen($this->fecha_disp) > 0 ) $this->fecha_disp = date("Ymd",strtotime($this->fecha_disp));
if (strlen($this->fecha_ini_comp) > 0 ) $this->fecha_ini_comp = date("Ymd",strtotime($this->fecha_ini_comp));

$p_sql_p2="insert into pdcabe values ( '{$this->empresa}','{$this->tdoc}' ,'{$this->letra}','{$this->sucur}','{$this->numero}',
                                      '{$this->nro_factura}','{$this->codigo_cliente}','{$this->sucursal_cliente}',
                                      '{$this->vendedor}','{$this->nro_oc}','{$this->ultimo_estado}',
                                      '{$this->fecha_doc}','{$this->fecha_ing}','{$this->fecha_disp}',
                                      '{$this->fecha_difer}','{$this->fecha_ini_comp}','{$this->fecha_prev_ent}',
                                      '{$this->fecha_conf_ent}','{$this->fecha_difer_cliente}','{$this->fecha_entrega}',
                                      '{$this->interior}','{$this->tte}','{$this->espera}','{$this->espera_logistica}',
                                      '{$this->contado}','{$this->retira}','{$this->turno}','{$this->fecha_pedido_turno}',
                                      '{$this->fecha_turno}','{$this->estado}',
                                      '{$this->bultos}','{$this->unidades}','{$this->volumen}','{$this->otros}',
                                      '{$this->valor_declarado}','{$this->edificio}','{$this->obser}',
                                      '{$this->usuario}','{$this->fecha_proc}','{$this->impreso}','{$this->etiquetado}',
                                      '{$this->hora_pactada}','{$this->hora_entrega}' ,'{$this->codigo_cliente_final}',
                                      '{$this->prioridad}','{$this->espera_acceso}','{$this->fc_concepto}',
                                      '{$this->nro_track}','{$this->directo}','{$this->nro_pd}','{$this->tipo_rm}',
                                      '{$this->sector}','{$this->documentado}','{$this->empresa_cuit}',0)";
$resultado=@odbc_exec($this->conexion,$p_sql_p2);
if (!$resultado) {
  $this->error     = 1;
  $this->msg_error = "05- Error. No se pudo insertar [pdcabe] !! ";
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "06- Error. No se pudo insertar [pdcabe]";
  return;  
}
odbc_free_result($resultado);

$p_sql_p2= "select * from pdcabe_tracking where nro_track_int = '{$this->nro_track_int}' ";
$this->r_select_fila($p_sql_p2,"pdcabe_tracking");
if ($this->error != 0 ){
    $p_sql_p2= "insert into pdcabe_tracking values ( '{$this->nro_track_int}','{$this->nro_track}','{$this->empresa}','{$this->tdoc}','{$this->letra}','{$this->sucur}','{$this->numero}',
                                              '1', '{$this->fecha_proc}','N' ) ";
    $resultado=@odbc_exec($this->conexion,$p_sql_p2);
    if (!$resultado) {
        $this->error     = 1;
        $this->msg_error = "07- Error. No se pudo insertar [pdcabe] !! ".$p_sql_p2;
        return;
    }
    if (odbc_num_rows($resultado) != 1){
        $this->error     = 1;
        $this->msg_error = "08- Error. No se pudo insertar [pdcabe]";
        return;
    }
    odbc_free_result($resultado);
    $this->error = 0;
    $this->msg_error = '';
}

return;
}

function r_select_pddeta()
{

$this->error     = 0;
$this->msg_error = "";
$p_sql_p="select * from pddeta     
       where empresa  = '{$this->empresa}'
         and tdoc     = '{$this->tdoc}'
         and letra    = '{$this->letra}'
         and sucur    = '{$this->sucur}'
         and numero   = '{$this->numero}' 
         and articulo = '{$this->d_articulo}'";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "07- Error. No se pudo leer [pddeta] !! ";
   return;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error     = 1;
   $this->msg_error = "08- Error. No se pudo leer [pddeta] !!";
   return;
}
$this->d_bultos   = $row['bultos'];
$this->d_unidades = $row['unidades'];
$this->d_volumen  = $row['volumen'];
$this->d_otros    = $row['otros'];

return;

}

function r_insert_pddeta()
{
$this->error     = 0;
$this->msg_error = "";
$p_cancel        = false;
$p_sql_p="insert into pddeta values ( '{$this->empresa}','{$this->tdoc}' ,'{$this->letra}','{$this->sucur}','{$this->numero}',
                                      '{$this->d_articulo}' ,'{$this->d_bultos}','{$this->d_unidades}','{$this->d_volumen}',
                                      '{$this->d_otros}', '{$this->estado}' )" ;
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 1;
  $this->msg_error = "09- Error. No se pudo insertar [pddeta] !! ";
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "10- Error. No se pudo insertar [pddeta] !! ";
  return;  
}
odbc_free_result($resultado);

return;
}

function r_update_pdcabe()
{
$this->error     = 0;
$this->msg_error = "";

$this->fecha_doc = date("Ymd",strtotime($this->fecha_doc));
if (strlen($this->fecha_turno) > 0 ) $this->fecha_turno = date("Ymd",strtotime($this->fecha_turno));
if (strlen($this->fecha_pedido_turno) > 0 ) $this->fecha_pedido_turno = date("Ymd",strtotime($this->fecha_pedido_turno));
if (strlen($this->fecha_disp) > 0 ) $this->fecha_disp = date("Ymd",strtotime($this->fecha_disp));
if (strlen($this->fecha_ini_comp) > 0 ) $this->fecha_ini_comp = date("Ymd",strtotime($this->fecha_ini_comp));
if (strlen($this->fecha_prev_ent) > 0 ) $this->fecha_prev_ent = date("Ymd",strtotime($this->fecha_prev_ent));
if (strlen($this->fecha_conf_ent) > 0 ) $this->fecha_conf_ent = date("Ymd",strtotime($this->fecha_conf_ent));
if (strlen($this->fecha_difer_cliente) > 0 ) $this->fecha_difer_cliente = date("Ymd",strtotime($this->fecha_difer_cliente));
if (strlen($this->fecha_entrega) > 0 ) $this->fecha_entrega = date("Ymd",strtotime($this->fecha_entrega));

$p_vol = sprintf("%0.6f",$this->volumen);
$p_otr = sprintf("%0.6f",$this->otros);

$p_sql_p="update pdcabe set codigo_cliente = '{$this->codigo_cliente}',
                            codigo_cliente_final = '{$this->codigo_cliente_final}',
                            fecha_doc      = '{$this->fecha_doc}',
                            interior       = '{$this->interior}',
                            nro_factura    = '{$this->nro_factura}',
                            valor_declarado = '{$this->valor_declarado}',
                            turno          = '{$this->turno}',
                            fecha_pedido_turno = '{$this->fecha_pedido_turno}',
                            fecha_turno    = '{$this->fecha_turno}',
                            hora_pactada   = '{$this->hora_pactada}',
                            nro_oc         = '{$this->nro_oc}',
                            retira         = '{$this->retira}',
                            etiquetado     = '{$this->etiquetado}',
                            contado        = '{$this->contado}',
                            espera_acceso  = '{$this->espera_acceso}',
                            edificio       = '{$this->edificio}',
                            tte            = '{$this->tte}',
                            fecha_disp      = '{$this->fecha_disp}',
                            fecha_ini_comp  = '{$this->fecha_ini_comp}',
                            fecha_prev_ent  = '{$this->fecha_prev_ent}',
                            fecha_conf_ent  = '{$this->fecha_conf_ent}',
                            fecha_difer_cliente = '{$this->fecha_difer_cliente}',
                            fecha_entrega  = '{$this->fecha_entrega}',
                            bultos         = '{$this->bultos}',
                            unidades       = '{$this->unidades}',
                            volumen        = '$p_vol',
                            otros          = '$p_otr',
                            estado         = '{$this->estado}',
                            ultimo_estado  = '{$this->ultimo_estado}',
                            prioridad    = '{$this->prioridad}',
                            hora_entrega   = '{$this->hora_entrega}',
                            fc_concepto    = '{$this->fc_concepto}',
                            directo        = '{$this->directo}',
                            sector         = '{$this->sector}',
                            documentado    = '{$this->documentado}'
       where empresa  = '{$this->empresa}'
         and tdoc     = '{$this->tdoc}'
         and letra    = '{$this->letra}'
         and sucur    = '{$this->sucur}'
         and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 1;
  $this->msg_error = "11- Error. No se pudo actualizar [pdcabe] !! ";
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "12- Error. No se pudo actualizar [pdcabe] !!";
  return;  
}
odbc_free_result($resultado);

return;
}

function r_update_pdcabe_cantidad()
{
$this->error     = 0;
$this->msg_error = "";
$p_cancel        = false;

$p_sql_p="update pdcabe set bultos    = bultos   + '{$this->bultos}',
                            unidades  = unidades + '{$this->unidades}',
                            volumen   = volumen  + '{$this->volumen}',
                            otros     = otros    + '{$this->otros}'
            where empresa  = '{$this->empresa}'
              and tdoc     = '{$this->tdoc}'
              and letra    = '{$this->letra}'
              and sucur    = '{$this->sucur}'
              and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "14- Error. No se pudo actualizar [pdcabe] !! ";
   return;
}
if (odbc_num_rows($resultado) != 1){
   $this->error     = 1;
   $this->msg_error = "15- Error. No se pudo actualizar [pdcabe] !!";
   return;
}
odbc_free_result($resultado);

return;
}

function r_delete_pdcabe()
{
$this->error     = 0;
$this->msg_error = "";

$p_sql_p="delete from pdcabe_obser 
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "16- Error. No se pudo actualizar [pdcabe] !! ";
   return;
}
odbc_free_result($resultado);

$p_sql_p="delete from pdcabe 
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "17- Error. No se pudo actualizar [pdcabe] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "18- Error. No se pudo actualizar [pdcabe] !! ";
   return;
}
odbc_free_result($resultado);

$p_sql_p="delete from ing_ped
           where empresa = '{$this->empresa}'
             and sucped  = '{$this->sucur}'
             and nroped  = '{$this->numero}'
             and letped  = '{$this->letra}'";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "19- Error. No se pudo actualizar [ing_ped] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "20- Error. No se pudo actualizar [ing_ped] !! ";
   return;
}
odbc_free_result($resultado);

$p_sql_p="delete from pdcabe_tracking 
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "21- Error. No se pudo actualizar [pdcabe_tracking] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "22- Error. No se pudo actualizar [pdcabe_tracking] !! ";
   return;
}
odbc_free_result($resultado);

if ($this->empresa == 163 && $this->tdoc == 'PED' ) {
   $p_sql_p = "delete from pdcabe_Candy 
                where empresa  = '{$this->empresa}'
                  and tdoc     = '{$this->tdoc}'
                  and letra    = '{$this->letra}'
                  and sucur    = '{$this->sucur}'
                  and numero   = '{$this->numero}' ";
   $this->r_exec($p_sql_p,"pdcabe_Candy",1);
   if ($this->error != 0 ){
      $this->error     = 1;
      $this->msg_error = "23- Error. No se pudo actualizar [pdcabe_Candy] !! ";
      return;
   }
   $p_sql_p = "delete from pddeta_Candy 
                where empresa  = '{$this->empresa}'
                  and tdoc     = '{$this->tdoc}'
                  and letra    = '{$this->letra}'
                  and sucur    = '{$this->sucur}'
                  and numero   = '{$this->numero}' ";
   $this->r_exec($p_sql_p,"pddeta_Candy",-1);
   if ($this->error != 0 ){
      $this->error     = 1;
      $this->msg_error = "24- Error. No se pudo actualizar [pddeta_Candy] !! ";
      return;
   }

}

}

function r_delete_pdcabe_or()
{

$this->error     = 0;
$this->msg_error = "";
$p_sql_p="delete from pdcabe 
            where empresa  = '{$this->empresa}'
            and tdoc     = '{$this->tdoc}'
            and letra    = '{$this->letra}'
            and sucur    = '{$this->sucur}'
            and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "23- Error. No se pudo actualizar [pdcabe] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "24- Error. No se pudo actualizar [pdcabe] !! ";
   return;
}
odbc_free_result($resultado);

$p_sql_p="delete from pddeta 
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "25- Error. No se pudo actualizar [pddeta] !!";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "26- Error. No se pudo actualizar [pddeta] !!";
   return;
}
odbc_free_result($resultado);

$p_sql_p="delete from pdcabe_tracking 
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "27- Error. No se pudo actualizar [pdcabe_tracking] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "28- Error. No se pudo actualizar [pdcabe_tracking] !! ";
   return;
}
odbc_free_result($resultado);

}

function r_delete_pddeta()
{
$this->error     = 0;
$this->msg_error = "";
$p_cancel        = false;
$p_sql_p="delete from pddeta 
           where empresa  = '{$this->empresa}'
             and tdoc     = '{$this->tdoc}'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 1;
  $this->msg_error = "29- Error. No se pudo actualizar [pddeta] !!";
  return;
}
if (odbc_num_rows($resultado) <= 0){
  $this->error     = 1;
  $this->msg_error = "30- Error. No se pudo actualizar [pddeta] !!";
  return;  
}
odbc_free_result($resultado);

}

function r_inserto_ctrl_remitos()
{
$this->error     = 0;
$this->msg_error = "";

$this->fecha_modif = date("Ymd H:i:s",strtotime($this->fecha_modif));
$p_sql_p="insert into ctrl_remitos values ( '{$this->empresa}', '{$this->tdoc}', '{$this->letra}', '{$this->sucur}',
                                            '{$this->numero}', '{$this->campo}', '{$this->valor_ant}', '{$this->valor_act}',
                                            '{$this->usuario_modif}','{$this->fecha_modif}','{$this->transf}' )";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 1;
  $this->msg_error = "31- Error. No se pudo insertar [ctrl_remitos] !! ";
  return;
}
if (odbc_num_rows($resultado) <= 0){
  $this->error     = 1;
  $this->msg_error = "32- Error. No se pudo insertar [ctrl_remitos] !! ";
  return;  
}
odbc_free_result($resultado);

}

function r_inserto_anul_ped()
{
$this->error     = 0;
$this->msg_error = "";
$this->fecha_modif = date("Ymd H:i:s",strtotime($this->fecha_modif));
$p_fecha         = date("Ymd",strtotime($this->fecha_modif));

$p_sql_p="insert into anul_ped values ( 'A','{$this->empresa}','S','{$this->letra}', '{$this->sucur}',
                                      '{$this->numero}', '{$this->secuencia}', '{$this->d_bultos}', 'N',
                                      '{$this->usuario_modif}','$p_fecha','{$this->fecha_modif}','N' )";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "33- Error. No se pudo actualizar [anul_ped] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "34- Error. No se pudo actualizar [anul_ped] !!";
   return;
}
odbc_free_result($resultado);

}

function r_insert_ped_ccr() 
{
$this->error     = 0;
$this->msg_error = "";
$p_obser_3       = "T01|N|    |A|".$_SESSION['UsuarioConectado']."|00:00:00";

$p_cli = substr($this->d_cliente,0,30);
$p_dir = substr($this->d_direccion,0,30);
$p_loc = substr($this->d_localidad,0,30);
$p_pro = substr($this->d_provincia,0,20);
$p_cp  = substr($this->d_cod_postal,0,8);
$p_vol = sprintf("%0.6f",$this->d_volumen);
$p_otr  = sprintf("%0.6f",$this->d_otros);

$p_sql_p="";
$this->fecha_ing = date("Ymd",strtotime($this->fecha_ing));
$this->fecha_doc = date("Ymd",strtotime($this->fecha_doc));
if (strlen($this->fecha_prev_ent) > 0 ) $this->fecha_prev_ent = date("Ymd",strtotime($this->fecha_prev_ent));
if (strlen($this->d_fecha_p_ent) > 0 )  $this->d_fecha_p_ent = date("Ymd",strtotime($this->d_fecha_p_ent));

$p_sql_p="SET ANSI_DEFAULTS Off;";
$p_sql_p.="insert into ped_ccr values ('5','{$this->empresa}','C','S','3','{$this->letra}',
                                  '{$this->sucur}','{$this->numero}', '{$this->d_secuencia}', 
                                  '{$this->fecha_ing}','{$this->d_fecha_p_ent}','','{$this->fecha_doc}',
                                  '{$this->nro_oc}','','{$this->d_cod_cliente}',
                                  '$p_cli','$p_dir','$p_loc','$p_pro','$p_cp','$p_obser_3')";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 2;
  $this->msg_error = "35- Error. No se pudo insertar [ped_ccr] !!";
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "36- Error. No se pudo insertar [ped_ccr] !! ";
  return;  
}
odbc_free_result($resultado);

$p_sql_p="SET ANSI_DEFAULTS Off;";
$p_sql_p.="insert into item_ccr values ('5','{$this->empresa}','S','3','{$this->letra}',
                                  '{$this->sucur}','{$this->numero}', '{$this->d_secuencia}', '{$this->d_secuencia}',
                                  '{$this->d_articulo}','{$this->d_precio}',
                                  '{$this->d_unidades}',
                                  '$p_vol',
                                  '$p_cli','$p_dir',
                                  '$p_loc','$p_pro',
                                  '$p_cp')";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 2;
  $this->msg_error = "37- Error. No se pudo insertar [item_ccr] !! ".$p_sql_p;
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "38- Error. No se pudo insertar [item_ccr] !! ";
  return;  
}
odbc_free_result($resultado);

$p_sql_p="insert into prop_ccr values ('5','{$this->empresa}','{$this->d_condicion}','S','3','{$this->letra}',
                                       '{$this->sucur}','{$this->numero}', '{$this->d_secuencia}', '{$this->d_secuencia}',
                                       '{$this->d_articulo}','{$this->d_precio}',
                                       '{$this->d_unidades}',
                                       '$p_vol','{$this->d_secuencia}',
                                       '{$this->d_fecha_p_ent}','{$this->d_concepto}',
                                       '$p_otr',
                                       '{$this->d_bultos}','{$this->d_nro_lote}','{$this->d_serie}')";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 2;
  $this->msg_error = "39- Error. No se pudo insertar [prop_ccr] !! ";
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "40- Error. No se pudo insertar [prop_ccr] !!";
  return;  
}
odbc_free_result($resultado);

return;
}

function r_insert_prop_ccr()
{
$this->error     = 0;
$this->msg_error = "";
if (strlen($this->fecha_prev_ent) > 0 ) $this->fecha_prev_ent = date("Ymd",strtotime($this->fecha_prev_ent));
$p_sql_p="insert into prop_ccr values ('5','{$this->empresa}','{$this->d_condicion}','S','3','{$this->letra}',
                                '{$this->sucur}','{$this->numero}', '{$this->d_secuencia}', '{$this->d_nro_item}',
                                '{$this->d_articulo}','0',
                                '{$this->d_unidades}',
                                '{$this->d_volumen}','{$this->d_orden}',
                                '{$this->fecha_prev_ent}','{$this->d_concepto}',
                                '{$this->d_otros}',
                                '{$this->d_bultos}','{$this->d_nro_lote}','{$this->d_serie}')";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 2;
   $this->msg_error = "41- Error. No se pudo insertar [prop_ccr] !! ";
   return;
}
if (odbc_num_rows($resultado) != 1){
   $this->error     = 1;
   $this->msg_error = "42- Error. No se pudo insertar [prop_ccr] !!";
   return;
}
odbc_free_result($resultado);

return;

}

function r_update_prop_ccr_estado($r_condicion)
{
$this->error = 0;
$this->msg_error = '';
$p_sql_p="update prop_ccr set condicion = '$r_condicion'
           where empresa = '{$this->empresa}'
             and tipo_mov = 'S'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}'
             and condicion != 'A' ";
$this->r_exec($p_sql_p,"prop_ccr",0);
if ($this->error != 0 ){
   $this->msg_error = '43- Error. No se pudo actualizar [prop_ccr] !! ';
   return;
}
return;

}

function r_delete_ped_ccr()
{

$this->error     = 0;
$this->msg_error = "";

$p_bul = 0;
$p_uns = 0;
$p_vol = 0;
$p_otr = 0;
$p_sql_p="select sum(bultos) bultos,sum(cantidad) unidades,sum(volumen) volumen,sum(otros) otros
            from prop_ccr
           where numero     = '{$this->numero}'
             and empresa    = '{$this->empresa}'
             and letra      = '{$this->letra}'
             and sucur      = '{$this->sucur}'
             and secuencia  = '{$this->d_secuencia}'
             and nro_lote   = '{$this->d_nro_lote}'
             and serie      = '{$this->d_serie}' 
             and condicion != 'C' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "44- Error. No se pudo insertar [prop_ccr] !!";
   return;
}
$row=odbc_fetch_array($resultado);
if ($row) {
   if (strlen($row['bultos']) > 0){
      $p_bul = $row['bultos'];
      $p_uns = $row['unidades'];
      $p_vol = $row['volumen'];
      $p_otr = $row['otros'];
   }
}
if ($p_bul == 0){
   $p_sql_p="delete from ped_ccr
               where numero  = '{$this->numero}'
                 and empresa = '{$this->empresa}'
                 and letra   = '{$this->letra}'
                 and sucur   = '{$this->sucur}'
                 and secuencia = '{$this->d_secuencia}' ";
   $resultado=@odbc_exec($this->conexion,$p_sql_p);
   if (!$resultado) {
      $this->error     = 2;
      $this->msg_error = "45- Error. No se pudo actualizar [ped_ccr] !! ";
      return;
   }
   if (odbc_num_rows($resultado) != 1){
      $this->error     = 1;
      $this->msg_error = "46- Error. No se pudo actualizar [ped_ccr] !! ";
      return;
   }
   odbc_free_result($resultado);

   $p_sql_p="delete from item_ccr
               where numero  = '{$this->numero}'
                 and empresa = '{$this->empresa}'
                 and letra   = '{$this->letra}'
                 and sucur   = '{$this->sucur}'
                 and secuencia = '{$this->d_secuencia}' ";
   $resultado=@odbc_exec($this->conexion,$p_sql_p);
   if (!$resultado) {
      $this->error     = 2;
      $this->msg_error = "47- Error. No se pudo actualizar [item_ccr] !!";
      return;
   }
   if (odbc_num_rows($resultado) != 1){
      $this->error     = 1;
      $this->msg_error = "48- Error. No se pudo actualizar [item_ccr] !! ";
      return;
   }
   odbc_free_result($resultado);
}
else{
   $p_sql_p="update item_ccr set cantidad = '$p_uns', volumen = '$p_bul'
              where numero  = '{$this->numero}'
                and empresa = '{$this->empresa}'
                and letra   = '{$this->letra}'
                and sucur   = '{$this->sucur}'
                and secuencia = '{$this->d_secuencia}' ";
   $resultado=@odbc_exec($this->conexion,$p_sql_p);
   if (!$resultado) {
      $this->error     = 2;
      $this->msg_error = "49- Error. No se pudo actualizar [item_ccr] !!";
      return;
   }
   if (odbc_num_rows($resultado) != 1){
      $this->error     = 1;
      $this->msg_error = "50- Error. No se pudo actualizar [item_ccr] !! ";
      return;
   }
   odbc_free_result($resultado);

}
$p_sql_p="delete from prop_ccr
           where numero  = '{$this->numero}'
             and empresa = '{$this->empresa}'
             and letra   = '{$this->letra}'
             and sucur   = '{$this->sucur}'
             and secuencia = '{$this->d_secuencia}'
             and nro_lote  = '{$this->d_nro_lote}'
             and serie     = '{$this->d_serie}' 
             and condicion   = 'C' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 2;
   $this->msg_error = "51- Error. No se pudo actualizar [prop_ccr] !! ";
   return;
}
if (odbc_num_rows($resultado) <= 0){
   $this->error     = 1;
   $this->msg_error = "52- Error. No se pudo actualizar [prop_ccr] !! ";
   return;
}
odbc_free_result($resultado);

return;
}

function r_delete_prop_ccr_cero($r_cond)
{
$this->error     = 0;
$this->msg_error = "";

$p_sql_p = "select * from prop_ccr 
             where numero  = '{$this->numero}'
               and empresa = '{$this->empresa}'
               and letra   = '{$this->letra}'
               and sucur   = '{$this->sucur}'
               and cantidad  = 0
               and bultos    = 0
               and otros     = 0 ";
if ($r_cond == 'C'){
   $p_sql_p .= " and condicion = 'C' ";
}
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
   $this->error     = 2;
   $this->msg_error = "53- Error. No se pudo actualizar [prop_ccr] !! ";
   return;
}
while ($row=odbc_fetch_array($resultado)){
   $p_sql_p="delete from ped_ccr
               where numero    = '{$this->numero}'
                 and empresa   = '{$this->empresa}'
                 and letra     = '{$this->letra}'
                 and sucur     = '{$this->sucur}'
                 and secuencia = '{$row['secuencia']}' 
                 and condicion = 'C' ";
   $this->r_exec($p_sql_p,"ped_ccr",0);
   if ($this->error != 0) {
      $this->error     = 2;
      $this->msg_error = "55- Error. No se pudo actualizar [ped_ccr] !! ";
      break;
   }

   $p_sql_p="delete from item_ccr
              where numero    = '{$this->numero}'
                and empresa   = '{$this->empresa}'
                and letra     = '{$this->letra}'
                and sucur     = '{$this->sucur}'
                and secuencia = '{$row['secuencia']}'";
   $this->r_exec($p_sql_p,"item_ccr",0);
   if ($this->error != 0 ) {
      $this->error     = 2;
      $this->msg_error = "56- Error. No se pudo actualizar [items_ccr] !! ";
      break;
   }
}
odbc_free_result($resultado);

$p_sql_p = "delete from prop_ccr 
             where numero  = '{$this->numero}'
               and empresa = '{$this->empresa}'
               and letra   = '{$this->letra}'
               and sucur   = '{$this->sucur}'
               and cantidad  = 0
               and bultos    = 0
               and otros     = 0 ";
if ($r_cond == 'C'){
   $p_sql_p .= " and condicion = 'C' ";
}
$this->r_exec($p_sql_p,"prop_ccr",-1);
if ($this->error != 0 ){
   $this->error     = 2;
   $this->msg_error = "57- Error. No se pudo actualizar [prop_ccr] !! ";
}

return;

}

function r_insert_pdcabe_obser()
{
$this->error     = 0;
$this->msg_error = "";

if (strlen($this->o_obser_gl) == 0 && strlen($this->o_obser) == 0){
  return;
}
$p_sql_p="insert into pdcabe_obser values ('{$this->empresa}','{$this->tdoc}','{$this->letra}',
                                           '{$this->sucur}','{$this->numero}', '{$this->o_obser}', 
                                           '{$this->o_obser_gl}','{$this->estado}' )";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 1;
  $this->msg_error = "57- Error. No se pudo insertar [pdcabe_obser]";
  return;
}
if (odbc_num_rows($resultado) != 1){
  $this->error     = 1;
  $this->msg_error = "58- Error. No se pudo insertar [pdcabe_obser]";
  return;  
}
odbc_free_result($resultado);
}

function r_select_clientes_emp()
{
$this->error     = 0;
$this->msg_error = "";

$p_sql_p="select * from clientes_emp
           where empresa = '{$this->empresa}'
             and codigo = '{$this->codigo_cliente}'";
$resultado = @odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
    $this->error     = 2;
    $this->msg_error = "59- Error. No se pudo leer [clientes_emp] !!";
    return;
}
$row=odbc_fetch_array($resultado);
if (!$row) {
    $this->error     = 1;
    $this->msg_error = "60- Error. No se pudo leer [clientes_emp] !!";
    return;
}
$this->cod_dest   = $row['cod_dest'];
$this->cliente    = trim($row['raz_soc']);
$this->direccion  = trim(GLSA::eliminar_simbolos($row['direccion']));
$this->pais       = $row['pais'];
$this->provincia  = $row['provincia'];
$this->localidad  = $row['localidad'];
$this->cod_postal = trim($row['cod_post']);
$this->cuit       = $row['cuit'];
$this->mail       = trim($row['email']);
$this->tel        = trim($row['tel']);
$this->codigo_cliente_ext = trim($row['cod_externo']);
return;

}

function r_select_clientes_emp_final()
{
$this->error     = 0;
$this->msg_error = "";

$p_sql_p="select * from clientes_emp
           where empresa = '{$this->empresa}'
             and codigo = '{$this->codigo_cliente_final}'";
$resultado = @odbc_exec($this->conexion,$p_sql_p);
if (!$resultado) {
  $this->error     = 2;
  $this->msg_error = "61- Error. No se pudo leer [clientes_emp] !! ";
  return;
}
$row=odbc_fetch_array($resultado);
if (!$row) {
  $this->error     = 1;
  $this->msg_error = "62- Error. No se pudo leer [clientes_emp] !! ";
  return;
}
$this->cliente_final    = trim($row['raz_soc']);
$this->direccion_final  = trim($row['direccion']);
$this->pais_final       = $row['pais'];
$this->provincia_final  = $row['provincia'];
$this->localidad_final  = $row['localidad'];
$this->cod_postal_final = trim($row['cod_post']);
$this->cuit_final       = $row['cuit'];
$this->mail             = trim($row['email']);
$this->tel              = trim($row['tel']);

return;

}

function r_siguiente_secuencia()
{
$this->error     = 0;
$this->msg_error = '';

$p_ultima = 0;
$p_sql_p="select max(a.secuencia) ultima from ped_ccr a
           where a.empresa   = '{$this->empresa}'
             and a.tipo_mov  = 'S'
             and a.letra     = '{$this->letra}'
             and a.sucur     = '{$this->sucur}'
             and a.numero    = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "63- Error. No se pudo leer [ped_ccr] !! ";
   return $p_ultima;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error     = 2;
   $this->msg_error = "64- Error. No se pudo leer [ped_ccr] !! ";
   return $p_ultima;
}
$p_ultima = $row['ultima'];
$p_ultima = $p_ultima + 1;

odbc_free_result($resultado);

return $p_ultima;
}

function r_busco_lote()
{
$this->error     = 0;
$this->msg_error = '';

$p_lote = 0;
$p_sql_p="select lote from lotcli
           where empresa = '{$this->empresa}'
             and tipdoc  = '{$this->tdoc}' 
             and letdoc  = '{$this->letra}'
             and sucdoc  = '{$this->sucur}'
             and nrodoc  = '{$this->numero}'";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "65- Error. No se pudo leer [lotcli] !! ";
   return $p_lote;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error     = 1;
   $this->msg_error = "66- Error. No se pudo leer [lotcli] !! ";
   return $p_lote;
}
$p_lote = $row['lote'];

return $p_lote;
}

function r_busco_alcance()
{
$this->error     = 0;
$this->msg_error = '';

$p_fecha_alcance = '';
$p_sql_p="select min(fecha_ent_alcance) alcance
            from hoja_ruta_det a, pre_expedicion_items b
           where a.hruta_d = b.hruta_d
             and a.nro_item = b.nro_item
             and a.empresa  = '{$this->empresa}'
             and a.tdoc     = '{$this->tdoc}'
             and a.letra    = '{$this->letra}'
             and a.sucur    = '{$this->sucur}'
             and a.numero   = '{$this->numero}'
             and b.condicion_alcance = 'E'
             and b.estado   <> 'A' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "67- Error. No se pudo leer [pre_expedicion_items] !! ";
   return $p_fecha_alcance;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error     = 1;
   $this->msg_error = "68- Error. No se pudo leer [pre_expedicion_items] !! ";
   return $p_fecha_alcance;
}
if (strlen($row['alcance']) > 0 && $row['alcance'] != '1900-01-01'){
   $p_fecha_alcance = date("Y-m-d",strtotime($row['alcance']));
}

return $p_fecha_alcance;

}

function r_veo_cpbt_en_hr()
{
$this->error     = 0;
$this->msg_error = '';

$p_hr = 0;
$p_sql_p="select hruta_d  from hoja_ruta_det
           where empresa = '{$this->empresa}'
             and tdoc   = '{$this->tdoc}'
             and letra  = '{$this->letra}'
             and sucur  = '{$this->sucur}'
             and numero = '{$this->numero}'
             and estado_rm <> 'N'";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "69- Error. No se pudo leer [hoja_ruta_det] !! ";
   return $p_hr;
}
$row=odbc_fetch_array($resultado);
if ($row){
   $p_hr = $row['hruta_d'];
}
return $p_hr;

}

function r_veo_or_en_hr($r_interior)
{
$this->error     = 0;
$this->msg_error = '';

$p_hr = 0;
$p_sql_p="select hruta_d  from hoja_ruta_det
           where empresa = '{$this->empresa}'
             and tdoc   = '{$this->tdoc}'
             and letra  = '{$this->letra}'
             and sucur  = '{$this->sucur}'
             and numero = '{$this->numero}'
             and estado_rm <> 'N'
             and interior = '$r_interior' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "70- Error. No se pudo leer [hoja_ruta_det] !! ";
   return $p_hr;
}
$row=odbc_fetch_array($resultado);
if ($row){
   $p_hr = $row['hruta_d'];
}
return $p_hr;

}

function r_veo_item_a_redespachar()
{
$this->error     = 0;
$this->msg_error = '';

$p_item = 0;
$p_sql_p="select a.hruta_d,b.nro_item,a.fecha   
            from hoja_ruta a, hoja_ruta_det b
           where a.hruta_d = b.hruta_d
             and b.empresa = '{$this->empresa}'
             and b.tdoc   = '{$this->tdoc}'
             and b.letra  = '{$this->letra}'
             and b.sucur  = '{$this->sucur}'
             and b.numero = '{$this->numero}'
             and b.estado_rm <> 'N'
             order by fecha desc";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "70- Error. No se pudo leer [hoja_ruta_det] !! ";
   return;
}
while ($row=odbc_fetch_array($resultado)){
   $p_can = 0;
   $p_sql_p="select count(*) can
               from pre_expedicion_items
              where hruta_d  = '{$row['hruta_d']}'
                and nro_item = '{$row['nro_item']}'
                and estado   = 'R' ";
   $this->r_select_fila($p_sql_p,"pre_expedicion_items");
   if ($this->error == 0){
      if (strlen($this->row['can']) > 0 ){
         $p_can = $this->row['can'];
      }
   }
   if ($p_can > 0 ){
      $p_item = 1;
   }
}
odbc_free_result($resultado);

return $p_item;

}

function r_array_pdcabe()
{
$this->error = 0;
$this->msg_error = '';
$pa=array();
$p_sql_p="select articulo,nro_lote,serie,concepto,
                 sum(bultos) bultos ,sum(cantidad) unidades,sum(volumen) volumen,sum(otros) otros 
            from prop_ccr
           where numero   = '{$this->numero}'
             and empresa  = '{$this->empresa}'
             and tipo_mov = 'S'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
           group by articulo,nro_lote,serie,concepto   
           order by articulo,nro_lote,serie,concepto ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->mgs_error = '71- Error. No se pudo leer [prop_ccr] !! ';
   return $pa;
}
while ($row=odbc_fetch_array($resultado)){
   $pa[] = array('articulo'=>rtrim($row['articulo']),
                 'nro_lote'   =>trim($row['nro_lote']),
                 'serie'  =>trim($row['serie']),
                 'concepto' =>trim($row['concepto']),
                 'bultos'   => $row['bultos'],
                 'unidades' => $row['unidades'],
                 'volumen'  => $row['volumen'],
                 'otros'    => $row['otros']
   );
}
odbc_free_result($resultado);

return $pa;

}

function r_ctrl_reservas($r_es_rechazo,$r_condicion,$r_ultimo_estado)
{
$this->error = 0;
$this->msg_error = '';

if ($r_es_rechazo == 'S' || $r_ultimo_estado == 13){
   return;
}
if ($this->estado == 4){ // ya preparado
   return;
}
if ($this->tdoc != 'RTO'){
   return;
}

$p_sql_p="select concepto,articulo,nro_lote,serie,
                 sum(bultos) bultos, sum(cantidad) unidades, sum(volumen) volumen, sum(otros) otros
            from prop_ccr
           where empresa = '{$this->empresa}'
             and tipo_mov = 'S'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}'
             and condicion = '$r_condicion' 
            group by concepto,articulo,nro_lote,serie ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '72- Error. No se pudo leer [prop_ccr] !! ';
   return;
}
while ($row=odbc_fetch_array($resultado)){
   $p_articulo = rtrim($row['articulo']);
   $p_nro_lote = trim($row['nro_lote']);
   $p_serie    = trim($row['serie']);
   $p_concepto = trim($row['concepto']);

   $pa_res = Stock::r_concepto_stock($p_concepto);
   if ($pa_res['error'] != 'OK'){
      $this->error     = 1;
      $this->msg_error = "73- Error. No se pudo leer [concepto_stock] !!";
      $p_cancel        = true;
      break;
   }
   $p_area_orig = $pa_res['area_orig'];
   $p_grupo_deposito = $pa_res['grupo_deposito'];

   $Stock = new Stock($this->empresa,$p_grupo_deposito,$p_area_orig,$p_articulo,$p_nro_lote);
   $Stock->conexion = $this->conexion;

   $Stock->r_select_stock();
   if ($Stock->error != 0){
      $this->error     = 1;
      $this->msg_error = "74- Error. No se pudo leer [stock] !!";
      $p_cancel        = true;
      break;
   }
   if ($Stock->bultos_res < $row['bultos']){
      $this->error     = 1;
      $this->msg_error = "75- Bultos en reserva insuficientes !!";
      $p_cancel        = true;
      break;
   }
   if ($Stock->unidades_res < $row['unidades']){
      $this->error     = 1;
      $this->msg_error = "76- Unidades en reserva insuficientes !!";
      $p_cancel        = true;
      break;
   }
   if ($Stock->volumen_res < $row['volumen']){
      $this->error     = 1;
      $this->msg_error = "77- Volumen en reserva insuficientes !!";
      $p_cancel        = true;
      break;
   }
   if ($Stock->otros_res < $row['otros']){
      $this->error     = 1;
      $this->msg_error = "78- Otros en reserva insuficientes !!";
      $p_cancel        = true;
      break;
   }
   if ($p_serie != '0'){

   }
}
odbc_free_result($resultado);

return;

}

function r_update_estado_pddeta()
{
$this->error = 0;
$this->msg_error = '';

$p_sql_p="update pddeta set estado = '{$this->d_estado}'
           where empresa = '{$this->empresa}'
             and tdoc    = '{$this->tdoc}'
             and letra   = '{$this->letra}'
             and sucur   = '{$this->sucur}'
             and numero  = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '79- Error. No se pudo leer [pddeta] !! ';
   return;
}

return;

}

function r_update_pddeta()
{
$this->error = 0;
$this->msg_error = '';

$p_sql_p="update pddeta set bultos   =  bultos + '{$this->d_bultos}',
                            unidades = unidades + '{$this->d_unidades}',
                            volumen  = volumen + '{$this->d_volumen}',
                            otros    = otros + '{$this->d_otros}'
          where empresa = '{$this->empresa}'
            and tdoc    = '{$this->tdoc}'
            and letra   = '{$this->letra}'
            and sucur   = '{$this->sucur}'
            and numero  = '{$this->numero}' 
            and articulo = '{$this->d_articulo}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '80- Error. No se pudo leer [pddeta] !! ';
   return;
}

return;

}

function r_cuenta_items_pendientes()
{
$this->error = 0;
$this->msg_error = "";

$p_can = 0;
$p_sql_p="select count(*) can from prop_ccr
           where empresa = '{$this->empresa}'
             and tipo_mov = 'S'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and numero   = '{$this->numero}'
             and condicion not in ('E') ";
$this->r_select_fila($p_sql_p,"prop_ccr");
if ($this->error == 0){
   $p_can = $this->row['can'];
}

return $p_can;

}

function r_select_cot_remito()
{
$this->error = 0;
$this->msg_error = 0;
$p_sql_p="select * from cot_remito
           where hruta_d = '{$this->cot_hruta_d}'
             and empresa = '{$this->empresa}'
             and td      = '{$this->tdoc}'
             and sucursal = '{$this->sucur}'
             and documento = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '81- Error. No se pudo leer [cot_remito] !! ';
   return;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error = 1;
   $this->msg_error = '82- Error. No se pudo leer [cot_remito] !! ';
   return;
}
$this->cot = $row['cot'];
$this->cot_resultado = $row['resultado'];
$this->cot_fecha_resp = $row['fecha_resp'];
$this->cot_hora_resp = $row['hora_resp'];
$this->cot_estado = $row['est'];
$this->cot_usuario = $row['usuario'];
$this->cot_carga = $row['carga'];

odbc_free_result($resultado);
return;

}

function r_update_cot_remito()
{
$this->error = 0;
$this->msg_error = 0;
if (strlen($this->cot_hora_resp) > 0 ) $this->cot_fecha_resp = date("Ymd",strtotime($this->cot_fecha_resp));
$p_sql_p="update cot_remito set cot = '{$this->cot}',
                                fecha_resp = '{$this->cot_fecha_resp}',
                                resultado  = '{$this->cot_resultado}'
          where hruta_d = '{$this->cot_hruta_d}'
            and empresa = '{$this->empresa}'
            and td      = '{$this->tdoc}'
            and sucursal = '{$this->sucur}'
            and documento = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '83- Error. No se pudo actualizar [cot_remito] !! ';
   return;
}
if (odbc_num_rows($resultado) != 1){
   $this->error = 1;
   $this->msg_error = '84- Error. No se pudo actualizar [cot_remito] !! ';
   return;
}
odbc_free_result($resultado);
return;

}

function r_insert_cot_remito()
{

$this->error = 0;
$this->msg_error = 0;
if (strlen($this->cot_hora_resp) > 0 ) $this->cot_fecha_resp = date("Ymd",strtotime($this->cot_fecha_resp));
$p_sql_p="insert into cot_remito  values ( '{$this->cot_hruta_d}', '{$this->empresa}','{$this->tdoc}','{$this->letra}',
                                       '{$this->sucur}','{$this->numero}','{$this->cot_resultado}','{$this->cot}',
                                       '{$this->cot_fecha_resp}','{$this->cot_hora_resp}','{$this->cot_estado}',
                                       '{$this->cot_usuario}','{$this->cot_carga}' )";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '85- Error. No se pudo insertar [cot_remito] !! ';
   return;
}
if (odbc_num_rows($resultado) != 1){
   $this->error = 1;
   $this->msg_error = '86- Error. No se pudo insertar [cot_remito] !! ';
   return;
}
odbc_free_result($resultado);
return;
}

function r_hay_items_pendientes()
{

$this->error = 0;
$this->msg_error = 0;
$pa_can['bul'] = 0;
$pa_can['uns'] = 0;
$pa_can['vol'] = 0;
$pa_can['otr'] = 0;
$p_sql_p="select sum(bultos) bultos,sum(cantidad) unidades, sum(volumen) volumen, sum(otros) otros
            from prop_ccr
           where numero = '{$this->numero}'
             and empresa = '{$this->empresa}'
             and tipo_mov = 'S'
             and letra    = '{$this->letra}'
             and sucur    = '{$this->sucur}'
             and condicion = 'P0' ";
$this->r_select_fila($p_sql_p,"prop_ccr");
if ($this->error == 2){
   $this->error = 1;
   $this->msg_error = '87- Error. No se pudo leer [prop_ccr] !!';
   return;
}
if ($this->error == 0){
   $pa_can['bul'] = $this->row['bultos'];
   $pa_can['uns'] = $this->row['unidades'];
   $pa_can['vol'] = $this->row['volumen'];
   $pa_can['otr'] = $this->row['otros'];
}
return $pa_can;

}

function r_inserta_pdcabe_incompleto(){

$this->error = 0;
$this->msg_error = '';
$p_sql_p="insert into pdcabe_incompleto values ( '{$this->empresa}','{$this->tdoc}','{$this->letra}',
                                                 '{$this->sucur}','{$this->numero}','{$this->bultos}',
                                                 '0','{$this->usuario_modif}','{$this->fecha_modif}')";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error = 2;
   $this->msg_error = '88- Error. No se pudo insertar [pdcabe_incompleto] !! ';
   return;
}
if (odbc_num_rows($resultado) != 1){
   $this->error = 1;
   $this->msg_error = '89- Error. No se pudo insertar [pdcabe_incompleto] !! ';
   return;
}
odbc_free_result($resultado);

return;
}

private function r_login_sigtrack(){

$this->error = 0;
$this->msg_error = '';
$p_token = '0';

$data=array();
$data=array("api_key" => 'vsajbgcy94x5nwfl',
   "user" => 'skoch@gargano.com.ar',
   "pass" => 'gargano2021' );

$j_data=json_encode($data);

$ch = curl_init();
$p_url = "https://sigtrack.com.ar/api/v2/login";
curl_setopt($ch, CURLOPT_URL, $p_url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_SSLv3' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $j_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$respuesta = curl_exec($ch);

$res = json_decode($respuesta);
if ($res->response != 200){
   $this->error = 1;
   $this->msg_error = '90- Error. No se puede conectar a sigTrac !! ';
   return $p_token;
}
$p_token = $res->token;
curl_close($ch);

return $p_token;

}

function r_select_pdcabe_tracking(){

$this->error = 0;
$this->msg_error = '';
$p_sql_p = "select * from pdcabe_tracking
         where empresa = '{$this->empresa}' 
           and tdoc    = '{$this->tdoc}'
           and letra   = '{$this->letra}'
           and sucur   = '{$this->sucur}'
           and numero  = '{$this->numero}'
           and estado    != 99 ";
$this->r_select_fila($p_sql_p,"pdcabe_tracking");
if ($this->error != 0 ){
   $this->error = 1;
   $this->msg_error = '91- Error. No se puede leer [pdcabe_tracking] !! ';
   return;
}
$this->nro_track     = $this->row['nro_track'];
$this->nro_track_int = $this->row['nro_track_int'];
return;
}

function r_update_pdcabe_tracking(){

$this->error = 0;
$this->msg_error = '';
$p_sql_p = "update pdcabe set nro_track = '{$this->nro_track}'
               where empresa = '{$this->empresa}' 
                 and tdoc    = '{$this->tdoc}'
                 and letra   = '{$this->letra}'
                 and sucur   = '{$this->sucur}'
                 and numero  = '{$this->numero}' ";
$this->r_exec($p_sql_p,"pdcabe_tracking",1);
if ($this->error != 0 ){
    $this->error = 1;
    $this->msg_error = '92- Error. No se puede actualizar [pdcabe] !! ';
    return;
}
$p_sql_p = "update pdcabe_tracking set nro_track = '{$this->nro_track}'
               where empresa = '{$this->empresa}' 
                 and tdoc    = '{$this->tdoc}'
                 and letra   = '{$this->letra}'
                 and sucur   = '{$this->sucur}'
                 and numero  = '{$this->numero}' ";
    $this->r_exec($p_sql_p,"pdcabe_tracking",1);
    if ($this->error != 0 ){
        $this->error = 1;
        $this->msg_error = '93- Error. No se puede actualizar [pdcabe_tracking] !! ';
        return;
    }

return;
}

function r_ins_ing_ped()
{
$this->error     = 0;
$this->msg_error = "";

$this->fecha_fc   = date("Ymd",strtotime($this->fecha_fc));
$this->fecha_proc = date("Ymd H:i:s",strtotime($this->fecha_proc));
$p_sql_p2 = "insert into ing_ped values ( '{$this->empresa}','{$this->sucur}','{$this->numero}',
                                           'I','FAC','{$this->letra_fc}',
                                           '{$this->sucur_fc}',
                                           '{$this->nro_factura}',
                                           '{$this->cuit}','{$this->valor_declarado}',
                                           '{$this->usuario}','{$this->fecha_proc}','N',
                                           '{$this->letra}','0','{$this->cliente_final}','{$this->fecha_fc}')";
$resultado=@odbc_exec($this->conexion,$p_sql_p2);
if (!$resultado) {
   $this->error     = 1;
   $this->msg_error = "94- Error. No se pudo insertar [ing_ped] !! ";
   return;
}
if (odbc_num_rows($resultado) != 1){
   $this->error     = 1;
   $this->msg_error = "95- Error. No se pudo insertar [ing_ped]";
   return;
}
odbc_free_result($resultado);

}

function r_upd_ing_ped()
{

$this->error = 0;
$this->msg_error = '';

$p_sql_i = "update ing_ped set valor_dec = '{$this->valor_declarado}',
                               letdoc     = '{$this->letra_fc}',
                               sucdoc     = '{$this->sucur_fc}',
                               nrodoc     = '{$this->nro_factura}',
                               cuit       = '{$this->cuit}'
             where empresa = '{$this->empresa}'
               and letped  = '{$this->letra}'
               and sucped  = '{$this->sucur}'
               and nroped  = '{$this->numero}'";
$this->r_exec($p_sql_i,"ing_ped",0);
if ($this->error != 0){
   $this->error     = 1;
   $this->msg_error = "94- Error. No se pudo actualizar [ing_ped] !! ";
   return;
}

return;

}
static function r_select_pdcabe_tracking_nro($r_nro_track,$r_operacion){
global $Base;

$pa_return['error'] = 'OK';
$pa_return['msg']   = '';
$r_nro_track = strtoupper(trim($r_nro_track));
$p_sql_p = "select * from pdcabe_tracking
             where nro_track_int = '$r_nro_track'  
               and estado    in ( 1,8 ) ";
$Base->r_select_fila($p_sql_p,"pdcabe_tracking");
if ($Base->error != 0 ){
   $pa_return['error'] = 'OK';
   $pa_return['msg']   = '96- Error. No se puede leer [pdcabe_tracking] !! ';
   return $pa_return;
}
$pa_return['empresa']  = $Base->row['empresa'];
$pa_return['tdoc']     = $Base->row['tdoc'];
$pa_return['letra']    = $Base->row['letra'];
$pa_return['sucur']    = $Base->row['sucur'];
$pa_return['numero']   = $Base->row['numero'];
$pa_return['nro_track_int'] = $Base->row['nro_track_int'];

return $pa_return;
}

function r_ins_sigtrack(){

$this->error = 0;
$this->msg_error = '';

//$p_fec = date("Y-m-d H:i",strtotime($this->fecha_proc));
$p_fec        = date("d-m-Y H:i");
$p_fecha_proc = date("Ymd H:i:s");

$p_token = $this->r_login_sigtrack();
if ($this->error != 0 || $p_token == '0'){
   return;
}
$headers = array( "Content-type: application/json",
                   "Authorization: Bearer $p_token",
                 );

$ped = array();
$this->nro_track_int = str_pad($this->empresa,3,'0',STR_PAD_LEFT).
                       $this->letra.
                       str_pad($this->sucur,5,'0',STR_PAD_LEFT).
                       str_pad($this->numero,10,'0',STR_PAD_LEFT);

//$p_c_hora = " en la franja horaria de ";
$p_c_hora = '';
$p_hora   = '';
switch ($this->st_operacion){
   case 'I':
      $p_estado = 1;
      $p_estado_sig = 1;
      break;
   case 'P':
      $p_estado = 8;
      $p_estado_sig = 2;
      break;
   case 'R':
      $p_estado = 3;
      $p_estado_sig = 5;
      break;
   case 'D':
      $p_estado = 6;
      $p_estado_sig = 3;
      $p_hora   = $p_c_hora.$this->hora_entrega;
      break;
}

switch ($this->empresa){
    case 9:
        $this->st_mail_comprador = 'skoch@gargano.com.ar';
        $this->st_mail_vendedor  = 'skoch@gargano.com.ar';
        break;
    case 193:
       $this->st_mail_comprador = 'distribucion_interior@gargano.com.ar';
       $this->st_mail_vendedor  = 'ventas@arfoods.com.ar';
       break;
    case 15:
        //$this->st_mail_comprador = 'distribucion_interior@gargano.com.ar';
        $this->st_mail_vendedor  = 'gaselec@orbis.com.ar';
        break;
    case 205: // sacar
        //$this->st_mail_comprador = 'waditernavasio@hotmail.com';
        $this->st_mail_vendedor  = 'duvinargentina@gmail.com';
        break;
    case 224:
        //$this->st_mail_comprador = 'waditernavasio@hotmail.com';
        $this->st_mail_vendedor  = 'info@mercata.com.ar';
        break;
    default:
       $this->st_mail_vendedor  = 'ecommerce@gargano.com.ar';
       break;
}

$ped = array('tracking' => $this->nro_track_int,
             'estado' => $p_estado_sig,
             'titulo' => $this->st_titulo,
             'nota' => $this->st_nota,
             'fecha' => $p_fec,
             'emailCliente' => $this->st_mail_comprador, //'romina.morello@kaser.com.ar',
             'emailEmpresa' => $this->st_mail_vendedor);
$j_ped = json_encode($ped);

$ch = curl_init();
$p_url = "https://sigtrack.com.ar/api/v2/record";
curl_setopt($ch, CURLOPT_URL, $p_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $j_ped);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$respuesta = curl_exec($ch);
if( $respuesta === false){
   //echo 'Curl error: ' . curl_error($ch);
   $this->error = 1;
   $this->msg_error = '97- '.curl_error($ch);
   return;
}
$res = json_decode($respuesta);
if ($res->response != 200){
   $this->error = 1;
   $this->msg_error = '98- Error. No se puede insertar a sigTrac !! '.print_r($res,1);
   return;
}

$this->nro_track = $res->data->st_trackingID;
$p_st_recordID   = $res->data->st_recordID;

$p_sql_p="insert into pdcabe_tracking_record values ('{$this->nro_track_int}','{$this->nro_track}','{$this->st_operacion}','{$p_st_recordID}',1) ";
$this->r_exec($p_sql_p,"pdcabe_tracking",1);
if ($this->error != 0){
   $this->error = 1;
   $this->msg_error = '99- Error. No se puede insertar [pdcabe_tracking_record] !! ';
   return;
}

curl_close($ch);

//if ($this->st_operacion != 'I' && $this->st_operacion != 'D'){
if ($this->st_operacion != 'I' && $this->st_operacion != 'D' && $this->st_operacion != 'P'){
   return;
}

$p_empresa_des = r_empresa_des($this->empresa);
$p_dir         = $this->direccion." - ".r_localidad_des($this->pais,$this->provincia,$this->localidad);
$p_dir         = GLSA::eliminar_simbolos($p_dir);
$p_fecha_doc   = date("d-m-Y",strtotime($this->fecha_doc));
$p_fecha_prev  = date("d-m-Y",strtotime($this->fecha_prev_ent));
if ($this->st_operacion == 'I'){
   $p_fecha_prev = '';
}
$ped = array();
$ped = array('tracking' => $this->nro_track_int,
             'empresa' => $p_empresa_des,
             'direccion_empresa' => $p_empresa_des,
             'nro_factura' => $this->nro_factura,
             'fecha_factura' => $p_fecha_doc,
             'nro_remito' => $this->numero,
             'fecha_remito' => $p_fecha_doc,
             'nro_pedido' => $this->numero,
             'nota' => '',
             'cliente' => $this->cliente,
             'direccion_entrega' => $p_dir,
             'fecha_entrega' => $p_fecha_prev,
             'hora_entrega' => $p_hora ,
             'contenido' => $this->st_contenido ) ;

$j_ped = json_encode($ped);

$ch = curl_init();
$p_url = "https://sigtrack.com.ar/api/v2/trackInfo";
curl_setopt($ch, CURLOPT_URL, $p_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $j_ped);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // SACAR
$respuesta = curl_exec($ch);
$res = json_decode($respuesta);
if ($res->response != 200){
   $this->error = 1;
   $this->msg_error = '100- Error. No se puede insertar a sigTrac !! ';
   return;
}

}

function r_ins_sigtrack_test(){

$this->error = 0;
$this->msg_error = '';

//$p_fec = date("Y-m-d H:i",strtotime($this->fecha_proc));
$p_fec        = date("d-m-Y H:i");
$p_fecha_proc = date("Ymd H:i:s");

$p_token = $this->r_login_sigtrack();
if ($this->error != 0 || $p_token == '0'){
    return;
}
$headers = array( "Content-type: application/json",
    "Authorization: Bearer $p_token",
);

$ped = array();
$this->nro_track_int = str_pad($this->empresa,3,'0',STR_PAD_LEFT).
                        $this->letra.
                        str_pad($this->sucur,5,'0',STR_PAD_LEFT).
                        str_pad($this->numero,10,'0',STR_PAD_LEFT);

//$p_c_hora = " en la franja horaria de ";
$p_c_hora = '';
$p_hora   = '';
switch ($this->st_operacion){
    case 'I':
        $p_estado = 1;
        $p_estado_sig = 1;
        break;
    case 'P':
        $p_estado = 8;
        $p_estado_sig = 1;
        break;
    case 'R':
        $p_estado = 3;
        $p_estado_sig = 2;
        break;
    case 'D':
        $p_estado = 6;
        $p_estado_sig = 3;
        $p_hora   = $p_c_hora.$this->hora_entrega;
        break;
}

switch ($this->empresa){
    case 9:
        $this->st_mail_comprador = 'skoch@gargano.com.ar';
        $this->st_mail_vendedor  = 'skoch@gargano.com.ar';
        break;
    case 193:
        $this->st_mail_comprador = 'distribucion_interior@gargano.com.ar';
        $this->st_mail_vendedor  = 'ventas@arfoods.com.ar';
        break;
    case 15:
        //$this->st_mail_comprador = 'distribucion_interior@gargano.com.ar';
        $this->st_mail_vendedor  = 'gaselec@orbis.com.ar';
        break;
    case 224:
       //$this->st_mail_comprador = 'distribucion_interior@gargano.com.ar';
       $this->st_mail_vendedor  = 'info@mercata.com.ar';
       break;
    default:
        break;
}

$ped = array('tracking' => $this->nro_track_int,
    'estado' => $p_estado_sig,
    'titulo' => $this->st_titulo,
    'nota' => $this->st_nota,
    'fecha' => $p_fec,
    'emailCliente' => $this->st_mail_comprador, //'romina.morello@kaser.com.ar',
    'emailEmpresa' => $this->st_mail_vendedor);
$j_ped = json_encode($ped);

/*
$ch = curl_init();
$p_url = "https://sigtrack.com.ar/api/v2/record";
curl_setopt($ch, CURLOPT_URL, $p_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $j_ped);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // SACAR
$respuesta = curl_exec($ch);
if( $respuesta === false){
    $this->error = 1;
    $this->msg_error = '80- '.curl_error($ch);
    return;
}
$res = json_decode($respuesta);
if ($res->response != 200){
    $this->error = 1;
    $this->msg_error = '81- Error. No se puede insertar a sigTrac !! ';
    return;
}


$this->nro_track = $res->data->st_trackingID;
*/

//$p_st_recordID   = $res->data->st_recordID;
    $p_st_recordID = 0  ;
    $this->nro_track = $this->nro_track_int;

$p_sql_p="insert into pdcabe_tracking_record values ('{$this->nro_track_int}','{$this->nro_track}','{$this->st_operacion}','{$p_st_recordID}',1) ";
$this->r_exec($p_sql_p,"pdcabe_tracking",1);
if ($this->error != 0){
    $this->error = 1;
    $this->msg_error = '101- Error. No se puede insertar [pdcabe_tracking_record] !! ';
    return;
}

//curl_close($ch);

if ($this->st_operacion != 'I' && $this->st_operacion != 'D'){
    return;
}

$p_empresa_des = r_empresa_des($this->empresa);
$p_dir         = $this->direccion." - ".r_localidad_des($this->pais,$this->provincia,$this->localidad);
$p_fecha_doc   = date("d-m-Y",strtotime($this->fecha_doc));
$p_fecha_prev  = date("d-m-Y",strtotime($this->fecha_prev_ent));
/*
$ped = array();
$ped = array('tracking' => $this->nro_track_int,
    'empresa' => $p_empresa_des,
    'direccion_empresa' => $p_empresa_des,
    'nro_factura' => $this->nro_factura,
    'fecha_factura' => $p_fecha_doc,
    'nro_remito' => $this->numero,
    'fecha_remito' => $p_fecha_doc,
    'nro_pedido' => $this->numero,
    'nota' => '',
    'cliente' => $this->cliente,
    'direccion_entrega' => $p_dir,
    'fecha_entrega' => $this->fecha_prev_ent,
    'hora_entrega' => $p_hora ,
    'contenido' => $this->st_contenido ) ;

$j_ped = json_encode($ped);

$ch = curl_init();
$p_url = "https://sigtrack.com.ar/api/v2/trackInfo";
curl_setopt($ch, CURLOPT_URL, $p_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $j_ped);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // SACAR
$respuesta = curl_exec($ch);
$res = json_decode($respuesta);
if ($res->response != 200){
    $this->error = 1;
    $this->msg_error = '83- Error. No se puede insertar a sigTrac !! ';
    return;
}
*/

}

function r_del_sigtrack(){

$this->error = 0;
$this->msg_error = '';
//    and operacion = '{$this->st_operacion}'

    $p_sql_p_d="select recordID from pdcabe_tracking_record
             where nro_track = '{$this->nro_track}'
               and estado  = 1 
              order by recordID desc  ";
$this->r_select_fila($p_sql_p_d,"pdcabe_tracking");
if ($this->error != 0 ){
   $this->error = 1;
   $this->msg_error = '102- Error. No se puede leer [pdcabe_tracking] !! '.$p_sql_p_d;
   return;
}
$p_st_recordID = $this->row['recordID'];

$p_token = $this->r_login_sigtrack();
if ($this->error != 0 || $p_token == '0'){
   return;
}

$headers = array( "Content-type: application/json",
                  "Authorization: Bearer $p_token",
                 );

$ch = curl_init();
$p_url ="https://sigtrack.com.ar/api/v2/record/".$p_st_recordID;
curl_setopt($ch, CURLOPT_URL, $p_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // SACAR
$respuesta = curl_exec($ch);
$res = json_decode($respuesta);
if ($res->response != 200){
   $this->error = 1;
   $this->msg_error = '103- Error. No se puede conectar a sigTrac !! '.$p_url;
   return;
}
curl_close($ch);

$p_sql_p="update pdcabe_tracking_record set estado = 99
           where nro_track_int = '{$this->nro_track}'
            and recordID = '$p_st_recordID' ";
$this->r_exec($p_sql_p,"pdcabe_tracking",-1);
if ($this->error != 0 ){
   $this->error = 1;
   $this->msg_error = '104- Error. No se puede actualizar [pdcabe_tracking_record] !! ';
   return;
}

if ($this->st_operacion != 'I'){ // Solo el alta se anula el tracking
   return;
}
return;

}

function r_select_pdcabe_nro_track(){

    $this->error = 0;
$this->msg_error = '';
$p_sql_p = "select * from pdcabe_tracking
           where nro_track = '{$this->st_nro_track}' 
             and estado    != 99 ";
$this->r_select_fila($p_sql_p,"pdcabe_tracking");
if ($this->error != 0 ){
    $p_sql_p = "select * from pdcabe_tracking
                 where nro_track_int = '{$this->st_nro_track}' 
                   and estado    != 99 ";
    $this->r_select_fila($p_sql_p,"pdcabe_tracking");
    if ($this->error != 0 ){
        $this->error = 1;
        $this->msg_error = '105- Error. No se puede leer [pdcabe_tracking] !! '.$p_sql_p;
        return;
    }
}
$this->empresa  = $this->row['empresa'];
$this->tdoc  = $this->row['tdoc'];
$this->letra  = $this->row['letra'];
$this->sucur  = $this->row['sucur'];
$this->numero  = $this->row['numero'];

return;
}

function r_ins_sigtrack_feedback(){

$this->error = 0;
$this->msg_error = '';

$p_sql_p= "insert into pdcabe_tracking_feedback values ( '{$this->nro_track_int}','{$this->nro_track}','{$this->empresa}','{$this->tdoc}','{$this->letra}',
                                                       '{$this->sucur}','{$this->numero}',
                                                       '{$this->st_condicion}','{$this->st_encuesta}','{$this->o_obser}',1) ";
$this->r_exec($p_sql_p,"pdcabe_tracking_feedback",1);
if ($this->error != 0){
   $this->error = 1;
   $this->msg_error = '106- Error. No se puede insertar [pdcabe_tracking] !! '.$p_sql_p;
   return;
}

}

// Candy
function r_select_pdcabe_fc()
{
$this->error     = 0;
$this->msg_error = "";
$p_sql_p="select * from pdcabe     
  where empresa     = '{$this->empresa}'
    and tdoc        = '{$this->tdoc}'
    and letra       = '{$this->letra}'
    and numero      = '{$this->numero}'
    and nro_factura = '{$this->nro_factura}'";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "107- Error. No se pudo leer [pdcabe] !! ";
   return;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error     = 1;
   $this->msg_error = "108- Error. No se pudo leer [pdcabe] !!";
   return;
}
$this->sucur          = $row['sucur'];
$this->codigo_cliente = $row['codigo_cliente'];
$this->sucursal_cliente = $row['sucursal_cliente'];
$this->vendedor       = trim($row['vendedor']);
$this->nro_oc         = trim($row['nro_oc']);
$this->ultimo_estado  = $row['ultimo_estado'];
$this->fecha_doc      = date("d-m-Y",strtotime($row['fecha_doc']));
$this->fecha_ing      = date("d-m-Y",strtotime($row['fecha_ing']));
$this->fecha_disp     = "";
if (strlen($row['fecha_disp']) > 0 && $row['fecha_disp'] != '1900-01-01'){
   $this->fecha_disp     = date("d-m-Y",strtotime($row['fecha_disp']));
}
$this->fecha_difer    = "";
if (strlen($row['fecha_difer']) > 0 && $row['fecha_difer'] != '1900-01-01'){
   $this->fecha_difer    = date("d-m-Y",strtotime($row['fecha_difer']));
}
$this->fecha_ini_comp = "";
if (strlen($row['fecha_ini_comp']) > 0 && $row['fecha_ini_comp'] != '1900-01-01'){
   $this->fecha_ini_comp = date("d-m-Y",strtotime($row['fecha_ini_comp']));
}
$this->fecha_prev_ent = "";
if (strlen($row['fecha_prev_ent']) > 0  && $row['fecha_prev_ent'] != '1900-01-01'){
   $this->fecha_prev_ent = date("d-m-Y",strtotime($row['fecha_prev_ent']));
}
$this->fecha_conf_ent = "";
if (strlen($row['fecha_conf_ent']) > 0 && $row['fecha_conf_ent'] != '1900-01-01'){
   $this->fecha_conf_ent = date("d-m-Y",strtotime($row['fecha_conf_ent']));
}
$this->fecha_difer_cliente = "";
if (strlen($row['fecha_difer_cliente']) > 0 && $row['fecha_difer_cliente'] != '1900-01-01'){
   $this->fecha_difer_cliente = date("d-m-Y",strtotime($row['fecha_difer_cliente']));
}
$this->fecha_entrega = "";
if (strlen($row['fecha_entrega']) > 0 && $row['fecha_entrega'] != '1900-01-01'){
   $this->fecha_entrega = date("d-m-Y",strtotime($row['fecha_entrega']));
}
$this->interior      = $row['interior'];
$this->tte           = trim($row['tte']);
$this->espera        = $row['espera'];
$this->espera_logistica = $row['espera_logistica'];
$this->espera_acceso = $row['espera_acceso'];
$this->contado       = $row['contado'];
$this->retira        = $row['retira'];
$this->turno         = $row['turno'];
$this->fecha_pedido_turno = "";
if (strlen($row['fecha_pedido_turno']) > 0 && $row['fecha_pedido_turno'] != '1900-01-01'){
   $this->fecha_pedido_turno = date("d-m-Y",strtotime($row['fecha_pedido_turno']));
}
$this->fecha_turno   = "";
if (strlen($row['fecha_turno']) > 0 && $row['fecha_turno'] != '1900-01-01'){
   $this->fecha_turno   = date("d-m-Y",strtotime($row['fecha_turno']));
}
$this->estado        = $row['estado'];
$this->bultos        = $row['bultos'];
$this->unidades      = $row['unidades'];
$this->volumen       = sprintf("%0.6f",$row['volumen']);
$this->otros         = $row['otros'];
$this->valor_declarado = $row['valor_declarado'];
$this->edificio      = $row['edificio'];
$this->obser         = trim($row['obser']);
$this->impreso       = $row['impreso'];
$this->etiquetado    = $row['etiquetado'];
$this->hora_pactada  = $row['hora_pactada'];
$this->hora_entrega  = $row['hora_entrega'];
$this->codigo_cliente_final = $row['codigo_cliente_final'];
$this->prioridad   = $row['prioridad'];
$this->fc_concepto   = $row['fc_concepto'];
$this->nro_track     = $row['nro_track'];
$this->directo       = $row['directo'];
$this->nro_pd        = $row['nro_pd'];
$this->tipo_rm       = $row['tipo_rm'];

$this->r_veo_tipo_pedido();

odbc_free_result($resultado);

$this->letra_fc = 'X';
$this->sucur_fc = 0;
$this->cons_final = 'N';
if ($this->tdoc != 'OR'){
   $p_sql_p = "select * from ing_ped 
where empresa  = '{$this->empresa}'
and letped   = '{$this->letra}'
and sucped   = '{$this->sucur}'
and nroped   = '{$this->numero}' ";
   $resultado=@odbc_exec($this->conexion,$p_sql_p);
   if (!$resultado){
      $this->error     = 2;
      $this->msg_error = "03- Error. No se pudo leer [ing_ped] !!";
      return;
   }
   $row=odbc_fetch_array($resultado);
   if ($row) {
      $this->letra_fc = $row['letdoc'];
      $this->sucur_fc = $row['sucdoc'];
      $this->cons_final = $row['cons_final'];
      $this->fecha_fc   = date("Ymd",strtotime($row['fecha_fc']));
   }
   odbc_free_result($resultado);
}

$this->o_obser    = "";
$this->o_obser_gl = "";
$p_sql_p="select * from pdcabe_obser
where empresa  = '{$this->empresa}'
and tdoc     = '{$this->tdoc}'
and letra    = '{$this->letra}'
and sucur    = '{$this->sucur}'
and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "04- Error. No se pudo leer [pdcabe_obser] !!";
   return;
}
$row=odbc_fetch_array($resultado);
if ($row){
   $this->o_obser    = trim($row['obser']);
   $this->o_obser_gl = trim($row['obser_gl']);
}

return;
}

function r_select_pdcabe_sin_fc()
{
$this->error     = 0;
$this->msg_error = "";
$p_sql_p="select * from pdcabe     
            where empresa     = '{$this->empresa}'
            and tdoc        = '{$this->tdoc}'
            and letra       = '{$this->letra}'
            and numero      = '{$this->numero}'
            and nro_factura = 0 ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "107- Error. No se pudo leer [pdcabe] !! ";
   return;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $this->error     = 1;
   $this->msg_error = "108- Error. No se pudo leer [pdcabe] !!";
   return;
}
$this->sucur          = $row['sucur'];
$this->codigo_cliente = $row['codigo_cliente'];
$this->sucursal_cliente = $row['sucursal_cliente'];
$this->vendedor       = trim($row['vendedor']);
$this->nro_oc         = trim($row['nro_oc']);
$this->ultimo_estado  = $row['ultimo_estado'];
$this->fecha_doc      = date("d-m-Y",strtotime($row['fecha_doc']));
$this->fecha_ing      = date("d-m-Y",strtotime($row['fecha_ing']));
$this->fecha_disp     = "";
if (strlen($row['fecha_disp']) > 0 && $row['fecha_disp'] != '1900-01-01'){
   $this->fecha_disp     = date("d-m-Y",strtotime($row['fecha_disp']));
}
$this->fecha_difer    = "";
if (strlen($row['fecha_difer']) > 0 && $row['fecha_difer'] != '1900-01-01'){
   $this->fecha_difer    = date("d-m-Y",strtotime($row['fecha_difer']));
}
$this->fecha_ini_comp = "";
if (strlen($row['fecha_ini_comp']) > 0 && $row['fecha_ini_comp'] != '1900-01-01'){
   $this->fecha_ini_comp = date("d-m-Y",strtotime($row['fecha_ini_comp']));
}
$this->fecha_prev_ent = "";
if (strlen($row['fecha_prev_ent']) > 0  && $row['fecha_prev_ent'] != '1900-01-01'){
   $this->fecha_prev_ent = date("d-m-Y",strtotime($row['fecha_prev_ent']));
}
$this->fecha_conf_ent = "";
if (strlen($row['fecha_conf_ent']) > 0 && $row['fecha_conf_ent'] != '1900-01-01'){
   $this->fecha_conf_ent = date("d-m-Y",strtotime($row['fecha_conf_ent']));
}
$this->fecha_difer_cliente = "";
if (strlen($row['fecha_difer_cliente']) > 0 && $row['fecha_difer_cliente'] != '1900-01-01'){
   $this->fecha_difer_cliente = date("d-m-Y",strtotime($row['fecha_difer_cliente']));
}
$this->fecha_entrega = "";
if (strlen($row['fecha_entrega']) > 0 && $row['fecha_entrega'] != '1900-01-01'){
   $this->fecha_entrega = date("d-m-Y",strtotime($row['fecha_entrega']));
}
$this->interior      = $row['interior'];
$this->tte           = trim($row['tte']);
$this->espera        = $row['espera'];
$this->espera_logistica = $row['espera_logistica'];
$this->espera_acceso = $row['espera_acceso'];
$this->contado       = $row['contado'];
$this->retira        = $row['retira'];
$this->turno         = $row['turno'];
$this->fecha_pedido_turno = "";
if (strlen($row['fecha_pedido_turno']) > 0 && $row['fecha_pedido_turno'] != '1900-01-01'){
   $this->fecha_pedido_turno = date("d-m-Y",strtotime($row['fecha_pedido_turno']));
}
$this->fecha_turno   = "";
if (strlen($row['fecha_turno']) > 0 && $row['fecha_turno'] != '1900-01-01'){
   $this->fecha_turno   = date("d-m-Y",strtotime($row['fecha_turno']));
}
$this->estado        = $row['estado'];
$this->bultos        = $row['bultos'];
$this->unidades      = $row['unidades'];
$this->volumen       = sprintf("%0.6f",$row['volumen']);
$this->otros         = $row['otros'];
$this->valor_declarado = $row['valor_declarado'];
$this->nro_factura   = $row['nro_factura'];
$this->edificio      = $row['edificio'];
$this->obser         = trim($row['obser']);
$this->impreso       = $row['impreso'];
$this->etiquetado    = $row['etiquetado'];
$this->hora_pactada  = $row['hora_pactada'];
$this->hora_entrega  = $row['hora_entrega'];
$this->codigo_cliente_final = $row['codigo_cliente_final'];
$this->prioridad   = $row['prioridad'];
$this->fc_concepto   = $row['fc_concepto'];
$this->nro_track     = $row['nro_track'];
$this->directo       = $row['directo'];
$this->nro_pd        = $row['nro_pd'];
$this->tipo_rm       = $row['tipo_rm'];

$this->r_veo_tipo_pedido();

odbc_free_result($resultado);

$this->letra_fc = 'X';
$this->sucur_fc = 0;
$this->cons_final = 'N';
if ($this->tdoc != 'OR'){
   $p_sql_p = "select * from ing_ped 
where empresa  = '{$this->empresa}'
and letped   = '{$this->letra}'
and sucped   = '{$this->sucur}'
and nroped   = '{$this->numero}' ";
   $resultado=@odbc_exec($this->conexion,$p_sql_p);
   if (!$resultado){
      $this->error     = 2;
      $this->msg_error = "03- Error. No se pudo leer [ing_ped] !!";
      return;
   }
   $row=odbc_fetch_array($resultado);
   if ($row) {
      $this->letra_fc = $row['letdoc'];
      $this->sucur_fc = $row['sucdoc'];
      $this->cons_final = $row['cons_final'];
      $this->fecha_fc   = date("Ymd",strtotime($row['fecha_fc']));
   }
   odbc_free_result($resultado);
}

$this->o_obser    = "";
$this->o_obser_gl = "";
$p_sql_p="select * from pdcabe_obser
where empresa  = '{$this->empresa}'
and tdoc     = '{$this->tdoc}'
and letra    = '{$this->letra}'
and sucur    = '{$this->sucur}'
and numero   = '{$this->numero}' ";
$resultado=@odbc_exec($this->conexion,$p_sql_p);
if (!$resultado){
   $this->error     = 2;
   $this->msg_error = "04- Error. No se pudo leer [pdcabe_obser] !!";
   return;
}
$row=odbc_fetch_array($resultado);
if ($row){
   $this->o_obser    = trim($row['obser']);
   $this->o_obser_gl = trim($row['obser_gl']);
}

return;
}

function r_select_sucur_pdcabe()
{
$this->error = 0;
$this->msg_error = '';
$p_sucur = 0;
$p_sql_pd = "select max(sucur) suc from pdcabe
              where empresa = '{$this->empresa}'
                and tdoc    = '{$this->tdoc}'
                and letra   = '{$this->letra}'
                and numero  = '{$this->numero}' ";
$this->r_select_fila($p_sql_pd,"pdcabe");
if ($this->error != 0 ){
   $p_sucur = 1;
}
else{
   $p_sucur = $this->row['suc'] + 1;
}
return $p_sucur;
}

static function r_busco_valor_declarado($r_empresa,$r_tdoc,$r_letra,$r_sucur,$r_numero)
{
global $Base;

$pa_return['error']   = 'OK';
$pa_return['msg']     = '';
$pa_return['importe'] = 0;

$p_sql_p="select valor_declarado from pdcabe 
           where empresa = '$r_empresa'
             and tdoc    = '$r_tdoc'
             and letra   = '$r_letra'
             and sucur   = '$r_sucur'
             and numero  = '$r_numero' ";
$resultado=@odbc_exec($Base->conexion,$p_sql_p);
if (!$resultado){
   $pa_return['error'] = 'NOK';
   $pa_return['msg']   = '107- Error. No se pudo leer [pdcabe] !! ';
   return $pa_return;
}
$row=odbc_fetch_array($resultado);
if (!$row){
   $pa_return['error'] = 'NOK';
   $pa_return['msg']   = '108- Error. No se pudo leer [pdcabe] !! ';
   return $pa_return;
}
$pa_return['importe'] = $row['valor_declarado'];

odbc_free_result($resultado);

return $pa_return;

}

static function r_busco_lineas($r_empresa,$r_letra,$r_sucur,$r_numero)
{
global $Base;

$pa_return['error'] = 'OK';
$pa_return['msg'] = '';
$pa_return['lineas'] = 0;


$p_lineas = 0;
$p_sql_p = "select secuencia,articulo
              from prop_ccr a
             where a.empresa  = '$r_empresa'
               and a.tipo_mov = 'S' 
               and a.letra    = '$r_letra'
               and a.sucur    = '$r_sucur'
               and a.numero   = '$r_numero'
               and a.condicion != 'A'
             group by secuencia,articulo ";
$resultado = @odbc_exec($Base->conexion, $p_sql_p);
if (!$resultado) {
   $pa_return['error'] = 'NOK';
   $pa_return['msg'] = '109- Error. No se pudo leer [prop_ccr] !! ';
   return $pa_return;
}
while ($row = odbc_fetch_array($resultado)) {
   $p_lineas++;
}
odbc_free_result($resultado);

$pa_return['lineas'] = $p_lineas;

return $pa_return;

}

static function r_busco_si_se_facturo($r_empresa,$r_tdoc,$r_letra,$r_sucur,$r_numero,$r_concepto)
{
global $Base;

$pa_return['error'] = 'OK';
$pa_return['msg'] = '';
$pa_return['facturado'] = 'N';

$p_sql_p = "select nro_fac from fc_remito
             where empresa   = '$r_empresa'
               and tipo_doc  = '$r_tdoc' 
               and letra_doc = '$r_letra'
               and suc_doc   = '$r_sucur'
               and nro_doc   = '$r_numero'
               and concepto  = '$r_concepto' 
               group by nro_fac";
$Base->r_select_fila($p_sql_p,"fc_remito");
if ($Base->error == 0){
   $pa_return['facturado'] = 'S';
}

return $pa_return;

}

static function r_cuantos_numeros($r_numero,$r_sucur=-1,$r_tdoc='XX',$r_letra='Z')
{
global $Base;

$p_can = 0;
$p_sql_p_r="select numero from pdcabe
             where numero = '$r_numero'  ";
if ($r_sucur != -1){
    $p_sql_p_r.=" and sucur  = '$r_sucur' ";
}
if ($r_tdoc != 'XX'){
    $p_sql_p_r.= " and tdoc = '$r_tdoc' ";
}
if ($r_letra != 'Z'){
    $p_sql_p_r.= " and letra = '$r_letra' ";
}
$p_sql_p_r.=" group by numero ";
$resultado=@odbc_exec($Base->conexion,$p_sql_p_r);
while ($row=odbc_fetch_array($resultado)){
    $p_can++;
}
odbc_free_result($resultado);

return $p_can;
}

function r_veo_tipo_pedido()
{

$this->error = 0;
$this->msg_error = '';
// tipo_pedido N el stock esta en glsa / E el stock esta en cliente o punto retiro
$this->tipo_pedido   = 'N';
$this->usa_trackeo   = 'N';
switch ($this->fc_concepto){
    case 2:
        break;
    case 3:
        break;
    case 4:
        break;
    case 30:
        break;
    case 32:
        $this->tipo_pedido     = 'E';
        $this->usa_trackeo     = 'S';
        $this->tdoc_retiro     = 'COL';
        $this->concepto_or     = 34;
        $this->concepto_or_stk = 'R02';
        break;
    case 33:
        $this->tipo_pedido     = 'E';
        $this->usa_trackeo     = 'S';
        $this->tdoc_retiro     = 'RET';
        $this->concepto_or     = 35;
        $this->concepto_or_stk = 'R03';
        break;
    case 31:
        $this->usa_trackeo = 'S';
        break;
    default:
        $this->error = 1;
        $this->msg_error = '110- Error. No encuento concepto asociado !! ';
        break;
}

}

//funcion a agregar en c-pdcabe para modificar datoss de trackeo
function r_ins_sigtrack_modif(){

$this->error = 0;
$this->msg_error = '';

$p_fec        = date("d-m-Y H:i");
$p_fecha_proc = date("Ymd H:i:s");

$p_token = $this->r_login_sigtrack();
if ($this->error != 0 || $p_token == '0'){
    return;
}
$headers = array( "Content-type: application/json",
                   "Authorization: Bearer $p_token",
                );

$ped = array();
$this->nro_track_int = str_pad($this->empresa,3,'0',STR_PAD_LEFT).
                        $this->letra.
                        str_pad($this->sucur,5,'0',STR_PAD_LEFT).
                        str_pad($this->numero,10,'0',STR_PAD_LEFT);

$p_empresa_des = r_empresa_des($this->empresa);
$p_dir         = $this->direccion." - ".r_localidad_des($this->pais,$this->provincia,$this->localidad);
$p_fecha_doc   = date("d-m-Y",strtotime($this->fecha_doc));
$p_fecha_prev  = date("d-m-Y",strtotime($this->fecha_prev_ent));
$ped = array();
$ped = array('tracking' => $this->nro_track_int,
             'empresa' => $p_empresa_des,
             'direccion_empresa' => $p_empresa_des,
             'nro_factura' => $this->nro_factura,
             'fecha_factura' => $p_fecha_doc,
             'nro_remito' => $this->numero,
             'fecha_remito' => $p_fecha_doc,
             'nro_pedido' => $this->numero,
             'nota' => '',
             'cliente' => $this->cliente,
             'direccion_entrega' => $p_dir,
             'contenido' => $this->st_contenido ) ;

$j_ped = json_encode($ped);

$ch = curl_init();
$p_url = "https://sigtrack.com.ar/api/v2/trackInfo";
curl_setopt($ch, CURLOPT_URL, $p_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $j_ped);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // SACAR
$respuesta = curl_exec($ch);
$res = json_decode($respuesta);
if ($res->response != 200){
    $this->error = 1;
    $this->msg_error = '111- Error. No se puede insertar a sigTrac !! ';
    return;
}
return;

}

function __destruct()
{
  //odbc_close($this->conexion);
}
}
?>