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

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
			$cond1 = isset($_GET['cid'])? ' AND C.city_id_fk ='.$_GET['cid']:'';

			$cond2 = '';
			if(isset($_GET['branch_id']) && $_GET['branch_id'] !=0){ 
				$cond2 = ' AND C.branch_id_fk ='.$_GET['branch_id'];
			}

			$cond3 = '';

			if(isset($_SESSION['branch_id']) && $_SESSION['branch_id'] !=0){ 
				$cond3 = ' AND C.branch_id_fk ='.$_SESSION['branch_id'];
			}
			
			$cond = $cond1 . $cond2 . $cond3  ;
			
			
			$table  =  '(
						(
							SELECT 	customer_id,
									customer_full_name,
									customer_phone,
									customer_email,
									customer_address,
									customer_company,

	
				          			(
				          			  
										COALESCE((SELECT sum(invoice_total_net_balance) FROM invoice I
											
											WHERE  I.customer_id_fk = C.customer_id AND I.invoice_transaction="Invoice" AND I.invoice_status <3  AND I.is_deleted = 0),0)
										
								      	+
								      COALESCE((SELECT sum(withdraw_amount) FROM capital_withdraw CW1 WHERE  CW1.is_deleted = 0 AND CW1.staff_customer=0  AND CW1.gived_to_id_fk = C.customer_id ),0)

								    ) AS total_invoice_price,
								   
								  	
								    (
										COALESCE((SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = C.customer_id AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Payment"),0)
										-
										COALESCE((SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = C.customer_id AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Return"),0) 
									) AS total_paid,

									(SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = C.customer_id AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Discount") AS total_payment_discount,

									(SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = C.customer_id AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Return") AS total_payment_return,

			        				
        
								(SELECT COUNT(*) FROM invoice I  
												WHERE I.invoice_status <3 AND  I.is_deleted = 0  AND  I.customer_id_fk = C.customer_id ) as No_of_inv,

								(SELECT COUNT(*) FROM capital_withdraw CW WHERE  CW.is_deleted = 0  AND CW.gived_to_id_fk = C.customer_id AND CW.staff_customer=0 AND CW.capital_withdraw_transaction="Withdraw") as No_of_withdraw


					FROM customer C WHERE C.is_deleted=0 '.$cond.'
				)
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'customer_id';
			$columns = array(
							    array( 'db' => 'customer_id', 'dt' => 0 ),
							    array( 'db' => 'customer_full_name', 'dt' => 1 ),
							    array( 'db' => 'customer_phone', 'dt' => 2),
							    array( 'db' => 'total_invoice_price', 'dt' => 3 ),
							    array( 'db' => 'total_payment_discount', 'dt' => 4 ),
							    array( 'db' => 'total_paid', 'dt' => 5 ),

								array( 'db' => 'total_payment_return', 'dt' => 6 ),
								array( 'db' => 'No_of_inv', 'dt' => 7 ),
							  	array( 'db' => 'No_of_withdraw', 'dt' => 8 ),
							  	array( 'db' => 'customer_company', 'dt' => 9 ),
							  	array( 'db' => 'customer_address', 'dt' => 10 ),
							  	
			);
			// 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( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '' )
			);
			exit;
		}

		

		if ($_POST['type']=="show_invoices_summary") {

			$id 		= $_POST['id'];
		

			$res = $db->query('(( 

								SELECT
									invoice_id AS id,
									invoice_number as voucher_no,
								    invoice_date AS date_,
								    (invoice_total_net_balance) AS debits,

									invoice_transaction AS transaction_,
								  	(0) AS credits,
								    invoice_note AS note
						
								FROM invoice Inv
								
								WHERE
								(Inv.is_deleted = 0 AND  Inv.invoice_status <3 AND  Inv.invoice_transaction ="Invoice" AND Inv.customer_id_fk='.$id.' )


								) 
								)
								 
								 UNION ALL
								 
								 ( SELECT
								         capital_withdraw_id,
								         capital_withdraw_number,
								         withdraw_date,
								         withdraw_amount,
								         capital_withdraw_transaction,
								  		 (0) AS Credits,
								         withdraw_note														
								 FROM  capital_withdraw CW WHERE CW.gived_to_id_fk ='.$id.' AND CW.is_deleted =0 AND CW.capital_withdraw_transaction ="Withdraw" )
								 
								  UNION ALL
								 
								 ( SELECT
								         payment_id,
								         payment_number,
								         paid_date,
								         paid_amount,
								         payment_transaction,
								  		 (0) AS Credits,
								         payment_note
														
								 FROM  payments PY WHERE PY.customer_id_fk ='.$id.' AND PY.is_returned=0 AND PY.is_deleted =0 AND PY.payment_transaction ="Return" ) 
								 
								  UNION ALL
								 
								 ( SELECT
								         payment_id,
								         payment_number,
								         paid_date,
								         (0) AS Debits,
								         payment_transaction,
								  		 paid_amount,
								         payment_note
								 FROM  payments PY WHERE PY.customer_id_fk ='.$id.' AND PY.is_returned=0 AND PY.is_deleted =0 AND PY.payment_transaction ="Payment" ) 
								 
								  UNION ALL
								 
								 ( SELECT
								         payment_id,
								         payment_number,
								         paid_date,
								         (0) AS Debits,
								         payment_transaction,
								  		 paid_amount AS Credits,
								         payment_note

								 FROM  payments PY WHERE PY.customer_id_fk ='.$id.' AND PY.is_returned=0 AND PY.is_deleted =0 AND PY.payment_transaction ="Discount" ) ORDER BY Date_ ASC');

		
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['id']  					= $row['id'];
					$result['voucher_no']  			= $row['voucher_no'];
					$result['date_']  				= date('Y-m-d',strtotime($row['date_'])) ;
					$result['debits']  				= $row['debits'];
					$result['transaction_']  		= $row['transaction_'];
					$result['credits']  			= $row['credits'];
					$result['note'] 				= $row['note'];
					
					
					array_push($op['invoice'],$result);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}
		}






		if ($_POST['type']=="load_all_invoices") {

			$id 		= $_POST['id'];
		

			$res = $db->query('(( 

								SELECT
									invoice_id AS id,
									invoice_number as voucher_no,
								    invoice_date AS date_,
								    author,

									(invoice_total_net_balance) AS debits,


									(SELECT sum(paid_amount) FROM payments_details PY WHERE PY.invoice_id_fk = Inv.invoice_id AND  PY.is_deleted = 0 AND PY.payment_transaction ="Payment") AS credits,

									invoice_transaction AS transaction_,
								    invoice_note AS note
						
								FROM invoice Inv
								
								WHERE
								(Inv.is_deleted = 0 AND  Inv.invoice_status <3 AND  Inv.invoice_transaction ="Invoice" AND Inv.customer_id_fk='.$id.' )


								) 
								) ORDER BY Date_ ASC');

		
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['id']  					= $row['id'];
					$result['voucher_no']  			= $row['voucher_no'];
					$result['date_']  				= date('Y-m-d',strtotime($row['date_'])) ;
					$result['debits']  				= $row['debits'];
					$result['transaction_']  		= $row['transaction_'];
					$result['credits'] 			= $row['credits'];
					$result['note'] 				= $row['note'];
					$result['author'] 				= $row['author'];
					
					
					array_push($op['invoice'],$result);
						
				}	

				$res = $db->query("SELECT 
									  customer_full_name,
									  customer_email,
									  customer_phone,
									  customer_address, 
									  sum(invoice_total_net_balance) AS total_invoices_price,

									  

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Payment') AS total_paid,

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Discount') AS total_payment_discount,

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Return') AS total_payment_return

									FROM invoice I
								 		
										LEFT JOIN customer C ON (I.customer_id_fk = C.customer_id )
								 	WHERE I.customer_id_fk='$id'  AND I.is_deleted = 0 AND  I.invoice_status <3 AND  I.invoice_transaction ='Invoice' ");

		
				if ($res) {
					
					while ($row = $res->fetch_assoc()) {
					   
						
						$result1['customer_full_name'] 		= $row['customer_full_name'];
						$result1['customer_email']  			= $row['customer_email'];
						$result1['customer_phone']  			= $row['customer_phone'];
						$result1['customer_address']  		= $row['customer_address'];
						$result1['total_invoices_price']  	= $row['total_invoices_price'];
						$result1['total_paid']  				= $row['total_paid'] - $row['total_payment_return'];
						$result1['total_payment_discount']  	= $row['total_payment_discount'];
						$result1['total_payment_return']  	= $row['total_payment_return'];
						
						$result1['total_remained']  			= $row['total_invoices_price'] - $row['total_paid'] - $row['total_payment_discount'] + $row['total_payment_return'];
						
						array_push($op['details'],$result1);
							
					}		
					echo json_encode($op);
					exit;
				}else{
					echo 0;
					exit;
				}

				
			}else{
				echo $db->error;
				exit;
			}
		}



		if ($_POST['type']=="load_all_invoices_full_detail") {

			$id 		= $_POST['id'];
		

			$res = $db->query('(( 

								SELECT
									invoice_id AS id,
									invoice_date,
									invoice_number
									
						
								FROM invoice Inv
								
								WHERE
								(Inv.is_deleted = 0 AND  Inv.invoice_status <3 AND  Inv.invoice_transaction ="Invoice" AND Inv.customer_id_fk='.$id.' )


								) 
								) ORDER BY invoice_date ASC');

		
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array(),'invoice1'=>array(),'details1'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['id']  					= $row['id'];
					$result['invoice_date']  		= date('Y-m-d',strtotime($row['invoice_date']));
					$result['invoice_number']  		= $row['invoice_number'];
					
					$inv_id 							= $result['id'] ;
					
					
					array_push($op['invoice'],$result);



					$res1 = $db->query("SELECT 
										invoice_id, 
										invoice_number, 
										invoice_date, 
										invoice_status, 
										invoice_usd_rate, 
										invoice_currency,
										invoice_total_price_actual, 
										invoice_total_net_balance, 
										I.discount,
										I.discount_type, 
										I.actual_discount, 
										invoice_note,
										author,
										invoice_sequence_no,
										
										invoice_barcode,
										customer_id_fk, 
										sell_item_id,
										sell_item_quantity,
										sell_discount,
										sell_discount_type,
										SI.actual_discount as sell_actual_discount, 
										item_buy_price_per_unit, 
										item_sell_price_per_unit, 
										tax_per_unit, 
										sell_date,
										sell_item_barcode,
										sell_item_notes,
										product_id_fk, 
										customer_full_name,
										customer_email,
										customer_phone,
										customer_address,									  
									  	customer_company,


									  	Pr1.product_name,
									  	
									  													
									  	(0 ) AS row_price,

									  	branch_name,
									  	saleman_full_name,
									  	I.branch_id_fk,
									  	saleman_id_fk,
									  	SI.invoice_id_fk,

									


									

									(SELECT sum(paid_amount) FROM payments_details PY WHERE PY.invoice_id_fk = I.invoice_id AND  PY.is_deleted = 0 AND PY.payment_transaction ='Payment') AS total_paid

								  

										FROM invoice I
										LEFT JOIN sell_item SI ON (SI.invoice_id_fk = I.invoice_id AND SI.is_deleted=0)
										LEFT JOIN branch B ON (I.branch_id_fk = B.branch_id )
										LEFT JOIN product Pr1 ON (SI.product_id_fk = Pr1.product_id )
					 	 				LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)
					 	 				LEFT JOIN saleman SM ON (I.saleman_id_fk = SM.saleman_id)

										WHERE I.invoice_id='$inv_id'  AND I.is_deleted = 0");
					if ($res1) {
						
						
						while ($row = $res1->fetch_assoc()) {

							
						   
							$result2['invoice_id']  				= $row['invoice_id'];
							$result2['invoice_number']  			= $row['invoice_number'];
							$result2['invoice_date']  				= date('Y-m-d',strtotime($row['invoice_date'])) ;
							$result2['invoice_status']  			= $row['invoice_status'];
							$result2['invoice_usd_rate']  			= $row['invoice_usd_rate'];
							$result2['invoice_currency']  			= $row['invoice_currency'];
							$result2['invoice_total_price_actual'] 	= $row['invoice_total_price_actual'];
							$result2['invoice_total_net_balance']  	= $row['invoice_total_net_balance'];
							$result2['discount']  					= $row['discount'];
							$result2['discount_type']  				= $row['discount_type'];
							$result2['actual_discount']  			= $row['actual_discount'];
							$result2['invoice_note']  				= $row['invoice_note'];
							$result2['invoice_sequence_no']  		= $row['invoice_sequence_no'];
							$result2['author']  					= $row['author'];
							$result2['invoice_barcode']  			= $row['invoice_barcode'];
							$result2['customer_id_fk']  			= $row['customer_id_fk'];
							$result2['branch_id_fk']  				= $row['branch_id_fk'];
							$result2['saleman_id_fk']  				= $row['saleman_id_fk'];

							$result2['sell_item_id']  				= $row['sell_item_id'];
							$result2['sell_item_quantity']  		= $row['sell_item_quantity'];
							$result2['sell_discount']  				= $row['sell_discount'];
							$result2['sell_discount_type']  		= $row['sell_discount_type'];
							$result2['sell_actual_discount']  		= $row['sell_actual_discount'];
							$result2['item_buy_price_per_unit']  	= $row['item_buy_price_per_unit'];
							$result2['item_sell_price_per_unit']  	= $row['item_sell_price_per_unit'];
							$result2['sell_item_barcode']  			= $row['sell_item_barcode'];
							$result2['sell_date']  					= $row['sell_date'];
							$result2['sell_item_notes']  			= $row['sell_item_notes'];
							$result2['customer_full_name']  		= $row['customer_full_name'];
							$result2['customer_phone']  			= $row['customer_phone'];
							$result2['customer_address']  			= $row['customer_address'];
							$result2['customer_email']  			= $row['customer_email'];
							$result2['customer_company']  			= $row['customer_company'];
							
							$result2['product_id_fk']  				= $row['product_id_fk'];
							$result2['invoice_id_fk']  				= $row['invoice_id_fk'];

							$result2['product_name']  				= $row['product_name'];
							$result2['branch_name']  				= $row['branch_name'];
							$result2['saleman_full_name']  			= $row['saleman_full_name'];
							
							
							$result2['total_paid']  				= $row['total_paid'];
							$result2['total_remained']  			= $row['invoice_total_net_balance'] - $row['total_paid'];
							$result2['row_price']  					= $row['sell_item_quantity'] * $row['item_sell_price_per_unit'] - $row['sell_actual_discount'];
							
							array_push($op['invoice1'],$result2);
					
						}		
						
					}else{
						echo $db->error;
						exit;
					}
						
				}	

				$res = $db->query("SELECT 
									  customer_full_name,
									  customer_email,
									  customer_phone,
									  customer_address, 
									  sum(invoice_total_net_balance) AS total_invoices_price,

									  

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Payment') AS total_paid,

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Discount') AS total_payment_discount,

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Return') AS total_payment_return

									FROM invoice I
								 		
										LEFT JOIN customer C ON (I.customer_id_fk = C.customer_id )
								 	WHERE I.customer_id_fk='$id'  AND I.is_deleted = 0 AND  I.invoice_status <3 AND  I.invoice_transaction ='Invoice' ");

		
				if ($res) {
					
					while ($row = $res->fetch_assoc()) {
					   
						
						$result1['customer_full_name'] 		= $row['customer_full_name'];
						$result1['customer_email']  			= $row['customer_email'];
						$result1['customer_phone']  			= $row['customer_phone'];
						$result1['customer_address']  		= $row['customer_address'];
						$result1['total_invoices_price']  	= $row['total_invoices_price'];
						$result1['total_paid']  				= $row['total_paid'] - $row['total_payment_return'];
						$result1['total_payment_discount']  	= $row['total_payment_discount'];
						$result1['total_payment_return']  	= $row['total_payment_return'];
						
						$result1['total_remained']  			= $row['total_invoices_price'] - $row['total_paid'] - $row['total_payment_discount'] + $row['total_payment_return'];
						
						array_push($op['details'],$result1);
							
					}		
					echo json_encode($op);
					exit;
				}else{
					echo 0;
					exit;
				}

				
			}else{
				echo $db->error;
				exit;
			}
		}


		if ($_POST['type']=="load_all_invoices_just_totals") {

			$id 		= $_POST['id'];
		
				

			$op  = array('invoice'=>array(),'details'=>array());
				
			$res = $db->query("SELECT 
									  customer_full_name,
									  customer_email,
									  customer_phone,
									  customer_address, 
									  sum(invoice_total_net_balance) AS total_invoices_price,

									 

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Payment') AS total_paid,

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Discount') AS total_payment_discount,

									  (SELECT sum(paid_amount) FROM payments IP WHERE IP.customer_id_fk = I.customer_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Return') AS total_payment_return

									FROM invoice I
								 		
										LEFT JOIN customer C ON (I.customer_id_fk = C.customer_id )
								 	WHERE I.customer_id_fk='$id'  AND I.is_deleted = 0");

		
			if ($res) {
				
				while ($row = $res->fetch_assoc()) {
				   
					
					$result1['customer_full_name'] 		= $row['customer_full_name'];
					$result1['customer_email']  			= $row['customer_email'];
					$result1['customer_phone']  			= $row['customer_phone'];
					$result1['customer_address']  		= $row['customer_address'];
					$result1['total_invoices_price']  	= $row['total_invoices_price'];
					$result1['total_paid']  				= $row['total_paid'] - $row['total_payment_return'];
					$result1['total_payment_discount']  	= $row['total_payment_discount'];
					$result1['total_payment_return']  	= $row['total_payment_return'];
					
					$result1['total_remained']  			= $row['total_invoices_price'] - $row['total_paid'] - $row['total_payment_discount'] + $row['total_payment_return'];
					
					array_push($op['details'],$result1);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}

				
			
		}


		if ($_POST['type']=="show_withdraw_summary") {

			$id 		= $_POST['id'];
			
			$cond 		='';

			$res = $db->query("SELECT capital_withdraw_id, 
									  withdraw_amount, 
									  withdraw_date, 
									  withdraw_note, 
									  withdraw_status, 
									  withdraw_by,
									  gived_to_id_fk, 
									  withdraw_usd_rate, 
									  withdraw_currency, 
									  customer_full_name,
									  customer_email,
									  customer_phone,
									  customer_address, 
									  
														
								    (SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP WHERE  CWP.is_deleted = 0  AND CWP.payment_gived_to_id_fk = CW.gived_to_id_fk ) AS total_paid,
								

									(SELECT sum(withdraw_amount) FROM capital_withdraw CW1 WHERE  CW1.is_deleted = 0  AND CW1.gived_to_id_fk = CW.gived_to_id_fk ) AS total_withdraw_price



									FROM capital_withdraw CW
										LEFT JOIN customer C ON (CW.gived_to_id_fk = C.customer_id )
								 	WHERE CW.gived_to_id_fk='$id'  AND CW.is_deleted = 0  $cond");

		
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['capital_withdraw_id']  	= $row['capital_withdraw_id'];
					$result['withdraw_amount']  		= $row['withdraw_amount'];
					$result['withdraw_date']  			= date('Y-m-d',strtotime($row['withdraw_date'])) ;
					$result['withdraw_note']  			= $row['withdraw_note'];
					$result['withdraw_status']  		= $row['withdraw_status'];
					$result['withdraw_by']  			= $row['withdraw_by'];
					$result['gived_to_id_fk'] 			= $row['gived_to_id_fk'];
					$result['withdraw_usd_rate']  		= $row['withdraw_usd_rate'];
					$result['customer_full_name']  		= $row['customer_full_name'];
					$result['customer_phone']  			= $row['customer_phone'];
					$result['customer_address']  		= $row['customer_address'];
					$result['withdraw_currency']  		= $row['withdraw_currency'];
					$result['total_paid']  				= $row['total_paid'];
					$result['total_withdraw_price']  	= $row['total_withdraw_price'];
					$result['total_remained']  			= $row['total_withdraw_price'] - $row['total_paid'];
					
					array_push($op['invoice'],$result);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="get_inv") {

			$user_id 	= $_POST['cus_id'];
			$cust_typ 	= $_POST['cust_typ'];

			$cond = '';
			if($user_id !='' && $user_id != NULL){
				$cond = ' AND I.customer_id_fk = '.$user_id ;
			}

			$res = $db->query("SELECT invoice_id,invoice_number,invoice_date,customer_full_name FROM invoice I
													LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk ) WHERE I.is_deleted = 0 AND I.invoice_status < 3 $cond  AND C.customer_type ='$cust_typ'");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['invoice_id'];
						$result[1]  = $row['invoice_number'];
						$result[2]  = $row['customer_full_name'];
						$result[3]  = date('Y-m-d',strtotime($row['invoice_date'])) ;
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				echo $db->error;
				exit;
			}
		}

	

	
		if ($_POST['type']=="get_totals_withdraw") {

			$customer_id_fk 	= $_POST['customer_id_fk'];
			
			
			$res = $db->query("
								SELECT									
										customer_full_name,
										
										(SELECT sum(withdraw_amount) FROM capital_withdraw CW  WHERE CW.is_deleted =0 AND CW.gived_to_id_fk = C.customer_id) AS total_amount,

										(SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0  AND CWP1.payment_gived_to_id_fk = C.customer_id) AS total_paid,
										(
										COALESCE((SELECT sum(withdraw_amount) FROM capital_withdraw CW  WHERE CW.is_deleted =0 AND CW.gived_to_id_fk = C.customer_id),0)
										-
										COALESCE((SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0  AND CWP1.payment_gived_to_id_fk = C.customer_id),0)
										 ) AS total_remained
								FROM customer C
						
								WHERE  C.is_deleted = 0  AND C.customer_id='$customer_id_fk'  ");
			
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				$total_item_type_price 		=0;
				$total_item_type_paid	 	=0;

				while ($row = $res->fetch_assoc()) {

					 
					$total_item_type_price		= $row['total_amount'];
					$total_item_type_paid 		= $row['total_paid'];
					$total_item_type_remaind 	= $row['total_remained'];
						
						
				}


				$result['total_item_type_price'] 	= $total_item_type_price;
				$result['total_item_type_paid'] 	= $total_item_type_paid;
				$result['total_item_type_remaind'] 	= $total_item_type_remaind;
				array_push($op,$result);

				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="account_statment") {

			// $cond_inv_id 	= isset($_POST['inv_id'])? ' AND I.invoice_id='.$_POST['inv_id']:'';
			// $cond_cust_id = isset($_POST['cust_id'])? ' AND I.customer_id_fk='.$_POST['cust_id']:'';

			$cond_inv_id 	= '';
			$cond_cust_id 	= '';
			$cond_inv_date 	= '';
			$with_cust_id 	= '';
			$cond_cw_date 	= '';
			$cond_cwp_date 	= '';
			$cond_cust_typ  = '';
			
			if(isset($_POST['inv_id'])){
					$inv_id = $_POST['inv_id'];
					if($inv_id != NULL && $inv_id != ''){
						$cond_inv_id 	=  ' AND I.invoice_id='.$_POST['inv_id'];
					}
			}

			if(isset($_POST['cust_typ'])){
					$cust_typ = $_POST['cust_typ'];
					if($cust_typ != NULL && $cust_typ != ''){
						$cond_cust_typ 	=  ' AND C.customer_type='.$_POST['cust_typ'];
					}
			}

			if(isset($_POST['cust_id'])){
					$cust_id = $_POST['cust_id'];
					if($cust_id != NULL && $cust_id != ''){
						$cond_cust_id 	=  ' AND I.customer_id_fk='.$_POST['cust_id'];
						$with_cust_id 	=  ' AND C.customer_id='.$_POST['cust_id'];
					}
			}



			if(isset($_POST['date_operation'])){

				$first_date = $_POST['inv_date'];
				$last_date 	= $_POST['inv_date_end'];

				if($first_date =='' || $first_date == NULL){
					$first_date = date("Y-m-d", time());
				}

				if($last_date =='' || $last_date == NULL){
					$last_date = date("Y-m-d", time());
				}

				switch ($_POST['date_operation']) {
					case 'E': // equal to date any day of any month of any year // this can be as daily also
						$cond_inv_date 		= ' AND I.invoice_date="'.$first_date.'"';				
						$cond_cw_date 	= ' AND CW.withdraw_date="'.$first_date.'"';		
						$cond_cwp_date 	= ' AND CWP1.payment_withdraw_date="'.$first_date.'"';		
						break;
					case 'L': // less than any date 
						$cond_inv_date 	= ' AND I.invoice_date < "'.$first_date.'"';
						$cond_cw_date 	= ' AND CW.withdraw_date < "'.$first_date.'"';		
						$cond_cwp_date 	= ' AND CWP1.payment_withdraw_date < "'.$first_date.'"';		

						break;
					case 'G': // greater than any date
						$cond_inv_date 	= ' AND I.invoice_date > "'.$first_date.'"';			
						$cond_cw_date 	= ' AND CW.withdraw_date > "'.$first_date.'"';		
						$cond_cwp_date 	= ' AND CWP1.payment_withdraw_date > "'.$first_date.'"';	
						break;
					case 'B': // between specific dates
						$cond_inv_date 	= ' AND I.invoice_date BETWEEN "'.$first_date.'" AND "'.$last_date.'"';
						$cond_cw_date 	= ' AND CW.withdraw_date BETWEEN "'.$first_date.'" AND "'.$last_date.'"';		
						$cond_cwp_date 	= ' AND CWP1.payment_withdraw_date BETWEEN "'.$first_date.'" AND "'.$last_date.'"';
						break;
					case 'Y': // equal for any year
						$cond_inv_date 	= ' AND year(I.invoice_date) = year("'.$first_date.'")';
						$cond_cw_date 	= ' AND year(CW.withdraw_date) = year("'.$first_date.'")';	
						$cond_cwp_date 	= ' AND year(CWP1.payment_withdraw_date) = year("'.$first_date.'")';
						break;	
					case 'M': // equal for any month for any year
						$cond_inv_date 	= ' AND  month(I.invoice_date) = month("'.$first_date.'") AND year(I.invoice_date) = year("'.$first_date.'")';

						$cond_cw_date 	= ' AND  month(CW.withdraw_date) = month("'.$first_date.'") AND year(CW.withdraw_date) = year("'.$first_date.'")';
						$cond_cwp_date 	= ' AND  month(CWP1.payment_withdraw_date) = month("'.$first_date.'") AND year(CWP1.payment_withdraw_date) = year("'.$first_date.'")';	
						break;	
					case 'W': // equal to any week in any month in any year but the first date is sunday
						$cond_inv_date 	= ' AND week(I.invoice_date) = week("'.$first_date.'")';
						$cond_cw_date 	= ' AND week(CW.withdraw_date) = week("'.$first_date.'")';
						$cond_cwp_date 	= ' AND week(CWP1.payment_withdraw_date) = week("'.$first_date.'")';
						// $cond_inv_date 	= ' AND I.invoice_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()';
						break;	
					default:
						$cond_inv_date 	= '';
						$cond_cw_date 	= '';
						$cond_cwp_date 	= '';
						break;	
				}
			}
			
			$cond = " AND I.invoice_status < 3 " . $cond_inv_id . " " . $cond_cust_id . " " . $cond_inv_date;

			$cond_CW 	=   $cond_cw_date ;
			$cond_CWP1 	=   $cond_cwp_date ;

			$res = $db->query("

								SELECT item_type_id,item_name,
											(SELECT sum(paid_amount) FROM invoice_payment IP1 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond)
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										   WHERE I.invoice_id = IP1.invoice_id_fk AND  IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id) as total_Paid_curtain_single,

											(SELECT sum(sell_item_quantity) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond)
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id) as quantity_single,

										  (SELECT COUNT(*) FROM invoice I  
										  	WHERE  I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond  
										   ) as No_of_s_inv,


										   (SELECT COUNT(*) FROM invoice I  
										  	WHERE  I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond  
										   ) as No_of_m_inv,

										   (SELECT COUNT(*) FROM invoice I  
										  	WHERE  I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond  
										   ) as No_of_raw_inv,

										        
											((SELECT sum(sell_item_detail_height * item_sell_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond)
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=0)
												-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=0)
											) as total_cost_single_no_curtain,

											((SELECT sum(sell_item_detail_height * sell_item_detail_width * item_sell_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=1) 
										 	+
										 
										 	(SELECT sum( sell_item_detail_width * decorate_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=1)
										 	-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=1)
										 	)as total_cost_single_curtain,
										        
										        
											(SELECT sum(paid_amount) FROM invoice_payment IP1 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = IP1.invoice_id_fk AND  IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id) as total_Paid_curtain_plural,

											(SELECT sum(sell_item_quantity) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id) as Quantity_plural,

										  ((SELECT sum(sell_item_detail_height * item_sell_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=0)
												-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=0)
											) as total_cost_plural_no_curtain,


											((SELECT sum(sell_item_detail_height * sell_item_detail_width * item_sell_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=1) 
										 	+
										 
										 	(SELECT sum( sell_item_detail_width * decorate_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=1)
										 	-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id AND IT.is_have_curtain=1)
										 	)as total_cost_plural_curtain,

										        
											(SELECT sum(paid_amount) FROM invoice_payment IP1 
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )       
										        WHERE I.invoice_id = IP1.invoice_id_fk AND  IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id) as total_Paid_Raw,

											(SELECT sum(sell_item_quantity) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id) as Quantity_Raw,


										  ((SELECT sum(sell_item_detail_height * item_sell_price_per_meter) FROM sell_item_detail SID 
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										       LEFT JOIN sell_item S ON ( S.is_deleted=0 )
										        WHERE I.invoice_id = SID.invoice_id_fk AND  SID.part_status =0 AND SID.sell_item_id_fk=S.sell_item_id  AND  S.item_type_id_fk = IT.item_type_id )
												-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.item_type_id_fk = IT.item_type_id )
											) as total_cost_raw,

											(SELECT sum(paid_amount) FROM invoice_payment IP1 
											       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0  $cond )
											       LEFT JOIN sell_item S ON ( S.is_deleted=0 )       
											        WHERE I.invoice_id = IP1.invoice_id_fk AND  IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.sell_item_id_fk=S.sell_item_id  AND  S.other_id_fk >0) as total_other_Paid_Raw,

											(SELECT sum(sell_item_quantity) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.other_id_fk >0) as Quantity_other_Raw,

										  ((SELECT sum(sell_item_quantity * item_sell_price_per_meter) FROM sell_item S  
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = S.invoice_id_fk AND  S.other_id_fk >0 AND S.is_deleted=0)
												-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='0'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.other_id_fk >0 )
											) as total_cost_other_raw,


											(SELECT sum(paid_amount) FROM invoice_payment IP1 
											       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1  $cond )
											       LEFT JOIN sell_item S ON ( S.is_deleted=0 )       
											        WHERE I.invoice_id = IP1.invoice_id_fk AND  IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.sell_item_id_fk=S.sell_item_id  AND  S.other_id_fk >0) as total_other_Paid_S,

											(SELECT sum(sell_item_quantity) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.other_id_fk >0) as Quantity_other_S,

										  ((SELECT sum(sell_item_quantity * item_sell_price_per_meter) FROM sell_item S  
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										        WHERE I.invoice_id = S.invoice_id_fk AND  S.other_id_fk >0 AND S.is_deleted=0)
												-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=1 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.other_id_fk >0 )
											) as total_cost_other_S,


											(SELECT sum(paid_amount) FROM invoice_payment IP1 
											       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0  $cond )
											       LEFT JOIN sell_item S ON ( S.is_deleted=0 )       
											        WHERE I.invoice_id = IP1.invoice_id_fk AND  IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.sell_item_id_fk=S.sell_item_id  AND  S.other_id_fk >0) as total_other_Paid_M,

											(SELECT sum(sell_item_quantity) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.other_id_fk >0) as Quantity_other_M,

										  ((SELECT sum(sell_item_quantity * item_sell_price_per_meter) FROM sell_item S  
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = S.invoice_id_fk AND  S.other_id_fk >0 AND S.is_deleted=0)
												-
										 	(SELECT sum(actual_discount) FROM sell_item SI 
										       LEFT JOIN invoice I ON (I.invoice_type='1'  AND I.is_deleted = 0  AND I.is_single=0 $cond )
										        WHERE I.invoice_id = SI.invoice_id_fk  AND SI.is_deleted =0   AND  SI.other_id_fk >0 )
											) as total_cost_other_M

																		        
								FROM item_type IT 			WHERE IT.is_deleted=0					");

			if ($res) {
				//$row = $res->fetch_all();
				$op  = array('sell'=>array(),'withdraw'=>array());
				while ($row = $res->fetch_assoc()) {

						$total_cost_single = $row['total_cost_single_no_curtain'] + $row['total_cost_single_curtain'];
						$total_cost_plural = $row['total_cost_plural_no_curtain'] + $row['total_cost_plural_curtain'];
				   
						$result['item_type_id']  				= $row['item_type_id'];
						$result['item_name']  					= $row['item_name'];
						
						$result['total_Paid_curtain_single']  	= $row['total_Paid_curtain_single'];
						$result['quantity_single']  			= $row['quantity_single'];
						$result['total_cost_single']  			= $total_cost_single;
						
						$result['total_Paid_curtain_plural']  	= $row['total_Paid_curtain_plural'];
						$result['Quantity_plural']  			= $row['Quantity_plural'];
						$result['total_cost_plural']  			= $total_cost_plural;
						
						$result['total_Paid_Raw']  				= $row['total_Paid_Raw'];
						$result['Quantity_Raw']  				= $row['Quantity_Raw'];
						$result['total_cost_raw']  				= $row['total_cost_raw'];
						
						$result['total_remain_raw']  			= $row['total_cost_raw'] - $row['total_Paid_Raw'];
						
						$result['total_remain_s']  				= $total_cost_single - $row['total_Paid_curtain_single'];
						
						$result['total_remain_m']  				= $total_cost_plural - $row['total_Paid_curtain_plural'];
						

						$result['No_of_s_inv']  				= $row['No_of_s_inv'];
						$result['No_of_m_inv']  				= $row['No_of_m_inv'];
						$result['No_of_raw_inv']  				= $row['No_of_raw_inv'];
						
						$result['total_other_Paid_Raw']  		= $row['total_other_Paid_Raw'];
						$result['Quantity_other_Raw']  			= $row['Quantity_other_Raw'];
						$result['total_cost_other_raw']  		= $row['total_cost_other_raw'];

						$result['total_other_Paid_S']  			= $row['total_other_Paid_S'];
						$result['Quantity_other_S']  			= $row['Quantity_other_S'];
						$result['total_cost_other_S']  			= $row['total_cost_other_S'];

						$result['total_other_Paid_M']  			= $row['total_other_Paid_M'];
						$result['Quantity_other_M']  			= $row['Quantity_other_M'];
						$result['total_cost_other_M']  			= $row['total_cost_other_M'];

						$result['total_remain_other_raw']  		= $row['total_cost_other_raw'] - $row['total_other_Paid_Raw'];
						
						$result['total_remain_other_s']  		= $row['total_cost_other_S'] - $row['total_other_Paid_S'];
						
						$result['total_remain_other_m']  		= $row['total_cost_other_M'] - $row['total_other_Paid_M'];
						

						array_push($op['sell'],$result);
				}


				// now we should get withdraw totals

				$res = $db->query("
								SELECT									
										customer_full_name,
										
										COALESCE((SELECT count(withdraw_amount) FROM capital_withdraw CW  WHERE CW.is_deleted =0 AND CW.gived_to_id_fk = C.customer_id  $cond_CW),0) AS total_withdraw_no,

										COALESCE((SELECT count(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0  AND CWP1.payment_gived_to_id_fk = C.customer_id  $cond_CWP1),0) AS total_paid_no,

										COALESCE((SELECT sum(withdraw_amount) FROM capital_withdraw CW  WHERE CW.is_deleted =0 AND CW.gived_to_id_fk = C.customer_id  $cond_CW),0) AS total_amount,

										COALESCE((SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0  AND CWP1.payment_gived_to_id_fk = C.customer_id  $cond_CWP1),0) AS total_paid,
										(
										COALESCE((SELECT sum(withdraw_amount) FROM capital_withdraw CW  WHERE CW.is_deleted =0 AND CW.gived_to_id_fk = C.customer_id  $cond_CW),0)
										-
										COALESCE((SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0  AND CWP1.payment_gived_to_id_fk = C.customer_id  $cond_CWP1),0)
										 ) AS total_remained
								FROM customer C
						
								WHERE  C.is_deleted = 0  $with_cust_id  $cond_cust_typ");
			
			if ($res) {
				
				$total_item_type_price 		=0;
				$total_item_type_paid	 	=0;

				while ($row = $res->fetch_assoc()) {

					 
					$result_w['total_withdraw_price']		= $row['total_amount'];
					$result_w['total_withdraw_paid'] 		= $row['total_paid'];
					$result_w['total_withdraw_remaind'] 	= $row['total_remained'];
					$result_w['total_withdraw_no'] 			= $row['total_withdraw_no'];
					$result_w['total_paid_no']			 	= $row['total_paid_no'];
					$result_w['customer_full_name']			= $row['customer_full_name'];
					
					array_push($op['withdraw'],$result_w);

						
				}



				
			}

				echo json_encode($op);
				exit;
			}else{
				echo 0;
				echo $db->error;
				exit;
			}
		}

	

		if ($_POST['type'] == "add_invoice_payment") {

			$id 						= $_POST['customer_id_fk'];
			$paid_amount				=addslashes($_POST["paid_amount"]);
			$paid_date					=addslashes($_POST["paid_date"]);
			$payment_note				=addslashes($_POST["payment_note"]);
			
			$item_type_id_fk 	= $_POST['item_type_id_fk'];

			$cond = '';
			if($item_type_id_fk != '' && $item_type_id_fk != NULL){
				$cond = " AND S.item_type_id_fk = '$item_type_id_fk' ";
			}

			$rnd_no						=rand(100000000,1000000000);
			$invoice_currency			= 1; //USD
			$reg_date 					= date("Y-m-d h:i:s", time());
			
			$next_payment_date 			='';
			$next_payment_amount 		= '';

			$op  = array('is_success'=>false, 'data' => '');

			if($paid_amount <= 0 || $paid_amount == '' || $paid_amount == NULL || !is_numeric($paid_amount)){
				$op['is_success'] = false;
				$op['data'] 	  = "الرجاء قم بادخال دفعة صحيحة";
				echo json_encode($op);
				exit;
			}
			

			$remain_after_paying = $paid_amount;
			
			$is_added = false; // to check may this customer has all invoices paid so the insertion will not happend
			$successfully = false;

		// check if the select type is add withdraw just
		if($item_type_id_fk != 'w'){
				
			

			// here we will bring all invoices for the current customer that not paid
			$res = $db->query("SELECT invoice_id, 
									invoice_number, 						
									invoice_status,  
									sell_item_quantity, 
									customer_id_fk,  
									actual_discount,
									item_sell_price_per_meter,
									decorate_price_per_meter, 
									is_paid,
									S.item_type_id_fk, 
								  	other_id_fk, 
								  	S.product_id_fk,
                                    sell_item_id,
								    customer_full_name,
															 
									CONCAT(COALESCE(erbil_code,''), COALESCE(other_name,'')) 
									AS product_name,

									(SELECT sum(paid_amount) FROM invoice_payment IP WHERE I.invoice_id = IP.invoice_id_fk AND IP.is_returned=0 AND IP.is_deleted =0) 
									AS total_paid,
																
									(SELECT sum(actual_discount) FROM sell_item SI WHERE I.invoice_id = SI.invoice_id_fk AND SI.is_deleted =0) 
									AS total_discount,

									
									(

									COALESCE((SELECT sum(sell_item_detail_height * item_sell_price_per_meter) FROM sell_item_detail SID, sell_item S 
											          			
									WHERE I.invoice_id = SID.invoice_id_fk AND S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND  SID.part_status =0 AND SID.is_deleted=0 AND S.sell_item_id = SID.sell_item_id_fk AND S.other_id_fk =0 AND SID.sell_item_detail_width = 0),0)
									+
									COALESCE((SELECT sum(sell_item_detail_height * sell_item_detail_width * item_sell_price_per_meter) FROM sell_item_detail SID, sell_item S 
											          			
									WHERE I.invoice_id = SID.invoice_id_fk AND S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND  SID.part_status =0 AND SID.is_deleted=0 AND S.sell_item_id = SID.sell_item_id_fk AND S.other_id_fk =0 AND SID.sell_item_detail_width > 0),0)
									+
									COALESCE((SELECT sum(sell_item_detail_width * decorate_price_per_meter) FROM sell_item_detail SID, sell_item S 
											          			
									WHERE I.invoice_id = SID.invoice_id_fk AND S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND  SID.part_status =0 AND SID.is_deleted=0 AND S.sell_item_id = SID.sell_item_id_fk AND S.other_id_fk =0 AND SID.sell_item_detail_width > 0),0)

									+
									COALESCE((SELECT sum(sell_item_quantity * item_sell_price_per_meter) FROM sell_item S  
									WHERE I.invoice_id = S.invoice_id_fk AND  S.other_id_fk >0 AND S.is_deleted=0),0)
									-
									(SELECT sum(actual_discount) from sell_item where sell_item.invoice_id_fk = I.invoice_id AND sell_item.is_deleted=0 )
																
									) 
									AS total_invoice_price,


									(SELECT sum(sell_item_detail_height) FROM sell_item_detail SID WHERE SID.invoice_id_fk = I.invoice_id AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0) 
									AS total_length,

									(SELECT sum(paid_amount) FROM invoice_payment IP1 WHERE				   I.invoice_id = IP1.invoice_id_fk AND IP1.sell_item_id_fk=S.sell_item_id AND IP1.is_returned=0 AND IP1.is_deleted =0) 
									AS total_paid_per_product,
																													
													
									(SELECT sum(sell_item_detail_height * sell_item_detail_width) FROM sell_item_detail SID WHERE SID.invoice_id_fk = I.invoice_id AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0 AND SID.sell_item_detail_width > 0) 
									AS total_area,
																													
									(SELECT sum(sell_item_detail_width) FROM sell_item_detail SID WHERE SID.invoice_id_fk = I.invoice_id AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0 AND SID.sell_item_detail_width > 0) 
									AS total_decor_width


								FROM invoice I
							 		LEFT JOIN sell_item S ON (S.invoice_id_fk = I.invoice_id AND S.is_deleted=0  $cond)
							 		LEFT JOIN others O ON (S.other_id_fk = O.other_id AND S.other_id_fk >0)
									LEFT JOIN product P ON (S.product_id_fk = P.product_id )
									LEFT JOIN customer C ON (I.customer_id_fk = C.customer_id )
							 	WHERE I.customer_id_fk='$id'  AND I.is_deleted = 0 AND I.invoice_status <2
							 	");
			
			
			while ($row = $res->fetch_assoc()) {
				
				$total_row_price = 0;

				
                
                if($row['other_id_fk'] > 0){
                  $total_row_price = $row['sell_item_quantity'] * $row['item_sell_price_per_meter'] - $row['actual_discount'];
                }else{
                  
                  if($row['total_area'] > 0 && $row['total_area'] != NULL){ // it mean its curtain
                    $total_row_price = $row['total_area'] * $row['item_sell_price_per_meter'] + $row['total_decor_width'] * $row['decorate_price_per_meter'] - $row['actual_discount'];
                  }else{
                    $total_row_price = $row['total_length'] * $row['item_sell_price_per_meter'] - $row['actual_discount'];
                  }
                } 






                $remainded_per_row = $total_row_price - $row['total_paid_per_product'];

                // now we should check every row in each invoice and see if its has remain if it has remain we should add amount from paid_amout and update its status and the invoice status also

                if($remain_after_paying > 0){ // check if we have paid_amout and its not finished

	                if($remainded_per_row > 0){ // it have remaind we will add payment

	                	// now we should check if the paid_amout more or less the remainded_per_row

	                	if($remain_after_paying >= $remainded_per_row ){ // that mean the paid_amout greater than this row remaind and we can make another adding to defferent rows
	                		$remain_after_paying = $remain_after_paying - $remainded_per_row;
	                		$row_new_payment 	 = $remainded_per_row;
	                	}else{ // that mean the paid_amount less than the remained so we will make it 0 and insert all the paid_amount in this row
	                		
	                		$row_new_payment 	 = $remain_after_paying;
	                		$remain_after_paying = 0;
	                	}

	                	$sell_id 	= $row['sell_item_id'];
	                	$inv_id_fk 	= $row['invoice_id'];
	                	$cust_id_fk = $row['customer_id_fk'];

	                	// here the insertion & update of payment will be done

	                	$lastaction 				="Add Payment for Invoice";

	                	$db->autocommit(FALSE); // to rollback insertion if update fail

						$sql ="INSERT INTO invoice_payment (pay_usd_rate, 
															pay_currency, 
															paid_amount,
															paid_date,
															next_payment_date,
															next_payment_amount,
															payment_note,
															sell_item_id_fk, 
															invoice_id_fk,
															customer_id_fk, 
															group_no, 
															created_by, 
															last_action, 
															last_action_by)
	 											VALUES(	'".$_SESSION['USD_TO_IQD']."',
 															'$invoice_currency',
 															'$row_new_payment',
 														 	'$reg_date',
 														 	'$next_payment_date',
 														 	'$next_payment_amount',
 														 	'$payment_note',
 														 	'$sell_id',
 														 	'$inv_id_fk',
 														 	'$cust_id_fk',
 														 	'$rnd_no',
 														 	'".$_SESSION['user_id']."',
 														 	'$lastaction',
 														 	'".$_SESSION['user_id']."')";
						
						$res_pay = $db->query($sql);
						
						if ($res_pay){

							// we should update sell_item pay status 

							$res1 = $db->query("SELECT 	sell_item_id,
														invoice_total_price_actual, 					  
														sell_item_quantity, 
														actual_discount,
														item_sell_price_per_meter,
														decorate_price_per_meter, 
														is_paid,
														(SELECT sum(paid_amount) FROM invoice_payment IP WHERE I.invoice_id = IP.invoice_id_fk AND IP.is_returned=0 AND IP.is_deleted =0) AS total_paid,

														(SELECT sum(sell_item_detail_height) FROM sell_item_detail SID WHERE SID.invoice_id_fk = I.invoice_id AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0) AS total_length,


														(SELECT sum(paid_amount) FROM invoice_payment IP1 WHERE I.invoice_id = IP1.invoice_id_fk AND IP1.sell_item_id_fk=S.sell_item_id AND IP1.is_returned=0 AND IP1.is_deleted =0 ) AS total_paid_per_product,
    																				
														(SELECT sum(sell_item_detail_height * sell_item_detail_width) FROM sell_item_detail SID WHERE SID.invoice_id_fk = I.invoice_id AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0 AND SID.sell_item_detail_width > 0) AS total_area,
																							
														(SELECT sum(sell_item_detail_width) FROM sell_item_detail SID WHERE SID.invoice_id_fk = I.invoice_id AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0 AND SID.sell_item_detail_width > 0) AS total_decor_width,

														(

											          	COALESCE((SELECT sum(sell_item_detail_height * item_sell_price_per_meter) FROM sell_item_detail SID, sell_item S 
																		          			
											        	WHERE I.invoice_id = SID.invoice_id_fk AND S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND  SID.part_status =0 AND SID.is_deleted=0 AND S.sell_item_id = SID.sell_item_id_fk AND S.other_id_fk =0 AND SID.sell_item_detail_width = 0),0)
												    	+
												   		COALESCE((SELECT sum(sell_item_detail_height * sell_item_detail_width * item_sell_price_per_meter) FROM sell_item_detail SID, sell_item S 
																		          			
											        	WHERE I.invoice_id = SID.invoice_id_fk AND S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND  SID.part_status =0 AND SID.is_deleted=0 AND S.sell_item_id = SID.sell_item_id_fk AND S.other_id_fk =0 AND SID.sell_item_detail_width > 0),0)
												    	+
												   		COALESCE((SELECT sum(sell_item_detail_width * decorate_price_per_meter) FROM sell_item_detail SID, sell_item S 
																		          			
										        		WHERE I.invoice_id = SID.invoice_id_fk AND S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND  SID.part_status =0 AND SID.is_deleted=0 AND S.sell_item_id = SID.sell_item_id_fk AND S.other_id_fk =0 AND SID.sell_item_detail_width > 0),0)

												    	+
												    	COALESCE((SELECT sum(sell_item_quantity * item_sell_price_per_meter) FROM sell_item S  
														WHERE I.invoice_id = S.invoice_id_fk AND  S.other_id_fk >0 AND S.is_deleted=0),0)
														-
												 		(SELECT sum(actual_discount) from sell_item where sell_item.invoice_id_fk = I.invoice_id AND sell_item.is_deleted=0 )
														) AS total_invoice_price

													FROM invoice I
			 										LEFT JOIN sell_item S ON (S.invoice_id_fk = I.invoice_id AND S.is_deleted=0 AND S.sell_item_id='$sell_id')
										 		
			 										WHERE I.invoice_id='$inv_id_fk'  AND I.is_deleted = 0");

							$row1 = $res1->fetch_assoc();

							$total_length 					= $row1['total_length'];
							$total_paid_per_product 		= $row1['total_paid_per_product'];
							$total_payments					= $row1['total_paid'];
							$net_balance 					= $row1['total_invoice_price'];
							$sell_item_quantity 			= $row1['sell_item_quantity'];
							$actual_discount 				= $row1['actual_discount'];
							$item_sell_price_per_meter 		= $row1['item_sell_price_per_meter'];
							$decorate_price_per_meter 		= $row1['decorate_price_per_meter'];
							$is_paid 						= $row1['is_paid'];
							$total_area 					= $row1['total_area'];
							$total_decor_width 				= $row1['total_decor_width'];
							
							// compute total product price

							$total_product_price = 0;
							
							
							
							if($total_length > 0 && $total_length !=NULL){

								if($total_area > 0 && $total_area !=NULL){ // it mean curtain
									$total_product_price = ($total_area * $item_sell_price_per_meter) + ($total_decor_width * $decorate_price_per_meter) -  $actual_discount;
								}else{
									$total_product_price = ($total_length * $item_sell_price_per_meter) -  $actual_discount;
								}

							}else{
								$total_product_price = ($sell_item_quantity * $item_sell_price_per_meter) -  $actual_discount;
							}

							if($total_paid_per_product >= $total_product_price ){
								$is_paid_sell = 2;
							}elseif($total_paid_per_product < $total_product_price AND $total_paid_per_product >0 ){
								$is_paid_sell = 1;
							}else{
								$is_paid_sell = 0;
							}

							$lastaction = "Update Product Payment Status after adding Payment for customer";

							$update_qry = "UPDATE sell_item SET  is_paid='$is_paid_sell',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id_fk = $inv_id_fk AND sell_item_id='$sell_id' ";

							$res2 = $db->query($update_qry);

							if ($res2) {

								// update invoice status
											
								// echo "remainded_per_row=".$remainded_per_row.";;;";
								// echo "total_product_price=".$total_product_price.";;;";
								// echo "total_paid_per_product=".$total_paid_per_product.";;;";
								// echo "row_new_payment=".$row_new_payment.";;;";

								$lastaction = "Update Invoice status after Adding payments for customer";

								if($total_payments >= $net_balance ){
									$is_paid = 2; // complete paid
									$pay_term = 0;
									$update_qry1 = "UPDATE invoice SET  invoice_status='$is_paid',pay_terms='$pay_term',last_action='$lastaction',
									last_action_by='".$_SESSION['user_id']."' WHERE invoice_id = $inv_id_fk";

								}elseif($total_payments < $net_balance AND $total_payments >0 ){
									$is_paid = 1; // partially paid
									$update_qry1 = "UPDATE invoice SET  invoice_status='$is_paid',last_action='$lastaction',
									last_action_by='".$_SESSION['user_id']."' WHERE invoice_id = $inv_id_fk";
								}
								// echo "$total_payments= ".$total_payments . "  $net_balance=".$net_balance;
								$res3 = $db->query($update_qry1);

								if ($res3) {
									$db->commit();
									
									$successfully = true;
									// exit;

								}else{
									$db->rollback();
									$op['is_success'] = false;
									$op['data'] 	  = "حصل خطأ : لم يتم تحديث حالة الدفع للوصل ";
									echo json_encode($op);
									exit;
								}
										
							}else{
								// $op['data'] 	  = $db->error;

								$db->rollback();
								$op['is_success'] = false;
								$op['data'] 	  = "حصل خطأ : لم يتم تحديث حالة الدفع للمادة ";
								echo json_encode($op);
								exit;
							}
									


						}else{

							$db->rollback();
							$op['is_success'] = false;
							$op['data'] 	  = "حصل خطأ : لم يتم اضافة الدفوعات ";

							echo json_encode($op);
							exit;
						}


	                	// end insertion & update of payment


	                } // if remainded_per_row
	            
	            }else{ // if remain_after_paying
	            		// that mean the paid amount was finished and we should stop the while and exit 

	            	if($successfully == false){
						$op['is_success'] = false;
						$op['data'] 	  = "الرجاء قم بادخال دفعة واحدة على الاقل";
						echo json_encode($op);
						exit;
					}else{
						$op['is_success'] = true;
						$op['data'] 	  = "تمت عملية الاضافة بنجاح";
						echo json_encode($op);
						exit;
					}

	            } 

				
						
			} // while

		} // if item_type_id_fk !=w


			// here after we add the payment to all invoice we should check if still remaind money we will add it to withdraw

			$res1 = $db->query("SELECT customer_id,
									   (COALESCE((SELECT sum(withdraw_amount) FROM capital_withdraw CW WHERE CW.is_deleted =0 AND CW.gived_to_id_fk =C.customer_id),0)
									   -
									   COALESCE((SELECT sum(payment_withdraw_amount) FROM capital_withdraw_payments CWP1 WHERE  CWP1.is_deleted = 0 AND CWP1.payment_gived_to_id_fk = C.customer_id ),0)
									   ) AS total_withdraw_remaid

								FROM customer C 
										 		
								WHERE C.customer_id='$id'  AND C.is_deleted = 0");

			$row1 = $res1->fetch_assoc();

			$remainded_per_row = $row1['total_withdraw_remaid'];

			$before_add_withdraw = $remain_after_paying ;
			


			if($remain_after_paying > 0){ // check if we have paid_amout and its not finished

                if($remainded_per_row > 0){ // it have remaind we will add payment

                	// now we should check if the paid_amout more or less the remainded_per_row

                	if($remain_after_paying >= $remainded_per_row ){ // that mean the paid_amout greater than this row remaind and we can make another adding to defferent rows
                		$remain_after_paying = $remain_after_paying - $remainded_per_row;
                		$row_new_payment 	 = $remainded_per_row;
                	}else{ // that mean the paid_amount less than the remained so we will make it 0 and insert all the paid_amount in this row
                		
                		$row_new_payment 	 = $remain_after_paying;
                		$remain_after_paying = 0;
                	}

     //            	echo $remainded_per_row . " # ";
     //            	echo $row_new_payment . " # ";
					// echo $remain_after_paying;

                	$lastaction = "Add New Payment to Capital_withdraw";
                	

					$sql_1 ="INSERT INTO capital_withdraw_payments (payment_withdraw_amount,
												payment_withdraw_date,
												payment_withdraw_usd_rate,
												payment_withdraw_currency,
												payment_withdraw_note,
												payment_gived_to_id_fk,
												created_by,
												last_action,
												last_action_by)
										VALUES( '$row_new_payment',
												'$paid_date',
												'".$_SESSION['USD_TO_IQD']."',
												'1',
												'$payment_note',
												'$id',
												'".$_SESSION['user_id']."',
												'$lastaction',
												'".$_SESSION['user_id']."')";

					$res_1 = $db->query($sql_1);

					if ($res_1) {
							$db->commit();
							if($remain_after_paying > 0){
								$op['is_success'] = true;
								$op['data'] 	  = "تمت عملية الاضافة بنجاح .. لكن المبلغ المدفوع اكبر من المبلغ الكلي المتبقي ولذلك لم يتم اضافة هذا المبلغ :";
								$op['amount'] 	  = $remain_after_paying;
								echo json_encode($op);
								exit;
							}else{
								$op['is_success'] = true;
								$op['data'] 	  = "تمت عملية الاضافة بنجاح";
								echo json_encode($op);
								exit;
							}
					}else{
							
							$db->rollback();
							// if finish while loop that mean this customer has all invoices paid and we didnt add anything
							if($successfully == false){
								$op['is_success'] = false;
								$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								echo json_encode($op);
								exit;


							}else{

								
								$op['is_success'] = false;
								$op['data'] 	  = "تمت عملية الاضافة للمبيعات فقط ..لكن حصل خطأ اثناء اضافة دفعة للقروض.. والمبلغ المتبقي وغير المضاف هو :";
								$op['amount'] 	  = $before_add_withdraw;
								echo json_encode($op);
								exit;
								
								
							}
					}

                }
            }

			
			// if finish while loop that mean this customer has all invoices paid and we didnt add anything
			if($successfully == false){
				$op['is_success'] = false;
				$op['data'] 	  = "هذا الزبون حسابه كامل ولم يكن عليه اي باقي.. الرجاء التحقق من كشوفات الحساب له";
				echo json_encode($op);
				exit;

			}else{

				if($remain_after_paying > 0){
					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية الاضافة بنجاح .. لكن المبلغ المدفوع اكبر من المبلغ الكلي المتبقي ولذلك لم يتم اضافة هذا المبلغ :";
					$op['amount'] 	  = $remain_after_paying;
					echo json_encode($op);
					exit;
				}else{
					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية الاضافة بنجاح";
					echo json_encode($op);
					exit;
				}
				
			}


		}


		if ($_POST['type']=="delete") {

			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Product";

			$op  = array('is_success'=>false, 'data' => '');

			$res = $db->query("SELECT * FROM sell_roll_detail WHERE is_deleted=0 AND product_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه المادة فقط تم بيع البعض منها";
				echo json_encode($op);
				exit;
			}

			$res = $db->query("SELECT * FROM purchase_item_detail WHERE is_deleted=0 AND product_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه المادة فهي تحوي على قيم في جدول المشتريات !!";
				echo json_encode($op);
				exit;
			}

			

	  		$res = $db->query("UPDATE product SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_id=$id");
		    	if ($res){
		        		$op['is_success'] = true;
						$op['data'] 	  = "تمت عملية الحذف بنجاح";
						echo json_encode($op);
						exit;
		     	}else{
		      			$op['is_success'] = false;
						$op['data'] 	  = "حصل خطأ : السجل في امان";
						echo json_encode($op);
						exit;
		     	}
		}

		if ($_POST['type'] == "create") {
      		$item_type_id					=addslashes($_POST["item_type_id"]);
			$category_id					=addslashes($_POST["category_id"]);
			$erbil_code						=addslashes($_POST["erbil_code"]);
			$turkish_code					=addslashes($_POST["turkish_code"]);
			$barcode						=addslashes($_POST["barcode"]);
			$product_note					=addslashes($_POST["product_note"]);
			$product_min_notification		=addslashes($_POST["product_min_notification"]);

			// $res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND product_name = '$name'");
			// if (mysqli_num_rows($res)>0) {
			// 		$op['is_success'] = false;
			// 		$op['data'] 	  = "خطأ اسم المادة مكررة";
			// 		echo json_encode($op);
			// 		exit;
			// }

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND erbil_code = '$erbil_code'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ كود اربيل مكرر";
					echo json_encode($op);
					exit;
			}

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND turkish_code = '$turkish_code'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ كود تركيا مكرر";
					echo json_encode($op);
					exit;
			}

				$delete = 0;
				$reg_date = date("Y-m-d h:i:s", time());
				$lastaction = "Create New Product";

				$sql ="INSERT INTO product(item_type_id_fk,erbil_code,turkish_code,barcode,product_note,category_id_fk,created_by,last_action,last_action_by)
				VALUES('$item_type_id','$erbil_code','$turkish_code','$barcode','$product_note','$category_id','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";

				$res = $db->query($sql);

					if ($res) {

								$last_inserted_id = $db->insert_id;

									/// for file upload
									$target_dir = '../product_img/'.$last_inserted_id;
									if(! file_exists($target_dir)){
										mkdir($target_dir);
									}
									// $target_dir = "../image/sys/";

									$count=0;

			            foreach ($_FILES['files_upload']['name'] as $filename)
			            {
											// print_r($_FILES);
			                // $tmp=$_FILES['files_upload']['tmp_name'][$count];
											$fileBook = rand(1000,100000) . "-" .$_FILES['files_upload']['name'][$count];

			                // $temp=$temp.basename($filename);
											$target_file = $target_dir .'/'. basename($fileBook);

											$uploadOk = 1;
											$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

											// $check = getimagesize($_FILES["files_upload"]["tmp_name"][$count]);
										  // if($check == false) {
											// 	 $error= " File is not an image. ";
											// 	 $State=false;
										  // }else {
											//  	 $State=true;
										  // }
											 $State=true;
											// Check file size
											if ($_FILES["files_upload"]["size"][$count] > 3500000) {
													$error= " Sorry, your file is too large. ";
													$State=false;
											}
											// Allow certain file formats
											if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
											&& $imageFileType != "gif" ) {
													$error= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
													$State=false;
											}

											// Check if $uploadOk is set to 0 by an error
											if ($State == false) {
													$error= " Sorry, your file was not uploaded. ";
											// if everything is ok, try to upload file
											} else {
													//move_uploaded_file($tmp,$temp);
													if (move_uploaded_file($_FILES["files_upload"]["tmp_name"][$count], $target_file)) {
														$filePath = 'product_img/'.$last_inserted_id .'/'.$fileBook;
														// $sql = "UPDATE system_settings SET SYSCompanyLogo='$filePath' WHERE SYSID = 1";

														$sql ="INSERT INTO product_image
																			(product_id_fk,
																			image_path,
																			created_by,
																			last_action,
																			last_action_by)
																VALUES('$last_inserted_id',
																		'$filePath',
																		'".$_SESSION['user_id']."',
																		'$lastaction',
																		'".$_SESSION['user_id']."')";


														$query = $db->query($sql);
														if (!$query) {
																	$error= "Error: " . $db->error;
																	$State=false;

														}else{
																$error= " Student Successfully Added ";
																$State=true;
														}

													} else {
															$error= " Sorry, there was an error uploading your file. ";
															$State=false;
													}
											}

											$count = $count +1;
			                $filePath='';
			                $tmp='';
			            }


							$op['is_success'] = true;
							$op['data'] 	  = "تم الاضافة بنجاح";
							echo json_encode($op);
							exit;
					}
					else{
								$op['is_success'] = false;
								$op['data'] 	  = "هناك خطأ : لم يتم اضافة المادة الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								echo json_encode($op);
								exit;
					}
			

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