<?php require_once('../Connections/cn_conexion.php'); ?>
<?php 
date_default_timezone_set('America/Lima');
mysql_query("SET NAMES 'utf8'");
?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

$_SESSION["modulo"]="CLIENTES";
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']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO clientes (nom_cliente, contacto, dir_cliente, dis_cliente, telf_cliente, cel_cliente, ruc_cliente, email_cliente, hab_cliente) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['nom_cliente'], "text"),
                       GetSQLValueString($_POST['contacto'], "text"),
					   GetSQLValueString($_POST['direccion'], "text"),
                       GetSQLValueString($_POST['distrito'], "text"),
                       GetSQLValueString($_POST['telefono'], "text"),
                       GetSQLValueString($_POST['Celular'], "text"),
                       GetSQLValueString($_POST['ruc'], "text"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['hab_cliente'], "text"));

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

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

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
  $updateSQL = sprintf("UPDATE clientes SET nom_cliente=%s, contacto=%s, dir_cliente=%s, dis_cliente=%s, telf_cliente=%s, cel_cliente=%s, ruc_cliente=%s, email_cliente=%s, hab_cliente=%s WHERE id_cliente=%s",
                       GetSQLValueString($_POST['nom_cliente'], "text"),
					   GetSQLValueString($_POST['contacto'], "text"),
                       GetSQLValueString($_POST['direccion'], "text"),
                       GetSQLValueString($_POST['distrito'], "text"),
                       GetSQLValueString($_POST['telefono'], "text"),
                       GetSQLValueString($_POST['Celular'], "text"),
                       GetSQLValueString($_POST['ruc'], "text"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['hab_cliente'], "text"),
                       GetSQLValueString($_POST['id_cliente'], "int"));

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

  $updateGoTo = "index.php";
  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_clientes = "SELECT * FROM clientes ORDER BY clientes.nom_cliente  ASC";
$rs_clientes = mysql_query($query_rs_clientes, $cn_conexion) or die(mysql_error());
$row_rs_clientes = mysql_fetch_assoc($rs_clientes);
$totalRows_rs_clientes = mysql_num_rows($rs_clientes);

mysql_select_db($database_cn_conexion, $cn_conexion);
$query_rs_distrito = "SELECT * FROM distrito WHERE (distrito.iddep='15' OR  distrito.iddep='07' )  AND distrito.idprov='01' ORDER BY distrito.distrito ASC";
$rs_distrito = mysql_query($query_rs_distrito, $cn_conexion) or die(mysql_error());
$row_rs_distrito = mysql_fetch_assoc($rs_distrito);
$totalRows_rs_distrito = mysql_num_rows($rs_distrito);
?>
<!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>
</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="clientes_lista" class="flotante_izq">
    	  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    	    <tr>
    	      <strong><td colspan="3">Lista de Clientes</td></strong>
   	        </tr>
    	    <tr>
    	      <td colspan="3"><input name="buscar_cli" type="text" class="fn_text" id="buscar_cli" size="80" onkeypress="buscar_cliente()"/></td>
   	        </tr>
    	    <tr>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
  	      </tr>
    	    <tr>
    	      <td colspan="3">
              <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td width="68%" height="25" bgcolor="#110167"><p class="texto_normal">Cliente</p></td>
                  <td width="17%" bgcolor="#110167"><p class="texto_normal">RUC</p></td>
                  <td width="15%" bgcolor="#110167"><p>&nbsp;</p></td>
                </tr>
              </table>
              <div id="cont_listcli">
              <?php
              if($totalRows_rs_clientes>0){
			  ?>
              <?php do { ?>
    	          <table width="100%" border="0" cellspacing="0" cellpadding="0">
    	            <tr>
    	              <td width="5%" height="25">
                      <?php $ico_cli=$row_rs_clientes['hab_cliente'];?>
                      <img src="../imagenes/ico_cliente_<?php echo($ico_cli);?>.jpg" width="20" height="20" border="0" /></td>
    	              <td width="65%"><?php echo $row_rs_clientes['nom_cliente']; ?></td>
    	              <td width="15%"><?php $ruc=$row_rs_clientes['ruc_cliente']; echo $ruc ; ?></td>
    	              <td width="15%"><p>| <a href="#" class="enlace_normal" onclick="modificar_cli('<?php echo $row_rs_clientes['id_cliente']; ?>')">Modificar</a> |</p></td>
   	                </tr>
   	              </table>
    	          <?php } while ($row_rs_clientes = mysql_fetch_assoc($rs_clientes)); ?>
                  <?php }else{
					  echo("No hay datos encontrados");
					  }?>
              </div></td>
   	        </tr>
    	    <tr>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
    	      <td>&nbsp;</td>
  	      </tr>
  	    </table>
    	</div>
        <div id="cliente_man" class="flotante_izq">
          <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td height="30" colspan="3"><p class="rot_man">&nbsp;&nbsp;&nbsp;&nbsp;Nuevo Cliente</p></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td width="58%"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Empresa</td>
                  </tr>
                  <tr>
                    <td><input name="nom_cliente" type="text" class="fn_text" id="nom_cliente" size="40" autofocus/></td>
                  </tr>
                </table></td>
                <td width="39%"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>RUC</td>
                  </tr>
                  <tr>
                    <td><input name="ruc" type="text" class="fn_text" id="ruc" maxlength="11" /></td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td width="3%">&nbsp;</td>
                <td colspan="2"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Nombre Cliente</td>
                  </tr>
                  <tr>
                    <td><input name="contacto" type="text" class="fn_text" id="contacto" size="75" /></td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Dirección</td>
                  </tr>
                  <tr>
                    <td><input name="direccion" type="text" class="fn_text" id="direccion" size="40" /></td>
                  </tr>
                </table></td>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Distrito</td>
                  </tr>
                  <tr>
                    <td><select name="distrito" class="fn_text" id="distrito">
                      <?php
do {  
?>
                      <option value="<?php echo $row_rs_distrito['id'];?>" <?php if($row_rs_distrito['distrito']=='LIMA'){echo('selected="selected"');}?> ><?php echo $row_rs_distrito['distrito']?></option>
                      <?php
} while ($row_rs_distrito = mysql_fetch_assoc($rs_distrito));
  $rows = mysql_num_rows($rs_distrito);
  if($rows > 0) {
      mysql_data_seek($rs_distrito, 0);
	  $row_rs_distrito = mysql_fetch_assoc($rs_distrito);
  }
?>
                    </select></td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Telefono</td>
                  </tr>
                  <tr>
                    <td><input name="telefono" type="text" class="fn_text" id="telefono" maxlength="7" /></td>
                  </tr>
                </table></td>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Celular</td>
                  </tr>
                  <tr>
                    <td><input name="Celular" type="text" class="fn_text" id="Celular" maxlength="9" /></td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Email</td>
                  </tr>
                  <tr>
                    <td><input name="email" type="text" class="fn_text" id="email" size="40" /></td>
                  </tr>
                </table></td>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td>Habilitado</td>
                  </tr>
                  <tr>
                    <td><input name="hab_cliente" type="radio" id="radio" value="1" checked="checked" />
                      Si&nbsp;&nbsp;
                      <input name="hab_cliente" type="radio" id="radio2" value="0" />
No </td>
                  </tr>
                </table></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td height="30">&nbsp;</td>
                <td><input type="submit" name="button2" id="button2" value="Guardar" /></td>
              </tr>
            </table>
            <input type="hidden" name="MM_insert" value="form1" />
          </form>
        </div>
        <div class="limpiar"></div>
    </div>
    </td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($rs_usuario);

mysql_free_result($rs_clientes);

mysql_free_result($rs_distrito);
?>
