<?php
	include('clases/clase.conexion.php');
	include('funciones/variables.php');
	$var = VarServer("MYSQLI");
	$aColumns = array('IDE1', 'IDE', 'FEMI', 'CTIP', 'TIPODOC', 'NDOC', 'ESTADO', 'MONTO');
	
	$gaSql['user']       = $var[1];
	$gaSql['password']   = $var[2];
	$gaSql['db']         = $var[3];
	$gaSql['server']     = $var[0];
	
	function fatal_error ( $sErrorMessage = '' )
		{
		header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
		die( $sErrorMessage );
		}

	
	/* 
	 * MySQL connection
	 */
	if ( ! $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) )
	{
		fatal_error( 'Could not open connection to server' );
	}

	if ( ! mysql_select_db( $gaSql['db'], $gaSql['link'] ) )
	{
		fatal_error( 'Could not select database ' );
	}
	
	
	/* 
	 * Paging
	 */
	$sLimit = "";
	if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
	{
		$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
			mysql_real_escape_string( $_GET['iDisplayLength'] );
	}
	
	
	/*
	 * Ordering
	 */
	$sOrder = "";
	if ( isset( $_GET['iSortCol_0'] ) ) {
		$sOrder = "ORDER BY  ";
		for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
			if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
				$sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
			}
		}
		
		$sOrder = substr_replace( $sOrder, "", -2 );
		if ( $sOrder == "ORDER BY" )
		{
			$sOrder = "";
		}
	}
	
	
	/* 
	 * Filtering
	 */
	$sWhere = "and ( V.id_venta LIKE '%".$_GET['sSearch']."%'
					 or T.nombre LIKE '%".str_replace(" ","%",$_GET['sSearch'])."%' 
					 or CONCAT(V.nro_serie,'-',V.nro_preimpreso) LIKE '%".str_replace(" ","%",$_GET['sSearch'])."%'
					 ) ";
					 
	
	/* Individual column filtering */
	for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
		if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) {
			if ( $sWhere == "" ) {
				$sWhere = "WHERE ";
				}
			else {
				$sWhere .= " AND ";
				}
			$sWhere .= "`".$aColumns[$i]."` LIKE '%".$_GET['sSearch_'.$i]."%' and V._estado='A' ";
			}
		}
	
	
	/*
	 * SQL queries
	 * Get data to display
	 */
	$sQuery = 	"select SQL_CALC_FOUND_ROWS
				 V.id_venta as IDE1, V.id_venta as IDE,
				 date_format(V.fecha_emision,'%d/%m/%Y') as FEMI,
				 V.id_tipo_doc as CTIP, T.nombre as TIPODOC, 
				 CONCAT(V.nro_serie,'-',V.nro_preimpreso) AS NDOC,
				 V.ESTADO, V.total as MONTO
				 from _sv_venta V
				 inner join _sv_tipo_doc_venta T ON T.id_tipo_doc = V.id_tipo_doc
				 where V._estado = 'A'
				 and V.id_empresa = $_GET[emp] 
				 and V.id_cliente = $_GET[cli]
				 and V.id_tipo_doc=2
				 and V.estado <> 'AN'
				 $sWhere
			   	 $sOrder
			   	 $sLimit";
	$rResult = mysql_query(utf8_decode($sQuery), $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$varSQL = $sQuery;
	/* Data set length after filtering */
	$sQuery = "
		SELECT FOUND_ROWS()
	";
	$rResultFilterTotal = mysql_query( utf8_decode($sQuery), $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
	$iFilteredTotal = $aResultFilterTotal[0];
	
	/* Total data set length */
	$sQuery = "
		SELECT COUNT(id_venta)
		FROM   _sv_venta
		where _estado = 'A'
		and id_empresa = $_GET[emp] 
		and id_cliente = $_GET[cli]
		and id_tipo_doc=2
		and estado <> 'AN'";
	$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$aResultTotal = mysql_fetch_array($rResultTotal);
	$iTotal = $aResultTotal[0];
	
	
	/*
	 * Output
	 */
	$output = array(
		"sEcho" => intval($_GET['sEcho']),
		"iTotalRecords" => $iTotal,
		"iTotalDisplayRecords" => $iFilteredTotal,
		"aaData" => array()
	);
	
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$row = array();
		for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
			if ($i==0) $row[] = "<img style=\"cursor:pointer\" onmouseout=\"UnTip()\"  
								 onmouseover=\"MensajeTip('HAGA CLICK PARA <b>SELECCIONAR</b> EL REGISTRO<br>
								 <b>".$aRow[1]." - ".$aRow[2]."</b>')\" 
								 onclick=\"javascript:fn_seleccionar_docref_venta('".$aRow[1]."','".$aRow[2]."','".$aRow[3]."','".$aRow[4]."','".$aRow[5]."','".$aRow[6]."','".$aRow[7]."')\"
								 src=\"../images/16x16/add.png\">";
			else
			{
				/* General output */
				$row[] = utf8_encode($aRow[$aColumns[$i]]);
			}
		}
//		$row = json_encode(array_map(utf8_decode,$row));
		$output['aaData'][] = $row;
	}
	
	echo json_encode( $output );
	
?>