<?php
	include('clases/clase.conexion.php');
	include('funciones/variables.php');
	$var = VarServer("MYSQLI");
	$aColumns = array('CPRO', 'CPRO', 'PRODUCTO', 'UM', 'PRECIO', 'STOCK');
	
	$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 = "";
		}
	}

	$sWhere = "and ( LP.id_producto LIKE '%".$_GET['sSearch']."%'
					 or P.descripcion LIKE '%".str_replace(" ","%",$_GET['sSearch'])."%' 
					 or LP.id_um 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]."%' ";
			}
		}
	
	
	/*
	 * SQL queries
	 * Get data to display
	 */
	$sQuery = "select SQL_CALC_FOUND_ROWS
			   LP.id_producto as CPRO, P.descripcion as PRODUCTO, LP.id_um AS UM, LP.PRECIO,
			   ifnull((select K.cantidad
					   from _sv_kardex K
					   where K._estado  = 'A'
					   and K.id_empresa = $_GET[cemp]
					   and K.id_almacen = $_GET[calm]
					   and K.id_producto = LP.id_producto),0) AS STOCK
			   from _sv_lista_producto LP
			   inner join _sv_producto P ON LP.id_producto = P.id_producto
			   inner join _sv_tipo T ON P.id_tipo = T.id_tipo
			   where LP._estado  = 'A' and P._estado = 'A'
			   and T.flag_proser = 'P'
			   and LP.id_empresa = $_GET[cemp]
			   and LP.id_lista 	 = $_GET[clis]
			   $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(LP.id_producto)
		FROM _sv_lista_producto LP
		inner join _sv_producto P on LP.id_producto = P.id_producto
		inner join _sv_tipo T on P.id_tipo = T.id_tipo
		where LP._estado = 'A' and P._estado = 'A'
		and T.id_tipo = 'P'
		and LP.id_empresa = $_GET[cemp]
		and LP.id_lista   = $_GET[clis]";
	$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[0]." - ".utf8_encode($aRow[1])."</b>')\" 
						 onclick=\"javascript:fn_seleccionar_producto_venta('".$_GET["cpos"]."','".$aRow[0]."','".utf8_encode($aRow[1])."','".$aRow[2]."','".$aRow[3]."','".$aRow[4]."')\"
						 src=\"../images/16x16/add.png\">";
				}
			elseif($i==4) {
				$row[] = number_format($aRow[$aColumns[$i]],5,".",",");
				}
			else {
				/* General output */
				$row[] = utf8_encode($aRow[ $aColumns[$i]]);
			}
		}
//		$row = json_encode(array_map(utf8_decode,$row));
		$output['aaData'][] = $row;
	}
	
	echo json_encode( $output );
	
?>