<?php require_once('../Connections/cn_conexion.php'); ?>
<?php include_once("../includes/funciones.php");?>
<?php  mysql_query("SET NAMES 'utf8'"); ?>
<?php
if(isset($_POST["hab_documento"])){
	$hab_documento=$_POST["hab_documento"];
	}else{
		$hab_documento='1';
		}
if(isset($_POST["tipo_documento"])){
	$tipodoc=$_POST["tipo_documento"];
	}else{
		$tipodoc=$_GET["tipo_doc"];
		}
switch($tipodoc){
	case "f":
		$nom_doc="Factura";
		$type="text";
		$nomigv="%IGV";
		break;
	case "b":
		$nom_doc="Boleta";
		$type="hidden";
		$nomigv="";
		break;
	}
if(isset($_POST['num_documento'])){
	$num_documento=$_POST['num_documento'];
	$numdocumento=$_POST['numdocumento'];
	}
?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

switch($tipodoc){
	case "f":
		$_SESSION["modulo"]="FACTURA";
		break;
	case "b":
		$_SESSION["modulo"]="BOLETA";
		break;
}

if($_SESSION["tipo_sesion"]!="1"){
	header("location:../".$_SESSION["ruta_permitida"]);
	}
$modulo=$_SESSION["modulo"];
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "../index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "../index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}


// Analisis si el documento esta repetido
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
	if($num_documento!=$numdocumento){
		$act_docbusqueda=busqueda_docrepetido($database_cn_conexion, $cn_conexion, $tipodoc, $num_documento);
		}
if($act_docbusqueda=='1'){
	$_POST["MM_update"]="";
	unset($_POST["MM_update"]);
	$mensaje="El número de documento que ha intentado ingresar esta repetido";	
	echo("<script>alert('".$mensaje."');</script>");
	}
}
// Fin del analisis


if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
	if(isset($_POST['detracc'])){
		$detracc=$_POST['detracc'];		
		switch($detracc){
			case '-1':
				$detraccion="";
				break;
			case '1':
				$detraccion=$_POST['detraccion'];
				break;
			}
	}else{
		$detraccion="";
		$detracc="-1";
		}
}


if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
  $updateSQL = sprintf("UPDATE documento SET id_cliente=%s, num_documento=%s, concepto=%s, detraccion=%s, detracc=%s, monto=%s, igv=%s, fecha_emision=%s, fecha_cancelado=%s, anulado=%s, tipo_cambio=%s, moneda=%s, tipo_documento=%s, hab_documento=%s WHERE id_documento=%s",
                       GetSQLValueString($_POST['idcliente'], "int"),
                       GetSQLValueString($_POST['num_documento'], "text"),
					   GetSQLValueString($_POST['concepto'], "text"),
					   GetSQLValueString($detraccion, "text"),
					   GetSQLValueString($detracc, "text"),
                       GetSQLValueString($_POST['monto'], "double"),
                       GetSQLValueString($_POST['igv'], "double"),					   
                       GetSQLValueString(fecha_peru($_POST['fecha_emision']), "date"),
                       GetSQLValueString(fecha_peru($_POST['fecha_cancelado']), "date"),
					   GetSQLValueString($_POST['anulado'], "text"),
                       GetSQLValueString($_POST['tipo_cambio'], "double"),
                       GetSQLValueString($_POST['moneda'], "text"),
                       GetSQLValueString($_POST['tipo_documento'], "text"),
                       GetSQLValueString($hab_documento, "text"),					   
                       GetSQLValueString($_POST['id_documento'], "int"));

  mysql_select_db($database_cn_conexion, $cn_conexion);
  $Result1 = mysql_query($updateSQL, $cn_conexion) or die(mysql_error());

  $updateGoTo = "documento.php?tipo_doc=".$tipodoc;
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

$colname_rs_usuario = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_rs_usuario = $_SESSION['MM_Username'];
}
mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_usuario = sprintf("SELECT * FROM usuarios WHERE dni_usuario = %s", GetSQLValueString($colname_rs_usuario, "text"));
$rs_usuario = mysql_query($query_rs_usuario, $cn_conexion) or die(mysql_error());
$row_rs_usuario = mysql_fetch_assoc($rs_usuario);
$totalRows_rs_usuario = mysql_num_rows($rs_usuario);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_cliente = "SELECT * FROM clientes WHERE clientes.hab_cliente='1' ORDER BY clientes.nom_cliente ASC";
$rs_cliente = mysql_query($query_rs_cliente, $cn_conexion) or die(mysql_error());
$row_rs_cliente = mysql_fetch_assoc($rs_cliente);
$totalRows_rs_cliente = mysql_num_rows($rs_cliente);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_documento = "SELECT * FROM documento, clientes WHERE documento.tipo_documento='".$tipodoc."' AND documento.anulado='0' AND clientes.id_cliente=documento.id_cliente ORDER BY documento.hab_documento DESC, documento.num_documento DESC";
$rs_documento = mysql_query($query_rs_documento, $cn_conexion) or die(mysql_error());
$row_rs_documento = mysql_fetch_assoc($rs_documento);
$totalRows_rs_documento = mysql_num_rows($rs_documento);

$compra=$_SESSION["compra"];
$venta=$_SESSION["venta"];
$igv=$_SESSION["igv"];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SISTEMA DE FACTURACION</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css" />
<link href="../css/estilos_imprimir.css" rel="stylesheet" type="text/css" media="print" />
<script type="text/javascript" src="../js/ajax.js"></script>
<script type="text/javascript" src="../js/funciones.js"></script>
<script language="Javascript">
function imprSelec(iddoc)
{
	document.getElementById('form2').action='../reporte_pdf/imprimirdoc.php';
	document.getElementById('form2').target='_blank';
	document.getElementById('form2').submit();
}
</script>
</head>

<body>
<?php include_once("../includes/cabecera.php");?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
    <div id="contenedor" onmouseout="cerrar_menu()">
    <div id="cont_buscar" style="display:none">
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td><p class="rot_man">&nbsp;&nbsp;&nbsp;&nbsp;Busqueda de Clientes</p></td>
        </tr>
        <tr>
          <td height="10"></td>
        </tr>
        <tr>
          <td bgcolor="#FFFFFF"><form id="form2" name="form2" method="post" action="">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;
<input name="nombrecliente" type="text" id="nombrecliente" size="100" onkeypress="busqueda_cli()"/>
                  <input type="button" name="button3" id="colocar_cli" value="Colocar" style="visibility:hidden" onclick="colocarclid()"/>
                  <input name="activo" type="hidden" id="activo" value="0" />
                  <input type="hidden" name="idcli" id="idcli" /></td>
              </tr>
              <tr>
                <td>
                <div id="listado_clientes" class="cont_list">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <?php do { ?>
                    <tr>
                      <td width="2%" height="20" align="center">&nbsp;</td>
                      <td width="95%"><p class="enlace_normal"><a href="#" class="enlace_normal" onclick="selec_cliente('<?php echo ($row_rs_cliente['nom_cliente']); ?>@@<?php echo($row_rs_cliente['id_cliente']);?>')"><?php echo $row_rs_cliente['nom_cliente']; ?></a><hr /></p></td>
                      <td width="4%">&nbsp;</td>
                    </tr>
                    <?php } while ($row_rs_cliente = mysql_fetch_assoc($rs_cliente)); ?>
                    <tr>
                      <td align="center">&nbsp;</td>
                      <td>&nbsp;</td>
                      <td>&nbsp;</td>
                    </tr>
                </table>
                </div>
                </td>
              </tr>
            </table>
          </form></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
        </tr>
    </table>
    </div>
    <div id="contenedor_p">
      <div id="clientes_lista" class="flotante_izq">
    	  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    	    <tr>
    	      <strong>
    	      <td colspan="3">Lista de <?php echo($nom_doc."s");?>
   	          <input name="tipo_doc" type="hidden" id="tipo_doc" value="<?php echo($tipodoc);?>" /></td></strong>
   	        </tr>
    	    <tr>
    	      <td colspan="3"><input name="buscar_gasto" type="text" class="fn_text" id="buscar_gasto" size="75" onkeypress="lista_facturas(this.value)" /></td>
   	        </tr>
    	    <tr>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
  	      </tr>
    	    <tr>
    	      <td colspan="3">
              <div id="busqueda">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td width="12%" align="center" bgcolor="#110167"><p class="texto_normal">Numero</p></td>
                          <td width="40%" height="25" bgcolor="#110167"><p class="texto_normal">Cliente</p></td>
                          <td width="12%" bgcolor="#110167"><p class="texto_normal">Monto</p></td>
                          <td width="11%" bgcolor="#110167"><p class="texto_normal">Moneda</p></td>
                          <td width="12%" bgcolor="#110167"><p class="texto_normal">Emisión</p></td>
                          <td width="13%" bgcolor="#110167"><p class="texto_normal">Cancelación</p></td>
                        </tr>
                      </table></td>
                    </tr>
                    <tr>
                      <td>
                      <?php if($totalRows_rs_documento>0){?>
              <div id="cont_listdoc">
                
                  <?php do { ?>
                  <?php
                  if($row_rs_documento['hab_documento']=='0'){
				    $classe_colortexto="enlace_cancelar";
					$clase_texto='class="texto_cancelar"';
					}else{
						$classe_colortexto="enlace_normal";
						$clase_texto="";
						}
				  ?>
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="12%" height="25" align="center"><p <?php echo($clase_texto);?>>
                        <?php $num_doc=$row_rs_documento['num_documento']; echo($num_doc); ?>
                      </p></td>
                      <td width="40%"><p><a href="#" class="<?php echo($classe_colortexto);?>" onclick="modificar_documento('<?php echo $row_rs_documento['id_documento']; ?>')">
                        <?php $nom_cli=$row_rs_documento['nom_cliente']; echo($nom_cli);?>
                      </a></p></td>
                      <td width="12%" align="right"><p <?php echo($clase_texto);?>>
                        <?php $monto=$row_rs_documento['monto']; echo(number_format(decimals($monto),2));?>
                      &nbsp;&nbsp;&nbsp;</p></td>
                      <td width="11%" align="center"><p <?php echo($clase_texto);?>>
                        <?php $moneda=$row_rs_documento['moneda']; if($moneda=='S'){echo("Soles");}else{echo("Dolares");} ?>
                      </p></td>
                      <td width="12%"><p <?php echo($clase_texto);?>>
                        <?php $emision=$row_rs_documento['fecha_emision']; echo(fecha_peru($emision));?>
                      </p></td>
                      <td width="13%"><p <?php echo($clase_texto);?>>
                        <?php $cancelado=$row_rs_documento['fecha_cancelado']; echo(fecha_peru($cancelado));?>
                      </p></td>
                    </tr>
                 </table>
                    <?php } while ($row_rs_documento = mysql_fetch_assoc($rs_documento)); ?>
               
              </div> 
              <?php  }else{
				  echo("No hay documentos encontrados");
				  }?>
                      </td>
                    </tr>
                  </table>
              </div>
              </td>
  	      </tr>
    	    <tr>
    	      <td colspan="3">&nbsp;</td>
    	      </tr>
    	    <tr>
    	      <td colspan="3">&nbsp;
              </td>
   	        </tr>
    	    <tr>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
  	      </tr>
  	    </table>
    	</div>
        <div id="documento_man" class="flotante_izq">
          <div id="documento_mant">
        	<img src="../imagenes/mod_documento.png" width="457" height="259" />
            </div>
        </div>
        <div class="limpiar">&nbsp;</div>
        </div>
    &nbsp;</div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_cliente);

mysql_free_result($rs_documento);
?>
