<?php require_once('../Connections/cn_conexion.php'); ?>
<?php include_once("../includes/funciones.php");?>
<?php 
date_default_timezone_set('America/Lima');
?>
<?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;
	}
?>

<?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;
}
}

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']);
}

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

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO documento (id_cliente, num_documento, concepto, detraccion, detracc, monto, igv, fecha_emision, fecha_cancelado, anulado, tipo_cambio, moneda, tipo_documento, hab_documento) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %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"));

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

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



$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);


$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" />
<script type="text/javascript" src="../js/ajax.js"></script>
<script type="text/javascript" src="../js/funciones.js"></script>
<script src="../src/js/jscal2.js"></script>
<script src="../src/js/lang/es.js"></script>
<link rel="stylesheet" type="text/css" href="../src/css/jscal2.css" />
<link rel="stylesheet" type="text/css" href="../src/css/border-radius.css" />
<link rel="stylesheet" type="text/css" href="../src/css/win2k/win2k.css" />
</head>

<body onload="foco_texto()">
<?php include_once("../includes/cabecera.php");?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
    <div id="contenedor_nuevo" onmouseout="cerrar_menu()">
    <div id="cont_nuevo">
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td><p class="rot_man">&nbsp;&nbsp;&nbsp;&nbsp;NUEVA <?php echo($modulo);?></p></td>
        </tr>
        <tr>
          <td height="10"></td>
        </tr>
        <tr>
          <td bgcolor="#FFFFFF"><form id="form1" name="form1" method="post" action="">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="3%" height="10"></td>
                <td width="42%"></td>
                <td width="55%"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td class="estilo_letranuevo">Número</td>
                      </tr>
                      <tr>
                        <td><input name="num_documento" type="text" class="fn_textnuevo" id="num_documento" size="20" autofocus="autofocus" onblur="next_focus('cliente')"/>
                          <input name="tipo_documento" type="hidden" id="tipo_documento" value="<?php echo($tipodoc);?>" /></td>
                      </tr>
                    </table></td>
                    <td width="50%"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Emision</p></td>
                      </tr>
                      <tr>
                        <td><input name="fecha_emision" class="fn_textnuevo" id="fecha_emision" value="<?php echo(date("d-m-Y"))?>" size="15" onfocus="limpiar_fecha(this.value,'fecha_emision')"   onblur="analizar_fecha(this.value,'fecha_emision')" onkeyup="valid_fecha(this.value,'fecha_emision')" />
                          <input type="button" name="f_btnini" id="f_btnini" value="..."  style="visibility:hidden"/>
                          </td>
                      </tr>
                    </table></td>
                    </tr>
                  </table></td>
                <td height="300" rowspan="5" valign="top">
                
                <div id="cont_buscar" style="display:none">
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                    <tr>
                      <td bgcolor="#FFFFFF"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td>&nbsp;</td>
                          </tr>
                        <tr>
                          <td>&nbsp;&nbsp;&nbsp;&nbsp;</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_normalgrande"><a href="#" class="enlace_normalgrande" 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></p>
                                    <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></td>
                    </tr>
                    <tr>
                      <td>&nbsp;</td>
                    </tr>
                  </table>
                </div>
                
                </td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><p class="estilo_letranuevo">Cliente</p></td>
                    </tr>
                  <tr>
                    <td><input name="cliente" type="text" class="fn_textnuevo" id="cliente" size="55" onkeypress="busquedaclid()" autofocus onblur="next_focus('concepto')"/>
                      <input type="button" name="button7" id="button5" value="..." onclick="buscarclid('1')"/>
                      <input name="idcliente" type="hidden" id="idcliente" />
                      <input type="hidden" name="idcli" id="idcli" />
                      <input name="activo" type="hidden" id="activo" value="0" />
					</td>
                    </tr>
                </table></td>
                </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><span class="estilo_letranuevo">Concepto</span></td>
                        <td>
                        <?php if($tipodoc=='f'){?>
                         <p>
                          <input type="checkbox" name="checkbox" id="checkbox" onclick="detraccion_d()"/>
                          <span class="estilo_letranuevo">Detracción</span></p>
                          <?php }?>
                          </td>
                      </tr>
                    </table></td>
                    </tr>
                  <tr>
                    <td>
                    <?php $detraccion="\"SUJETA A DETRACCIÓN 12% RESOLUCIÓN SUNAT Nº 183-2004 \nCUENTA BANCO DE LA NACIÓN Nº 000-364495\"";?>
                    <textarea name="concepto" cols="45" class="fn_textnuevo" id="concepto" ></textarea>
                      <input name="detracc" type="hidden" id="detracc" value="-1" />
                      <textarea name="detraccion" cols="45" class="fn_textnuevo" id="detraccion" style="display:none"><?php echo($detraccion);?></textarea></td>
                    </tr>
                </table></td>
                </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Monto</p></td>
                      </tr>
                      <tr>
                        <td><input name="monto" type="text" class="fn_textnuevo" id="monto" size="10" /></td>
                      </tr>
                    </table></td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><?php echo($nomigv);?></td>
                      </tr>
                      <tr>
                        <td><input name="igv" type="<?php echo($type);?>" class="fn_text" id="igv" value="<?php echo($igv);?>" size="10" /></td>
                      </tr>
                    </table></td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Moneda</p></td>
                      </tr>
                      <tr>
                        <td><select name="moneda" class="fn_textnuevo" id="moneda">
                          <option value="S">Soles</option>
                          <option value="D">Dolares</option>
                        </select></td>
                      </tr>
                    </table></td>
                  </tr>
                  <tr>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Cancelado</p></td>
                      </tr>
                      <tr>
                        <td><input name="fecha_cancelado" class="fn_textnuevo" id="fecha_cancelado" value="<?php //echo(date("d-m-Y"))?>" size="15" onfocus="limpiar_fecha(this.value,'fecha_cancelado')"   onblur="analizar_fecha(this.value,'fecha_cancelado')" onkeyup="valid_fecha(this.value,'fecha_cancelado')" />
                          <input name="hab_documento" type="checkbox" id="hab_documento" value="0" /></td>
                      </tr>
                    </table></td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Tipo de Cambio</p></td>
                      </tr>
                      <tr>
                        <td><input name="tipo_cambio" type="text" class="fn_textnuevo" id="tipo_cambio" value="<?php echo($compra);?>" size="10" /></td>
                      </tr>
                    </table></td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td><p class="estilo_letranuevo">Anulado</p></td>
                      </tr>
                      <tr>
                        <td><p class="estilo_letranuevo">
                          <input type="radio" name="anulado" id="radio" value="1" />
                          Si&nbsp;&nbsp;&nbsp;&nbsp;
  <input name="anulado" type="radio" id="radio2" value="0" checked="checked" />
                          No</p></td>
                      </tr>
                    </table></td>
                    </tr>
                </table></td>
                </tr>
              <tr>
                <td><input name="MM_insert" type="hidden" id="MM_insert" value="form1" /></td>
                <td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td width="78%">&nbsp;</td>
                    <td width="22%"><input type="submit" name="button2" id="button2" value="Guardar" /></td>
                    </tr>
                  </table></td>
              </tr>
              </table>
          </form></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
        </tr>
      </table>
    </div>
    </div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_cliente);

?>
