<?php

session_start();
include("DMMYSQLG.php");
include("DSA1000.php");
include("DMMYSQLG.php");
//incluímos la clase ajax
require ('xajax/xajax_core/xajax.inc.php');
//instanciamos el objeto de la clase xajax
$xajax = new xajax(); 

function cancela($form_entrada){
	$sq=mysqli_query($con ,"SELECT nparte1 FROM frecomp order by nparte1 desc");
	$re = mysqli_fetch_array($sq);
	$ssql = "delete from frecomp where nparte1='".$re['nparte1']."'";
   		if (mysqli_query($con ,$ssql)){
	    	$salida = "Insertado correctamente";
   	   }else{
	      	$salida = "No se ha insertado. Este es el error: " . mysqli_error($con);
   	   }
}

function procesar_form($form_entrada){
$uno=substr($form_entrada["fecini"], 0, 2);
$dos=substr($form_entrada["fecini"], 3, 2);
$tres=substr($form_entrada["fecini"], 6, 4);
$cad2 = ($tres."-".$dos."-".$uno);
$uno1=substr($form_entrada["fecfin"], 0, 2);
$dos1=substr($form_entrada["fecfin"], 3, 2);
$tres1=substr($form_entrada["fecfin"], 6, 4);
$cad3 = ($tres1."-".$dos1."-".$uno1);

$ssql = "insert into frecomp (nparte1,np_desc1,descripcion,fec_ini_pro,fec_fin_pro,usuario) values ('" . $form_entrada["txtnot"] . "','" . $form_entrada["txtemp"] . "','" . $form_entrada["agrup"] . "','" .$cad2. "','" . $cad3 . "','".$_SESSION['num_usu']."')";
	if (mysqli_query($con ,$ssql)){
		$salida = "Insertado correctamente";
	}else{
	    $salida = "No se ha insertado. Este es el error: " . mysqli_error($con);
	}
}

function mod_rec($form_entrada){
$sq=mysqli_query($con ,"SELECT SUM(subpre) as total FROM frecomart where codfre='" . $form_entrada["txtnot"] . "' ");
$re = mysqli_fetch_array($sq);
$ssql = "UPDATE frecomp SET total_rec='".$re['total']."' where nparte1='" . $form_entrada["txtnot"] . "'";	
	if (mysqli_query($con ,$ssql)){
    	$salida = "Insertado correctamente";
	}else{
	    $salida = "No se ha insertado. Este es el error: " . mysqli_error($con);
	}
}

function elimina($form_entrada){
 if(!empty($form_entrada["txtcod"])) {
  $aLista=array_keys($form_entrada["txtcod"]);
  $sQuery="DELETE from frecomart where nparte1 IN (".implode(',',$aLista).")";
  mysqli_query($con ,$sQuery);
 }
}

function elimina_todo($form_entrada){
$ssql = "DELETE  from frecomart where codfre='" . $form_entrada["txtnot"] . "' ";
	if (mysqli_query($con ,$ssql)){
		$salida = "Insertado correctamente";
	}else{
	    $salida = "No se ha insertado. Este es el error: " . mysqli_error($con);
	}
}
		
function agregar_art($form_entrada){
if ((!empty($form_entrada["txtclav"])) and ($form_entrada["txtclav"]!=0)) {
$sq=mysqli_query($con ,"SELECT codart,cant FROM frecomart where codfre='" . $form_entrada["txtnot"] . "' and codart='" . $form_entrada["txtclav"] . "' ");
$re = mysqli_fetch_array($sq);
	if ($re['codart']==$form_entrada["txtclav"]){
		$agre=$re['cant']+$form_entrada["txtcant"];
		$ssql = "UPDATE frecomart SET cant='$agre', subpre='" . $form_entrada["txtpre"]*$agre. "'  where codart='" . $form_entrada["txtclav"] . "' and codfre='" . $form_entrada["txtnot"] . "'";
   		if (mysqli_query($con ,$ssql)){
		      $salida = "Insertado correctamente";
		}else{
		      $salida = "No se ha insertado. Este es el error: " . mysqli_error($con);
	    }
	}else {
	$sq=mysqli_query($con ,"SELECT fec_ini_pro,fec_fin_pro FROM frecomp where nparte1='" . $form_entrada["txtnot"] . "'");
	$re = mysqli_fetch_array($sq);		
	//---------
	$num=mysqli_fetch_array($a=mysqli_query($con ,"select nparte1 from frecomart order by nparte1 desc limit 1"));
	$cont=$num['nparte1']+1; //----
	$ssql = "insert into frecomart (nparte1,codfre,codart,desc_art,cant,uni_med,nom_prov,clav_prov,precio,subpre,clav_mar,nom_mar,cos_prom,fec_ini,fec_fin) values ('".$cont."','" . $form_entrada["txtnot"] . "','" . $form_entrada["txtclav"] . "','" . $form_entrada["art"] . "','" .$form_entrada["txtcant"]. "','" . $form_entrada["txtunid"] . "','" . $form_entrada["prov"] . "','" . $form_entrada["txtclavpv"] . "','" . $form_entrada["txtpre"] . "','" . $form_entrada["txtpre"]*$form_entrada["txtcant"] . "','" . $form_entrada["txtcvmar"] . "','" . $form_entrada["marca"] . "','" . $form_entrada["txtprom"] . "','" . $re['fec_ini_pro'] . "','" . $re['fec_fin_pro']. "')";
   		if (mysqli_query($con ,$ssql)){
			$salida = "Insertado correctamente";
		}else{
		    $salida = "No se ha insertado. Este es el error: " . mysqli_error($con);
		}	
	}
}

}

//registramos la función creada anteriormente al objeto xajax
$xajax->registerFunction("cancela");
$xajax->registerFunction("procesar_form");
$xajax->registerFunction("agregar_art");
$xajax->registerFunction("mod_rec");
$xajax->registerFunction("elimina");
$xajax->registerFunction("elimina_todo");
//El objeto xajax tiene que procesar cualquier petición
$xajax->processRequest();
$com = "A";
include("DF30000.inc");
include("DF80000.php");
include("DFJSISCI.inc");
require_once("DFJQUERY.inc");
?>
<html>

<? //En el <head> indicamos al objeto xajax se encargue de generar el javascript necesario 
$xajax->printJavascript("xajax/"); ?>
</head>
<body>
<div align="center">
<form name="form1" method="post" action="" enctype="multipart/form-data"
 <?php
  @$sql23=mysqli_query($con ,"SELECT nparte1 FROM frecomp order by nparte1 desc");
			@$reg23 = mysqli_fetch_array($sql23);
			?>	>
<table width="894" height="74" border="0">
      <tr>
        <th height="19" colspan="4" scope="col">PERIODO</th>
        <th width="106" scope="col">No. ORDEN </th>
        <th width="197" scope="col">DEPARTAMENTO</th>
        <th width="197" scope="col">AGRUPADOR</th>
      </tr>
      <tr>
        <td width="137" height="23" style="border:none"><div align="center" class="estiloFecha"> Del
            <input name="fecini" type="text" class="Estilo3" id="fecini" size="15" 
			  	<?php
 
					if(isset($_POST['fecini']))
						echo 'value="'.$_POST['fecini'].'"'; 
				  	else
				    	echo 'value="'.date('d/m/Y').'"'; 
				?> >
        </div></td>
        <td width="33" style="border:none"><div id="fec" align="center">
          <input name="reset2" id="bot1" value=" ... " type="image" src="logos/cal4.jpg" />
		  		    <script type="text/javascript">
				  	Calendar.setup(
    					{
      						inputField  : "fecini",        // ID of the input field
      						ifFormat    : "%d/%m/%Y",    // the date format
      						button      : "bot1"      // ID of the button
    					}
  					);
			  	</script>
        </div></td>
        <td width="135" style="border:none"><div align="center" class="estiloFecha">al
          	<input name="fecfin" type="text" class="Estilo3" id="fecfin" size="15" 
			<?php
  
				if(isset($_POST['fecfin']))
			  		echo 'value="'.$_POST['fecfin'].'"'; 
			  	else 
			  		echo 'value="'.date('d/m/Y').'"'; 
			?>>
        </div></td>
        <td width="34" style="border:none"><div id="fec1" align="center">
          <input name="fecf" id="fecf" value=" ... " type="image" src="logos/cal4.jpg"/>
		  <script type="text/javascript">
				  	Calendar.setup(
    					{
      						inputField  : "fecfin",        // ID of the input field
      						ifFormat    : "%d/%m/%Y",    // the date format
      						button      : "fecf"      // ID of the button
    					}
  					);
			    </script>

        </div></td>
        <td><div align="center" style="font-size:12px">
          <input name="txtnot" type="hidden" id="txtnot" style="border:none; background:none;" value="<?php
  echo $reg23["nparte1"]+1; ?>" size="5" align="middle"> <?php
  echo $reg23["nparte1"]+1; ?>
        </div>
        </label></td>
        <td><div align="center">
          <select name="txtemp">
            <option value="SIN DEPARTAMENTO">-----Selecciona-----</option>
            <?php

	@$res=mysqli_query($con ,"select np_desc1 from fdepartamento order by np_desc1 ASC");
	while(@$reg=mysqli_fetch_array($res)){
		if($_POST['txtemp']==$reg['np_desc1']){
			echo '<option value="' . $reg['np_desc1'] . '" selected>' . $reg['np_desc1'] . '</option>';
		}else{
			echo '<option value="' . $reg['np_desc1'] . '">' . $reg['np_desc1'] . '</option>';
		}
	}
	?>
          </select>
        </div></td>
        <td><div align="center">
          <select name="agrup" onChange="javascript: document.getElementById('form1').submit()">
            <option value="">-----Selecciona-----</option>
            <?php

	@$res=mysqli_query($con ,"select * from fagrupadores order by np_desc1 ASC");
	while(@$reg=mysqli_fetch_array($res)){
		if($_POST['agrup'] == $reg['np_desc1']){
			echo '<option value="' . $reg['np_desc1'] . '" selected>' . $reg['np_desc1'] . '</option>';
		}else{
			echo '<option value="' . $reg['np_desc1'] . '">' . $reg['np_desc1'] . '</option>';
		}
	}
	?>
          </select>
        </div></td>
      </tr>
      <tr>
        <td height="24" colspan="3" style="border:none"><div id="botones" align="left">
          <label>
          <input type="reset" class="clase2" name="borrar" value="CANCELAR" onClick="xajax_cancela(xajax.getFormValues('form1'));hab(this);ocultar('sub1');mostrar('fec');mostrar('fec1')" style="display:none">
          <input type="button" name="slec" class="botonmen" value="SELECCIONAR PROD" size="20" onClick="xajax_procesar_form(xajax.getFormValues('form1'));mostrar('sub1');desactiva(this);ocultar('fec');ocultar('fec1')">
          </label>
        </div></td>
        <td style="border:none">&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td></td>
      </tr>
    </table>
  </form>
</div>

<form name="consulta" id="consulta" method="post" action="">
<div align="center" id="sub1" style="display:none" >
  <table width="894" height="67"  border="0" align="center">
<input name='txtnot' type='hidden'  id='txtnot' value=" <?php
 echo $reg23["nparte1"]+1; ?>" >
	    <tr>
        <th height="15" colspan="5"  nowrap>SELECCIONAR ARTICULOS </th>
        <td width="4" rowspan="3"  nowrap>&nbsp;</th>
        <th height="15" colspan="2"  nowrap>DATOS DEL PROVEEDOR</th>
      </tr>
      <tr>
        <th width="46" height="16"  nowrap><div align="center">CLAVE</div></th>
        <th width="188"  nowrap><div align="center">DESCRIPCION</div></th>
		<th width="70"  nowrap><div align="center">CANTIDAD</div></th>
		<th width="116"  nowrap><div align="center">UNIDAD MEDIDA </div></th>
		<th width="75"  nowrap><div align="center">PRECIO</div></th>
	    <th width="53"  nowrap>CLAVE</th>
	    <th width="308"  nowrap>NOMBRE</th>
      </tr>
	<tr>
	  <td height="25"> <div align='center'><input name='txtclav' type='text'  id='txtclav' style="border:none; background:none" value="" size="8" readonly="">
		</div></td>
		<td> <div align='center' id="articulos">     		
<?php
 
$qry=mysqli_query($con ,"select * from farticulos where t7='".$_POST['agrup']."'"); 
$row=array(); 
while($r=mysqli_fetch_assoc($qry)){ 
	$row[]=array($r['np_desc1'],$r['nparte1'],$r['pais'],$r['t3'],$r['cos_prom']);  } ?> 
	 <select name="art" id="art" onChange="document.getElementById('txtunid').value=this.options[this.selectedIndex].getAttribute('medidad');
  document.getElementById('txtclav').value=this.options[this.selectedIndex].getAttribute('claved');  
   document.getElementById('txtprom').value=this.options[this.selectedIndex].getAttribute('promedio');  document.getElementById('txtpre').value=this.options[this.selectedIndex].getAttribute('precio'); ">
  <option value="0">---Selecciona---</option> 
<?php
 foreach($row as $v){  
if($_POST['art'] == $v[0]){ ?>
<option medidad="<?php
 echo $v[2] ?>" claved="<?php
 echo $v[1] ?>" precio="<?php
 echo $v[3] ?>" promedio="<?php
 echo $v[4] ?>" value="<?php
 echo $v[0] ?>"><?php
 echo $v[0] ?></option> 
			
 <?php
		}else{ ?>
<option medidad="<?php
 echo $v[2] ?>" claved="<?php
 echo $v[1] ?>" precio="<?php
 echo $v[3] ?>" promedio="<?php
 echo $v[4] ?>" value="<?php
 echo $v[0] ?>"><?php
 echo $v[0] ?></option> 
		 <?php
 }  ?>
    
<?php
 }?> 
  </select> 
			 </div></td>
		<td> <div align='center'><input name='txtcant' type='text'  id='txtcant' size='10' onKeyUp=" var pattern = /[^0-9\.]/g; this.value = this.value.replace(pattern, ''); "></div></td>
		<td> <div align='center'><input name='txtunid' type='text'  id='txtunid' style="border:none; background:none" value="" size="10" readonly=""></div></td>
	<td> <div align="center"><input name="txtpre" type="text" style="border:none; background:none" value="" size="10" readonly=""> <input name='txtprom' type='hidden'  id='txtprom' style="border:none; background:none" value="" size="10" readonly=""></div></td>
	<td><div align='center'>
	  <input name='txtclavpv' type='text'  id='txtclavpv' style="border:none; background:none" value="" size="7" readonly="">
    </div></td>
	<td><div align='center'>
      <?php
  $qry2=mysqli_query($con ,"select * from fproveedores where proveedor='".$_POST['agrup']."'"); 
$row2=array(); 
while($r2=mysqli_fetch_assoc($qry2)){ 
	$row2[]=array($r2['np_desc1'],$r2['nparte1'],$r2['proveedor']); }   ?>
      <select name="prov" id="prov" onChange="document.getElementById('txtclavpv').value=this.options[this.selectedIndex].getAttribute('claved')">
        <option value="SIN PROVEEDOR">---Selecciona---</option>
        <?php
 foreach($row2 as $v2){ ?>
        <option medidad="<?php
 echo $v2[2] ?>" claved="<?php
 echo $v2[1] ?>" value="<?php
 echo $v2[0] ?>"><?php
 echo $v2[0] ?></option>
        <?php
 }?>
      </select>
    </div></td>
	</tr>
 </table>
  <table width="894" height="61" border="0">
    <tr>
      <td height="15"  nowrap><div align="left"></div></td>
      <td height="15" colspan="2"  nowrap>&nbsp;</td>
      <th height="15" colspan="3"  nowrap>DATOS DE LA MARCA</th>
    </tr>
    <tr>
      <td width="53" height="15"  nowrap>&nbsp;</td>
      <td width="101"  nowrap>
        <div align="left">
          <input name="reset" type="reset" class="botonmen" onClick="xajax_agregar_art(xajax.getFormValues('consulta'));ocultar('botones');javascript:recargar();mostrar('art1');" value="AGREGAR" >
          </div></td>
      <td width="398"  nowrap><input name="nuevo" type="button" class="botonmen" onClick="MM_openBrWindow('CO20001_AG.php?pas=<? echo $_POST['agrup']; ?>','','');javascript:recargar3()" value="NUEVO ART."></td>
      <th width="57"  nowrap>CLAVE</th>
      <th width="263" colspan="2"  nowrap>MARCA</th>
    </tr>
<tr>
		<td height="23">&nbsp;</td>
		<td colspan="2">&nbsp;</td>
		<td><div align='center'>
		  <input name='txtcvmar' type='text'  id='txtcvmar' style="border:none; background:none" value="" size="7" readonly="">
        </div></td>
        <td colspan="2"><div align='center'>
			<?php
 
$qry3=mysqli_query($con ,"select * from comar order by np_desc1 asc"); 
$row3=array(); 
while($r3=mysqli_fetch_assoc($qry3)){ 
$row3[]=array($r3['np_desc1'],$r3['nparte1']); 
} 
 ?>
 	         <select name="marca" id="select" onChange="document.getElementById('txtcvmar').value=this.options[this.selectedIndex].getAttribute('claved')">
            <option value="SIN MARCA">---Selecciona---</option>
            <?php
 foreach($row3 as $v3){ ?>
            <option claved="<?php
 echo $v3[1] ?>" value="<?php
 echo $v3[0] ?>"><?php
 echo $v3[0] ?></option>
            <?php
 }?>
          </select>
        </div></td>
 </tr>
  </table> </div>
 </form>
<form  name="frm1" action="" method="post">
<div  id="art1" align="center" style="display:none">
  <table width="894" border="0" align="center">
    <tr>
       <td width="118"><div align="center" id="act">
        <input name="actualzar" type="button" class="botonmen" onClick="javascript:recargar()" value="ACTUALIZAR">
      </div></td>
  	  <td width="105"><div align="center" id="elim">
        <input name="elim" type="button" class="botonmen" onClick="xajax_elimina(xajax.getFormValues('frm1'));javascript:recargar();" style="font-size:14px" value="X">
      </div></td>
      <td width="563"><div align="left" id="terminar"><input name="closed" type="submit" class="clase2" onClick="xajax_elimina_todo(xajax.getFormValues('frm1'));xajax_cancela(xajax.getFormValues('form1'));" value="CANCELAR"></div></td>
	      <td width="90" height="25">
        <div align="left" id="termina">
          <input name="cerrar" type="button" class="botonmen" onClick="xajax_mod_rec(xajax.getFormValues('frm1'));mostrar('total');mostrar('tot');mostrar('tot2');mostrar('imp');mostrar('nvo');ocultar('terminar');ocultar('termina');ocultar('elim');ocultar('act');ocultar('sub1');" value="TERMINAR">	
          </div></td>
        <td width="90" height="25">
        <div id="nvo" align="left" style="display:none">
          <input name="nv" type="button" class="botonmen" onClick="envi('CO20000_PR.php','_self','frm1')" value="NUEVA ORDEN">	
         </div></td>
         <td width="90" height="25">
        <div id="imp" align="left" style="display:none">
          <input name="nv" type="button" class="botonmen" onClick="envia2('CO20001_IM.php','_self','frm1');" value="IMPRIMIR">
		</div></td>
    </tr>
  </table>
 </div>
<div id="recargado" align="center"></div>
</div>
</form> 

</body>
</html>

<?php
 mysqli_close($con);?>