<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}

// $permission  = explode(',',$_SESSION['permission_id']);
// if(!in_array(19,$permission) && !in_array(1,$permission)  ){

// $op['is_success'] = false;
// $op['data'] 	  = "عذرا انت غير مخول للوصل الى هذه الصفحة";
// echo json_encode($op);
// exit;

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

require_once 'vendor/autoload.php';


	function pluck ( $a, $prop ){
		$out = array();

		for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
			$out[] = $a[$i][$prop];
		}

		return $out;
	}

	function bind ( &$a, $val, $type )
	{
		$key = ':binding_'.count( $a );

		$a[] = array(
			'key' => $key,
			'val' => $val,
			'type' => $type
		);

		return $key;
	}


	function orderss($columns){
		$order = '';

		if ( isset($_GET['order']) && count($_GET['order']) ) {
			$orderBy = array();
			$dtColumns = pluck( $columns, 'dt' );

			for ( $i=0, $ien=count($_GET['order']) ; $i<$ien ; $i++ ) {
				// Convert the column index into the column data property
				$columnIdx = intval($_GET['order'][$i]['column']);
				$requestColumn = $_GET['columns'][$columnIdx];

				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
				$column = $columns[ $columnIdx ];

				if ( $requestColumn['orderable'] == 'true' ) {
					$dir = $_GET['order'][$i]['dir'] === 'asc' ?
						'ASC' :
						'DESC';

				  
					$cols = explode(' AS ',$column['db']);
					$col =  $column['db'] ;
					if( count($cols) > 1 ){
						$col = $cols[1];
					}
					####### IMAD CODE #########
					$orderBy[] = '`'.$col.'` '.$dir;
				}
			}

			$order = 'ORDER BY '.implode(', ', $orderBy);
		}

		return $order;
	}



	function filterss ( $columns )
	{
		$globalSearch 	= array();
		$columnSearch 	= array();
		$dtColumns 		= pluck( $columns, 'dt' );


		$total_disc 		= '(SELECT sum(actual_discount) from sell_item where 
								sell_item.invoice_id_fk = Inv.invoice_id AND sell_item.is_deleted=0 )';

		

		if ( isset($_GET['search']) && $_GET['search']['value'] != '' ) {
			$str = $_GET['search']['value'];

			for ( $i=0, $ien=count($_GET['columns']) ; $i<$ien ; $i++ ) {
				$requestColumn = $_GET['columns'][$i];
				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
				$column = $columns[ $columnIdx ];

				if ( $requestColumn['searchable'] == 'true' ) {
					// $binding = bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
					$cols = explode(' AS ',$column['db']);
					$col =  $column['db'] ;
					if( count($cols) > 1 ){
						$col = $cols[1];
					}


					
					if($col == 'total_invoice_price_no_discount'){

						$globalSearch[] = " (".$total_disc." + invoice_total_price_actual) LIKE "."'%".$str."%'";

					}elseif($col == 'total_discount'){

						$globalSearch[] = " (".$total_disc.") LIKE "."'%".$str."%'";


					}elseif($col == 'total_invoice_price'){
						$globalSearch[] = " (invoice_total_price_actual) LIKE "."'%".$str."%'";

					}else{

						$globalSearch[] = "`".$col."` LIKE "."'%".$str."%'";

					}

					
				}
			}
		}

		// Individual column filtering
		if ( isset( $_GET['columns'] ) ) {
			for ( $i=0, $ien=count($_GET['columns']) ; $i<$ien ; $i++ ) {
				$requestColumn = $_GET['columns'][$i];
				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
					// print_r( $columns);
				
				$column = $columns[ $columnIdx ];

				$str = $requestColumn['search']['value'];

				
				$cols = explode(' AS ',$column['db']);
				$col =  $column['db'] ;
				if( count($cols) > 1 ){
					$col = $cols[1];
				}
				####### IMAD CODE #########

				if ( $requestColumn['searchable'] == 'true' && $str != '' ) {
					
					if($col == 'total_invoice_price_no_discount'){

						$columnSearch[] = " (".$total_disc." + invoice_total_price_actual) LIKE "."'%".$str."%'";

					}elseif($col == 'total_discount'){

						$columnSearch[] = " (".$total_disc.") LIKE "."'%".$str."%'";


					}elseif($col == 'total_invoice_price'){
						$columnSearch[] = " (invoice_total_price_actual) LIKE "."'%".$str."%'";

					}else{

						$columnSearch[] = "`".$col."` LIKE "."'%".$str."%'";

					}

				}
			}
		}

		// Combine the filters into a single string
		$where = '';

		if ( count( $globalSearch ) ) {
			$where = '('.implode(' OR ', $globalSearch).')';
		}

		if ( count( $columnSearch ) ) {
			$where = $where === '' ?
				implode(' AND ', $columnSearch) :
				$where .' AND '. implode(' AND ', $columnSearch);
		}

		if ( $where !== '' ) {
			$where = ' AND '.$where;
		}

		return $where;
	}
	


if (isset($_POST['type']) || isset($_GET['type'])){
		require("db_connect.php");

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND SID.product_id_fk='.$_GET['id']:'';
			$cond1 = isset($_GET['ip'])? ' AND Inv.invoice_status='.$_GET['ip']:'';
			
			$primaryKey = 'purchase_item_detail_id';

			$columns = array(
		    	array( 'db' => 'purchase_item_detail_id', 'dt' => 0 ),
		    	array( 'db' => 'erbil_code', 'dt' => 1 ),
		    	array( 'db' => 'turkish_code', 'dt' => 2 ),
		    	array( 'db' => 'barcode', 'dt' => 3 ),
		    	array( 'db' => 'stock_name', 'dt' => 4 ),
		    	array( 'db' => 'purchase_auto_number', 'dt' => 5 ),
		    	array( 'db' => 'purchase_date', 'dt' => 6 , 'formatter'=> function($d){
							return date('Y-m-d',strtotime($d));
					}),
				array( 'db' => 'customer_full_name', 'dt' => 7 ),
				array( 'db' => 'invoice_number', 'dt' => 8 ),
				

			  	array( 'db' => 'invoice_date', 'dt' => 9, 'formatter'=> function($d){
							return date('Y-m-d',strtotime($d));
					} ),
				array( 'db' => 'item_status', 'dt' => 10 ),
				
			);


			if ( isset($_GET['start']) && $_GET['length'] != -1 ) {
				$limit = "LIMIT ".intval($_GET['start']).", ".intval($_GET['length']);
			}else{
				$limit = "";
			}
			
			$bindings = array();

			$ords = orderss($columns);
			$fltr = filterss($columns);


			
			$table  =  '(
				(
					SELECT
							purchase_item_detail_id,
							erbil_code,
							turkish_code,
							barcode,
							stock_name,
							purchase_auto_number,
							purchase_date,
							customer_full_name,
							invoice_number,
							invoice_date,
							item_status


					 FROM
					 
					 sell_item_detail SID

					
					 LEFT JOIN purchase_item_detail PID ON (PID.purchase_item_detail_id = SID.purchase_item_detail_id_fk)
					 LEFT JOIN product P ON (PID.product_id_fk = P.product_id)
					 LEFT JOIN stock S ON (PID.stock_id_fk = S.stock_id)
					 LEFT JOIN purchase PR ON (PID.purchase_id_fk = PR.purchase_id)

					 LEFT JOIN invoice I ON (I.invoice_id = SID.invoice_id_fk)
					 LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)


				WHERE
					(PID.is_deleted = 0 AND (PID.item_status = 1 OR PID.item_status = 5) '.$cond.'  '.$fltr.') '. $ords. ' '.$limit.'
				)
			) AS ALLTBL';


			$raw_table  =  '(
				(
					SELECT
							purchase_item_detail_id,
							erbil_code,
							turkish_code,
							barcode,
							stock_name,
							purchase_auto_number,
							purchase_date,
							customer_full_name,
							invoice_number,
							invoice_date,
							item_status

					FROM
					sell_item_detail SID

					
					 LEFT JOIN purchase_item_detail PID ON (PID.purchase_item_detail_id = SID.purchase_item_detail_id_fk)
					 LEFT JOIN product P ON (PID.product_id_fk = P.product_id)
					 LEFT JOIN stock S ON (PID.stock_id_fk = S.stock_id)
					 LEFT JOIN purchase PR ON (PID.purchase_id_fk = PR.purchase_id)

					 LEFT JOIN invoice I ON (I.invoice_id = SID.invoice_id_fk)
					 LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)

				WHERE
					(PID.is_deleted = 0 AND (PID.item_status = 1 OR PID.item_status = 5) '.$cond.'  '.$fltr.')
				)
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.php' );
			echo json_encode(
			    SSP::complex_optimized( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '', $raw_table  )
			);
			exit;
		}




	}
	else{
		header("Location:../");
		exit;
	}
?>
