<?php
 
session_start();
$com = "C";
include("DMMYSQLG.php");
include("DSA3000.php");
include("DMMYSQLG.php");
require_once("DF30000.inc");
require_once("DF80000.php");
require_once("DFMOVCAP.inc");
require_once("DFJQUERY.inc");
?>
<html>
<link rel="stylesheet" href="css/estilo1.css" type="text/css"/>
<script type="text/javascript" language="JavaScript1.2" src="DSSCRIPT.js"></script>


<body>
<? 
/*Verifica que exista Variable contenedora del Id del Encabezado*/	
if (!isset($_REQUEST['bot'])){
	echo '<h2>!!! SELECCIONA UN REGISTRO... ACTUALIZANDO !!!</h2>';
	echo '<meta content="1; url=DV37000_PR.php"  HTTP-EQUIV="REFRESH">';
	exit();
}
/****************************************************************/

/*Llena Variable para verificar si esta en modo Update*/
if(!isset($_POST['block_mod'])){
	$bMod=false;			//Bandera de modificar, bloquea pagina en modo Modificar esperando el evento que la cambie de estado
	$bSel='';				//Id registro a modificar
}
else{
	$bMod=$_POST['block_mod'];
	$bSel=$_POST['reg_mod'];
}
/****************************************************/

$bModPri=false;					//Bandera de Modificar(True solo En el Primer Bloqueo o recarga de pagina en modo Modificar)
$id_encfac=$_REQUEST["bot"]; 	//Id de Encabezado
$id_detfac=$_POST['bot_det'];	//Id de Detalle (si se selecciono alguno)

/*Crear Objetos Necesarios para Manipular Encabezado y Detalle*/
include('DV36000_CL.php');
$dataEnc['idEncFac']=$id_encfac;
$dataDet['idEncFac']=$id_encfac;
$dataDet['idDetFac']=$id_detfac;
$encFac = new EncFac($dataEnc);
$detFac = new DetFac($dataDet);
/************************************************************/

/*Recuperar Información de Encabezado y la coloca en los objetos HTML*/
$res=$encFac->busReg();
$dt_encfac=mysqli_fetch_array($res);
$_REQUEST['tip_fac']=$dt_encfac['idTipFac'];
$_REQUEST['num_fac']=$dt_encfac['numFac'];
$_REQUEST['fec_fac']=$dt_encfac['fecFac'];
$_REQUEST['id_cli']=$dt_encfac['idBascps'];
$_REQUEST['nom_cli']=$dt_encfac['nomCli'];
$_REQUEST['tip_pro']=$dt_encfac['tipPro'];
$_REQUEST['iva_des']=$dt_encfac['ivaDes'];
$_REQUEST['cve_iva']=$dt_encfac['idTasIva'];
$_REQUEST['sub_fac']=number_format($dt_encfac['subFac'],2,'.',',');
$_REQUEST['iva_fac']=number_format($dt_encfac['ivaFac'],2,'.',',');
$_REQUEST['tot_fac']=number_format($dt_encfac['totFac'],2,'.',',');
/******************************************************************/
/*FECHA Y HORA DE CANCELACION*/
$_REQUEST['hor_can']=$dt_encfac['horCan'];
$_REQUEST['fec_can']=$dt_encfac['fecCan'];
/******************************/

/*Verificamos Si es la Primer Carga de La Pagina por si es necesario realizar alguna accion*/
if(!isset($_POST['DV37000_AGDET'])){
	$_REQUEST['id_iva']  =$dt_encfac['idTasIva'];
}
/************************************************/

/*Bloque de condiciones para Realizar las distintas operaciones sobre el detalle*/
if(isset($_POST['agregar'])){
	//codigo agregar
	$dataDet['tipNot']=$_POST['id_ope'];
	$dataDet['obsOpe']=$_POST['obs_ope'];
	$dataDet['preBas']=round($_POST['precio'],5);
	$dataDet['porDes']=round($_POST['por_des'],2);
	$dataDet['preUni']=round(($_POST['precio']*(1-$dataDet['porDes']/100)),5);	
	$dataDet['cveIva']=$_POST['id_iva'];
	$dataDet['canDet']=round($_POST['cantidad'],2);
	
	$dt_tasiva=mysqli_fetch_array(mysqli_query($con ,"SELECT * from dxtasiva WHERE cve_iva='".$dataDet['cveIva']."'"));
	//$dataDet['ivaUni']=round(($dataDet['preUni']*$dt_tasiva['porc_iva']/100),2);
	$dataDet['subDet']=round(($dataDet['preUni']*$dataDet['canDet']),2);
	$dataDet['ivaDet']=round(($dataDet['subDet']*$dt_tasiva['porc_iva']/100),2);
	$dataDet['totDet']=round(($dataDet['subDet']+$dataDet['ivaDet']),2);
	$detFac->resetData($dataDet);
	$rs=$detFac->agregar();
	if($rs){
		$_REQUEST['id_ope']  ='';
		$_REQUEST['des_ope'] ='';
		$_REQUEST['obs_ope'] ='';
		$_REQUEST['precio']  ='';
		$_REQUEST['por_des'] ='';	
		$_REQUEST['id_iva']  =$dt_encfac['idTasIva'];
		$_REQUEST['cantidad']='';		
	}
}
elseif(isset($_POST['modificar']) && isset($_POST['bot_det'])){
	//Recupera Registro de Detalle y coloca los valores en los objetos HTML
	//Cambia la bandera de modificar a True y llena la variable que contiene el id del registro a modificar
	$dt_detfacMod=mysqli_fetch_array($detFac->busReg());
	$_REQUEST['id_ope']=$dt_detfacMod['idTipNot'];
	$_REQUEST['des_ope']=$dt_detfacMod['desTipNot'];
	$_REQUEST['obs_ope']=$dt_detfacMod['obsOpe'];
	$_REQUEST['precio']=$dt_detfacMod['preBas'];
	$_REQUEST['por_des']=$dt_detfacMod['porDes'];	
	$_REQUEST['id_iva']=$dt_detfacMod['idTasIva'];
	$_REQUEST['cantidad']=$dt_detfacMod['canDet'];
	$bSel=$_POST['bot_det'];
	$bModPri=true;
	$bMod=true;
}
elseif(isset($_POST['eliminar']) && isset($_POST['bot_det'])){
	//codigo eliminar
	$rs=$detFac->eliminar();
}
elseif(isset($_POST['modificarReg'])){
	//Modificar el registro con id contenido en $bSel, posteriormente limpia $bSel
	//Cambia la bandera de modificar a False
	$dataDet['idDetFac']=$bSel;
	$dataDet['tipNot']=$_POST['id_ope'];
	$dataDet['obsOpe']=$_POST['obs_ope'];
	$dataDet['preBas']=round($_POST['precio'],5);
	$dataDet['porDes']=round($_POST['por_des'],2);
	$dataDet['preUni']=round(($_POST['precio']*(1-$dataDet['porDes']/100)),5);	
	$dataDet['cveIva']=$_POST['id_iva'];
	$dataDet['canDet']=round($_POST['cantidad'],2);
	
	$dt_tasiva=mysqli_fetch_array(mysqli_query($con ,"SELECT * from dxtasiva WHERE cve_iva='".$dataDet['cveIva']."'"));
	//$dataDet['ivaUni']=round(($dataDet['preUni']*$dt_tasiva['porc_iva']/100),2);
	$dataDet['subDet']=round(($dataDet['preUni']*$dataDet['canDet']),2);
	$dataDet['ivaDet']=round(($dataDet['subDet']*$dt_tasiva['porc_iva']/100),2);
	$dataDet['totDet']=round(($dataDet['subDet']+$dataDet['ivaDet']),2);
	$detFac->resetData($dataDet);
	$rs=$detFac->modificar();
	$_REQUEST['cantidad']='';
	$bMod=false;
	$bSel='';
	if($rs){
		$_REQUEST['id_ope']  ='';
		$_REQUEST['des_ope'] ='';
		$_REQUEST['obs_ope'] ='';
		$_REQUEST['precio']  ='';
		$_REQUEST['por_des'] ='';	
		$_REQUEST['id_iva']  =$dt_encfac['idTasIva'];
		$_REQUEST['cantidad']='';		
	}
}elseif(isset($_POST['terminarCaptura'])){
		$dt_catmov=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dvcatmov WHERE cod_usu='".$dt_encfac['idBascps']."'"));
		//Variables
		$tm = "A";//tipo de movimiento AGRAGAR (A) MODIFICAR (M) ELIMINAR (E)
		$num_reg = 0;
		$pag_reg1 = "DV37000_PR.php";
		//$pag_reg2 = "DG34000_PR.php";
		$num_doc = $dt_encfac['idTipFac'].$dt_encfac['numFac'];//numero de docuemnto 
		$cli_pro = $dt_encfac['idBascps'];//cliente
		//echo 'factura:'.$f.'<br>';
		$tip_per = "C";//CLIENTE PORVEEDOR
		$fec_doc =chfecha($dt_encfac['fecFac'],'d/m/Y','Y-m-d');//FECHA
		//buscar cta contable:
		$cve_mto=$dt_catmov['id_cta'];//CUENTA CONTABLE
		$sub_tot=$dt_encfac['subFac'];
		$iva_tot=$dt_encfac['ivaFac'];
		$total  =$dt_encfac['totFac'];
		$cve_iva=$dt_encfac['idTasIva'];
		$ret1=0;
		$ret1_po=0;
		$ret1_im=0;      
		$ret2=0;
		$ret2_po=0; 
		$ret2_im=0;
		$tot_doc=$dt_encfac['totFac'];
		//$tot_pag=0;
		$tot_pag=0;
		$tot_not=0;
		$tot_car=0;
		$tot_abo=0;
		//$tot_sal=$bus['imp_pag'];
		$tot_sal=$dt_encfac['totFac'];
		$moneda=1;
		$cve_pai=0;
		$tip_cam=0;
		$dia_cre=0;
		$con_cre=0;
		$tip_mot=0;
		$fec_ven=chfecha($dt_encfac['fecFac'],'d/m/Y','Y-m-d');
		$des="Facturacion Miscelanea";
		$regresar =0;
		include("DYDOCXCP.php");
		
		echo '<meta content="0; url=DV37000_PR.php"  HTTP-EQUIV="REFRESH">';		
		mysqli_close();
		exit();
}

/*Si Se Realizaron Operaciones sobre detalle actualiza Totales Factura*/
if($rs){
	$encFac->resetData($detFac->getTotFac());
	$encFac->actTotFac();
}
/****************************************************************/

/*Busca los Registros pertenecientes al encabezado en cuestion*/
$sq_detfac=$detFac->busByEnc();

/*************************************************************/
?>
<form name="frm1" method="post" action="DV37000_AGDET.php">
<input type="hidden" name="DV37000_AGDET" id="DV37000_AGDET" value="DV37000_AGDET.php">
<input type="hidden" name="bot" id="bot" value="<? echo $_REQUEST['bot'];?>">
<input type="hidden" name="reg_mod" id="reg_mod" value="<? echo $bSel;?>">
<input type="hidden" name="block_mod" id="block_mod" value="<? echo $bMod;?>">
<table border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <th colspan="3"><div align="center">CONSULTA DE FACTURA </div></th>
  </tr>
  <tr>
    <td nowrap style="#F9F9F9"><span class="Estilo29">Tipo:
          <label>
          <select name="tip_fac" id="tip_fac" disabled="disabled">
            <?php

	  $sq_tipfac=mysqli_query($con ,"SELECT * FROM dgtipfac");
	  if(!isset($_REQUEST['tip_fac'])){
	  	$dt_tipfac=mysqli_fetch_array($sq_tipfac);
		$selTipFac=$dt_tipfac['tip_fac'];
		if(mysqli_num_rows($sq_tipfac)>0)
			mysqli_data_seek($sq_tipfac,0);
	  }else{
	  	$selTipFac=$_REQUEST['tip_fac'];
	  }
	  while($dt_tipfac=mysqli_fetch_array($sq_tipfac)){
	  	if($selTipFac==$dt_tipfac['tip_fac'])
	  		echo '<option value="'.$dt_tipfac['tip_fac'].'" selected>'.$dt_tipfac['des_tipfac'].'</option>';
		else
			echo '<option value="'.$dt_tipfac['tip_fac'].'">'.$dt_tipfac['des_tipfac'].'</option>';
	  }
	  ?>
          </select>
          </label>
    </span></td>
    <td nowrap style="#F9F9F9"><span class="Estilo29">N&uacute;mero:
        <label>
        <input name="num_fac" type="text" id="num_fac" size="10" value="<? echo $_REQUEST['num_fac'];?>" readonly>
        </label>
    </span></td>
    <td nowrap style="#F9F9F9"><span class="Estilo29">Fecha:
          <label>
        <input name="fec_fac" type="text" class="emplea" id="fec_fac" size="10" value="<? echo $_REQUEST['fec_fac'];?>" readonly>

          </label>
    </span></td>
  </tr>
  <tr>
    <td colspan="3" nowrap style="#F9F9F9"><span class="Estilo29">Cliente:
        <input name="id_cli" type="text" id="id_cli" size="5" readonly value="<? echo trim($_REQUEST['id_cli']);?>">
        <input name="nom_cli" type="text" id="nom_cli" size="50" value="<? echo trim($_REQUEST['nom_cli']);?>" readonly>
    </span></td>
  </tr>
  <tr>
    <td nowrap style="#F9F9F9"><span class="Estilo29">IVA Desglosado:
          <label>
        <input name="iva_des" type="radio" value="1"<? if($_REQUEST['iva_des']=='1') echo 'checked';?> disabled>
        Si </label>
          <label>
          <input name="iva_des" type="radio" value="0"<? if($_REQUEST['iva_des']=='0') echo 'checked';?> disabled>
          No </label>
    </span></td>
    <td nowrap style="#F9F9F9"><span class="Estilo29" id="spanCveIva"> Tasa:
        <select name="cve_iva" id="cve_iva" disabled="disabled">
            <?php

	  	$sq_tasiva=mysqli_query($con ,"SELECT * FROM dxtasiva");
		if(!isset($_REQUEST['cve_iva'])){
			$dt_tasiva=mysqli_fetch_array($sq_tasiva);
			$selIVA=$dt_tasiva['cve_iva'];
			if(mysqli_num_rows($sq_tasiva)>0)
				mysqli_data_seek($sq_tasiva,0);
		}else{
			$selIVA=$_REQUEST['cve_iva'];
		}
		while($dt_tasiva=mysqli_fetch_array($sq_tasiva)){
			if($selIVA==$dt_tasiva['cve_iva'])
				echo "<option value=\"$dt_tasiva['cve_iva']\" selected>$dt_tasiva['conc_iva']</option>";
			else
				echo "<option value=\"$dt_tasiva['cve_iva']\">$dt_tasiva['conc_iva']</option>";	
		}	
	  ?>
        </select>
    </span></td>
    <td nowrap style="#F9F9F9"><span class="Estilo29">Tip. Proc.:
        <input name="tip_pro" type="radio" value="N"<? if($_REQUEST['tip_pro']=='N') echo 'checked';?> disabled>
      Normal
      <input name="tip_pro" type="radio" value="CFD"<? if($_REQUEST['tip_pro']=='CFD') echo 'checked';?> disabled>
      C.F.D.</span></td>
  </tr>
  <tr>
    <td colspan="3" nowrap style="#F9F9F9"><div align="center" class="Estilo29">Subtotal:
          <input name="sub_fac" type="text" id="sub_fac" size="10" value="<? echo $_REQUEST['sub_fac'];?>" readonly>
      I.V.A.:
      <input name="iva_fac" type="text" id="iva_fac" size="10" value="<? echo $_REQUEST['iva_fac'];?>" readonly>
      Total:
      <input name="tot_fac" type="text" id="tot_fac" size="10" value="<? echo $_REQUEST['tot_fac'];?>" readonly>    
    </div></td>
  </tr>
</table>
<br>
<p>&nbsp;</p>
  <table border="0" cellspacing="4" align="center" id="tableDetail">
    
	<? if($dt_encfac['esCan']){//SI ESTA CANCELADA?>
	<tr style="#999999">
	  <td colspan="8" style="#FF0000"><div align="center" class="Estilo34"><span class="Estilo35 Estilo38"><span class="Estilo37">Fecha/Hora de Cancelacion:
	          <label>
              <input name="fec_can" type="text" class="styTabEspB" id="fec_can" value="<? echo $_REQUEST['fec_can'];?>" size="10" readonly>
              </label>
          </span>
             </span>
              <span class="Estilo38">
              <input name="hor_can" type="text" class="styTabEspB" id="hor_can" value="<? echo $_REQUEST['hor_can'];?>" size="10" readonly>
              </span></div></td>
    </tr>
	<? ;}//TERMINA SI ESTA CANCELADA?>
	<tr style="#999999">
      <td nowrap class="Estilo33">Cantidad</td>
	  <td nowrap><span class="Estilo33">Descripci&oacute;n </span></td>
      <td nowrap><span class="Estilo33">Pre. Bas.</span></td>
      <td nowrap class="Estilo33">%Des.</td>
      <td nowrap class="Estilo33">Pre. Uni. </td>
      <td nowrap class="Estilo33">Subtotal </td>
      <td nowrap class="Estilo33">IVA Total </td>
      <td nowrap class="Estilo33">Total</td>
    </tr>
    <?php

		//Codigo Mostrar Detalle
		$subTotDoc=0.00;
		$ivaTotDoc=0.00;
		$totDoc=0.00;
		$subTotPar=0.00;
		$ivaTotPar=0.00;
		$totPar=0.00;
		$tipCar='-1';
		$contador=0;
		while(($dt_detfac=mysqli_fetch_array($sq_detfac))){
			$contador++;

			if($dt_detfac['idDetFac']!=$bSel){
				echo'<tr>
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['canDet'],2,'.',',').'&nbsp;
					</div></td>
					<td class="detailRowTable" ><div align="left">
							'.$dt_detfac['desTipNot'].'&nbsp;
					</div></td>
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['preBas'],2,'.',',').'&nbsp;
					</div></td>
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['porDes'],2,'.',',').'&nbsp;
					</div></td>
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['preUni'],2,'.',',').'&nbsp;
					</div></td>
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['subDet'],2,'.',',').'&nbsp;
					</div></td>																				
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['ivaDet'],2,'.',',').'&nbsp;
					</div></td>
					<td class="detailRowTable" ><div align="right">
							'.number_format($dt_detfac['totDet'],2,'.',',').'&nbsp;
					</div></td>
					</tr>';
					echo '<tr>
							<td  class="detailRowTableObs"  colspan="8"><pre>'."$dt_detfac['obsOpe']".'</pre></td>
						</tr>';
					$subTotDoc +=$dt_detfac['subDet'];
					$ivaTotDoc +=$dt_detfac['ivaDet'];
					$totDoc +=$dt_detfac['totDet'];
				}
		}
		echo '<tr><td colspan="8">&nbsp;</td></tr>
			<tr>
			<td colspan="5" class="inputcodigo"><div align="right">Total Documento: &nbsp;</div></td>
			<td colspan="1" class="inputcodigo"><div align="right">'.number_format($subTotDoc,2,'.',',').'</div></td>
			<td colspan="1" class="inputcodigo"><div align="right">'.number_format($ivaTotDoc,2,'.',',').'</div></td>
			<td colspan="1" class="inputcodigo"><div align="right">'.number_format($totDoc,2,'.',',').'</div></td>
			</tr>';		
		
	?>
	<tr>
	 	<td colspan="9"><div align="center"><input type="button" name="regresar" id="regresar" value="Regresar" onClick="openpage('DV37000_PR.php','_self')">
	 	</div></td>
	</tr>
  </table>
  <p>&nbsp;</p>
</form>
</body>
</html>
