<?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");


		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 		= '';

		

		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 == 'No_of_inv' ||  $col == 'total_invoice_price' ||  $col == 'total_Paid' ||  $col == 'total_remained' ||  $col == 'No_of_s_inv' ||  $col == 'No_of_m_inv' ||  $col == 'No_of_s_inv' ||  $col == 'No_of_s_inv'){

						

					}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 == 'No_of_inv' ||  $col == 'total_invoice_price' ||  $col == 'total_Paid' ||  $col == 'total_remained' ||  $col == 'No_of_s_inv' ||  $col == 'No_of_m_inv' ||  $col == 'No_of_s_inv' ||  $col == 'No_of_s_inv'){


					
					}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($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			$cond = isset($_GET['typ'])? ' AND C.customer_type ='.$_GET['typ']:'';
			$cond1 = isset($_GET['ip'])? ' AND Inv.invoice_status='.$_GET['ip']:'';
			
			$primaryKey = 'customer_id';
			$columns = array(
			    array( 'db' => 'customer_id', 'dt' => 0 ),
			    array( 'db' => 'customer_full_name', 'dt' => 1 ),
			    array( 'db' => 'No_of_inv', 'dt' => 2),
			    array( 'db' => 'total_invoice_price', 'dt' => 3 ),
			    array( 'db' => 'total_Paid', 'dt' => 4 ),
			    array( 'db' => 'total_remained', 'dt' => 5 ),

				array( 'db' => 'No_of_s_inv', 'dt' => 6 ),
				array( 'db' => 'No_of_m_inv', 'dt' => 7 ),
					

				array( 'db' => 'No_of_raw_inv', 'dt' => 8 ),
				array( 'db' => 'No_of_withdraw', 'dt' => 9 ),
				array( 'db' => 'customer_phone', 'dt' => 10),
				array( 'db' => 'customer_phone2', 'dt' => 11),
				array( 'db' => 'total_payment_discount', 'dt' => 12),
				array( 'db' => 'total_payment_return', 'dt' => 13),
			);



			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 			customer_id,
										customer_full_name,
										customer_phone,
										customer_phone2,
										
										(
					          				COALESCE(SQTC.total_Cost,0)
											+
											COALESCE(SQTWP.total_invoice_price,0)
										) as total_invoice_price,


										IFNULL(SQTC.total_Cost,0)  as total_Cost,
										IFNULL(SQPP.total_Paid,0) as total_Paid,
	        							IFNULL(SQPD.total_payment_discount,0) AS total_payment_discount,
										IFNULL(SQPR.total_payment_return,0) AS total_payment_return,
	        							(0) AS total_remained,
										IFNULL(SQNS.No_of_s_inv,0) as No_of_s_inv,
										IFNULL(SQNM.No_of_m_inv,0) as No_of_m_inv,
										IFNULL(SQNR.No_of_raw_inv,0) as No_of_raw_inv,
										IFNULL(SQNI.No_of_inv,0) as No_of_inv,
										IFNULL(SQNW.No_of_withdraw,0) as No_of_withdraw

							FROM customer C 
                            
                   				LEFT JOIN (SELECT sum(withdraw_amount) AS total_invoice_price, gived_to_id_fk
                               				FROM capital_withdraw CW 
                               				WHERE  CW.is_deleted = 0 GROUP BY gived_to_id_fk) 
                               				SQTWP ON (SQTWP.gived_to_id_fk = C.customer_id)
                               
                            
			                   	LEFT JOIN (SELECT SUM(invoice_total_price_actual) AS total_Cost, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3  AND I.is_deleted = 0  GROUP BY customer_id_fk ) 
			                               SQTC ON (SQTC.customer_id_fk = C.customer_id)
			                               
			                   	         
			                   	LEFT JOIN (SELECT SUM(paid_amount) AS total_Paid, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Payment" GROUP BY customer_id_fk ) 
			                               SQPP ON (SQPP.customer_id_fk = C.customer_id)
			                               
			                               
			                            
			                   	LEFT JOIN (SELECT SUM(paid_amount) AS total_payment_discount, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Discount" GROUP BY customer_id_fk ) 
			                               SQPD ON (SQPD.customer_id_fk = C.customer_id)
			                               
			                    
			                    LEFT JOIN (SELECT SUM(paid_amount) AS total_payment_return, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Return" GROUP BY customer_id_fk ) 
			                               SQPR ON (SQPR.customer_id_fk = C.customer_id)
			                            
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_s_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=1  AND I.is_deleted = 0 AND I.is_single=1 GROUP BY customer_id_fk ) 
			                               SQNS ON (SQNS.customer_id_fk = C.customer_id)
			                            
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_m_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=1  AND I.is_deleted = 0 AND I.is_single=0 GROUP BY customer_id_fk ) 
			                               SQNM ON (SQNM.customer_id_fk = C.customer_id)
			                               
								
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_raw_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=0  AND I.is_deleted = 0 AND I.is_single=0 GROUP BY customer_id_fk ) 
			                               SQNR ON (SQNR.customer_id_fk = C.customer_id)
			                               
								
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.is_deleted = 0 GROUP BY customer_id_fk ) 
			                               SQNI ON (SQNI.customer_id_fk = C.customer_id)
			                               
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_withdraw, gived_to_id_fk
			                               FROM capital_withdraw CW 
			                               WHERE  CW.is_deleted = 0 GROUP BY gived_to_id_fk) 
			                               SQNW ON (SQNW.gived_to_id_fk = C.customer_id) 

					WHERE C.is_deleted=0 '.$cond.' '.$fltr.' '. $ords. ' '.$limit.'
				)
			) AS ALLTBL';

			$table1  =  '(
				(
								SELECT 	customer_id,
										customer_full_name,
										customer_phone,
										customer_phone2,
										

									
									(

				          			COALESCE((SELECT sum(invoice_total_price_actual) 
				          			FROM invoice I 
								    WHERE I.customer_id_fk = C.customer_id 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.gived_to_id_fk = C.customer_id ),0)
									
									) as total_invoice_price,


									(SELECT SUM(invoice_total_price_actual) FROM invoice I WHERE I.invoice_status <3 AND  I.is_deleted = 0 AND I.customer_id_fk = C.customer_id)  as total_Cost,

									(
										COALESCE((SELECT sum(paid_amount) FROM payments IP1 
       								
        								WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.customer_id_fk = C.customer_id AND IP1.payment_transaction ="Payment" ),0)

        							) as total_Paid,

        							(
        								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 ="Discount" ),0)
        							) AS total_payment_discount,

									(
										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_payment_return,


        							(0) AS total_remained,
        
									(SELECT COUNT(*) FROM invoice I  
									WHERE I.invoice_status <3 AND  I.invoice_type=1  AND I.is_deleted = 0  AND I.is_single=1 AND I.customer_id_fk = C.customer_id ) as No_of_s_inv,


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

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

									(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 ) as No_of_withdraw


							FROM customer C 

					WHERE C.is_deleted=0 '.$cond.' '.$fltr.' '. $ords. ' '.$limit.'
				)
			) AS ALLTBL';


			$raw_table  =  '(
							(
								SELECT 	customer_id,
										customer_full_name,
										customer_phone,
										customer_phone2,
										
										(
					          				COALESCE(SQTC.total_Cost,0)
											+
											COALESCE(SQTWP.total_invoice_price,0)
										) as total_invoice_price,


										IFNULL(SQTC.total_Cost,0)  as total_Cost,
										IFNULL(SQPP.total_Paid,0) as total_Paid,
	        							IFNULL(SQPD.total_payment_discount,0) AS total_payment_discount,
										IFNULL(SQPR.total_payment_return,0) AS total_payment_return,
	        							(0) AS total_remained,
										IFNULL(SQNS.No_of_s_inv,0) as No_of_s_inv,
										IFNULL(SQNM.No_of_m_inv,0) as No_of_m_inv,
										IFNULL(SQNR.No_of_raw_inv,0) as No_of_raw_inv,
										IFNULL(SQNI.No_of_inv,0) as No_of_inv,
										IFNULL(SQNW.No_of_withdraw,0) as No_of_withdraw

							FROM customer C 
                            
                   				LEFT JOIN (SELECT sum(withdraw_amount) AS total_invoice_price, gived_to_id_fk
                               				FROM capital_withdraw CW 
                               				WHERE  CW.is_deleted = 0 GROUP BY gived_to_id_fk) 
                               				SQTWP ON (SQTWP.gived_to_id_fk = C.customer_id)
                               
                            
			                   	LEFT JOIN (SELECT SUM(invoice_total_price_actual) AS total_Cost, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3  AND I.is_deleted = 0  GROUP BY customer_id_fk ) 
			                               SQTC ON (SQTC.customer_id_fk = C.customer_id)
			                               
			                   	         
			                   	LEFT JOIN (SELECT SUM(paid_amount) AS total_Paid, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Payment" GROUP BY customer_id_fk ) 
			                               SQPP ON (SQPP.customer_id_fk = C.customer_id)
			                               
			                               
			                            
			                   	LEFT JOIN (SELECT SUM(paid_amount) AS total_payment_discount, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Discount" GROUP BY customer_id_fk ) 
			                               SQPD ON (SQPD.customer_id_fk = C.customer_id)
			                               
			                    
			                    LEFT JOIN (SELECT SUM(paid_amount) AS total_payment_return, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Return" GROUP BY customer_id_fk ) 
			                               SQPR ON (SQPR.customer_id_fk = C.customer_id)
			                            
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_s_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=1  AND I.is_deleted = 0 AND I.is_single=1 GROUP BY customer_id_fk ) 
			                               SQNS ON (SQNS.customer_id_fk = C.customer_id)
			                            
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_m_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=1  AND I.is_deleted = 0 AND I.is_single=0 GROUP BY customer_id_fk ) 
			                               SQNM ON (SQNM.customer_id_fk = C.customer_id)
			                               
								
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_raw_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=0  AND I.is_deleted = 0 AND I.is_single=0 GROUP BY customer_id_fk ) 
			                               SQNR ON (SQNR.customer_id_fk = C.customer_id)
			                               
								
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.is_deleted = 0 GROUP BY customer_id_fk ) 
			                               SQNI ON (SQNI.customer_id_fk = C.customer_id)
			                               
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_withdraw, gived_to_id_fk
			                               FROM capital_withdraw CW 
			                               WHERE  CW.is_deleted = 0 GROUP BY gived_to_id_fk) 
			                               SQNW ON (SQNW.gived_to_id_fk = C.customer_id)

					WHERE C.is_deleted=0 '.$cond.' '.$fltr.' 
				)
			) AS ALLTBL';

			$raw_table1  =  '(
							(
								SELECT 	customer_id,
										customer_full_name,
										customer_phone,
										customer_phone2,
										

									
									(

				          			COALESCE((SELECT sum(invoice_total_price_actual) 
				          			FROM invoice I 
								    WHERE I.customer_id_fk = C.customer_id 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.gived_to_id_fk = C.customer_id ),0)
									
									) as total_invoice_price,


									(SELECT SUM(invoice_total_price_actual) FROM invoice I WHERE I.invoice_status <3 AND  I.is_deleted = 0 AND I.customer_id_fk = C.customer_id)  as total_Cost,

									(
									COALESCE((SELECT sum(paid_amount) FROM payments IP1 
       								
        							WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.customer_id_fk = C.customer_id AND IP1.payment_transaction ="Payment" ),0)

        							) as total_Paid,

        							(
        							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 ="Discount" ),0)
        							) AS total_payment_discount,

									(
									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_payment_return,


        							(0) AS total_remained,
        
									(SELECT COUNT(*) FROM invoice I  
									WHERE I.invoice_status <3 AND  I.invoice_type=1  AND I.is_deleted = 0  AND I.is_single=1 AND I.customer_id_fk = C.customer_id ) as No_of_s_inv,


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

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

									(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 ) as No_of_withdraw


					FROM customer C 

					WHERE C.is_deleted=0 '.$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;
		}


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

			$id 		= $_POST['cust_type'];
			
			$cond = (isset($_POST['cust_type']) && $_POST['cust_type'] != 'not' )? ' AND C.customer_type ='.$_POST['cust_type']:'';

			if ($_POST['search'] != '') {
				 $cond = $cond . " AND customer_full_name LIKE '%".$_POST['search']."%'";
			}
			
			// $res = $db->query('SELECT 	customer_address,
			// 							customer_id,
			// 							customer_full_name,
			// 							customer_phone,
			// 							customer_phone2,
					

									
			// 							(

			// 		          			COALESCE((SELECT sum(invoice_total_price_actual) FROM 
			// 	          				 invoice I 
			// 					        WHERE  I.customer_id_fk = C.customer_id 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.gived_to_id_fk = C.customer_id ),0)
										
			// 							) as total_invoice_price,


			// 							(SELECT SUM(invoice_total_price_actual) FROM invoice I WHERE I.invoice_status <3 AND  I.is_deleted = 0 AND I.customer_id_fk = C.customer_id)  as total_Cost,

			// 							(
			// 								COALESCE((SELECT sum(paid_amount) FROM payments IP1 
		       								
		 //        							WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.customer_id_fk = C.customer_id AND IP1.payment_transaction ="Payment" ),0)

		 //        						) as total_Paid,

		 //        						(
		 //        							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 ="Discount" ),0)
		 //        						) AS total_payment_discount,

			// 							(
			// 								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_payment_return,


		 //        						(
		 //        						(
										
			// 							COALESCE((SELECT sum(invoice_total_price_actual) FROM invoice I 
			// 					        WHERE I.customer_id_fk = C.customer_id 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.gived_to_id_fk = C.customer_id ),0)
											
			// 							)
		 //        						-
		 //        						(
		 //        							COALESCE((SELECT sum(paid_amount) FROM payments IP1 
		       								
		 //        							WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.customer_id_fk = C.customer_id AND IP1.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 ="Discount" ),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_remained,
	        
			// 							(SELECT COUNT(*) FROM invoice I  
			// 							WHERE I.invoice_status <3 AND  I.invoice_type=1  AND I.is_deleted = 0  AND I.is_single=1 AND I.customer_id_fk = C.customer_id ) as No_of_s_inv,


			// 							(SELECT COUNT(*) FROM invoice I	WHERE I.invoice_status <3 AND  I.invoice_type=1  AND I.is_deleted = 0  AND I.is_single=0 AND I.customer_id_fk = C.customer_id) as No_of_m_inv,

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

			// 							(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 ) as No_of_withdraw


			// 			FROM customer C WHERE C.is_deleted=0 '. $cond);

			$res = $db->query('SELECT 	customer_id,
										customer_full_name,
										customer_phone,
										customer_phone2,
										customer_address ,
										
										(
					          				COALESCE(SQTC.total_Cost,0)
											+
											COALESCE(SQTWP.total_invoice_price,0)
										) as total_invoice_price,


										IFNULL(SQTC.total_Cost,0)  as total_Cost,
										IFNULL(SQPP.total_Paid,0) as total_Paid,
	        							IFNULL(SQPD.total_payment_discount,0) AS total_payment_discount,
										IFNULL(SQPR.total_payment_return,0) AS total_payment_return,
	        							(0) AS total_remained,
										IFNULL(SQNS.No_of_s_inv,0) as No_of_s_inv,
										IFNULL(SQNM.No_of_m_inv,0) as No_of_m_inv,
										IFNULL(SQNR.No_of_raw_inv,0) as No_of_raw_inv,
										IFNULL(SQNI.No_of_inv,0) as No_of_inv,
										IFNULL(SQNW.No_of_withdraw,0) as No_of_withdraw

							FROM customer C 
                            
                   				LEFT JOIN (SELECT sum(withdraw_amount) AS total_invoice_price, gived_to_id_fk
                               				FROM capital_withdraw CW 
                               				WHERE  CW.is_deleted = 0 GROUP BY gived_to_id_fk) 
                               				SQTWP ON (SQTWP.gived_to_id_fk = C.customer_id)
                               
                            
			                   	LEFT JOIN (SELECT SUM(invoice_total_price_actual) AS total_Cost, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3  AND I.is_deleted = 0  GROUP BY customer_id_fk ) 
			                               SQTC ON (SQTC.customer_id_fk = C.customer_id)
			                               
			                   	         
			                   	LEFT JOIN (SELECT SUM(paid_amount) AS total_Paid, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Payment" GROUP BY customer_id_fk ) 
			                               SQPP ON (SQPP.customer_id_fk = C.customer_id)
			                               
			                               
			                            
			                   	LEFT JOIN (SELECT SUM(paid_amount) AS total_payment_discount, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Discount" GROUP BY customer_id_fk ) 
			                               SQPD ON (SQPD.customer_id_fk = C.customer_id)
			                               
			                    
			                    LEFT JOIN (SELECT SUM(paid_amount) AS total_payment_return, customer_id_fk
			                               FROM payments IP
			                               WHERE IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ="Return" GROUP BY customer_id_fk ) 
			                               SQPR ON (SQPR.customer_id_fk = C.customer_id)
			                            
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_s_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=1  AND I.is_deleted = 0 AND I.is_single=1 GROUP BY customer_id_fk ) 
			                               SQNS ON (SQNS.customer_id_fk = C.customer_id)
			                            
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_m_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=1  AND I.is_deleted = 0 AND I.is_single=0 GROUP BY customer_id_fk ) 
			                               SQNM ON (SQNM.customer_id_fk = C.customer_id)
			                               
								
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_raw_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.invoice_type=0  AND I.is_deleted = 0 AND I.is_single=0 GROUP BY customer_id_fk ) 
			                               SQNR ON (SQNR.customer_id_fk = C.customer_id)
			                               
								
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_inv, customer_id_fk
			                               FROM invoice I 
			                               WHERE I.invoice_status <3   AND I.is_deleted = 0 GROUP BY customer_id_fk ) 
			                               SQNI ON (SQNI.customer_id_fk = C.customer_id)
			                               
			                    LEFT JOIN (SELECT COUNT(*) AS No_of_withdraw, gived_to_id_fk
			                               FROM capital_withdraw CW 
			                               WHERE  CW.is_deleted = 0 GROUP BY gived_to_id_fk) 
			                               SQNW ON (SQNW.gived_to_id_fk = C.customer_id)


						WHERE C.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['customer_id']  			= $row['customer_id'];
					$result['customer_full_name']  		= $row['customer_full_name'];
					$result['customer_phone']  			= $row['customer_phone'];
					$result['customer_phone2']  		= $row['customer_phone2'];
					$result['customer_address']  		= $row['customer_address'];
					$result['No_of_inv'] 				= $row['No_of_inv'];
					$result['total_invoice_price'] 		= $row['total_invoice_price'];
					$result['total_Paid'] 				= $row['total_Paid'];
					$result['total_remained'] 			= $row['total_invoice_price'] -$row['total_Paid'] - $row['total_payment_discount'] +$row['total_payment_return'];
					$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['No_of_withdraw'] 			= $row['No_of_withdraw'];
					$result['total_payment_discount'] 	= $row['total_payment_discount'];
					$result['total_payment_return'] 	= $row['total_payment_return'];
					
					
					array_push($op['invoice'],$result);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id 		= $_POST['id'];
			$opt 		= $_POST['date_operation'];
			$d1 		= $_POST['date1'];
			$d2 		= $_POST['date2'];

			$cond_i = "";
			$cond_w = "";
			$cond_p = "";


			switch ($opt) {
				case 'e':
					$cond_i = " AND I.invoice_date = '". $d1."' ";
	 				$cond_w = " AND CW.withdraw_date = '". $d1."' ";
	 				$cond_p = " AND PY.paid_date = '". $d1."' ";
	 				break;

				case 'l':
					$cond_i = " AND I.invoice_date < '". $d1."' ";
	 				$cond_w = " AND CW.withdraw_date < '". $d1."' ";
	 				$cond_p = " AND PY.paid_date < '". $d1."' ";
	 				break;

				case 'g':
					$cond_i = " AND I.invoice_date > '". $d1."' ";
	 				$cond_w = " AND CW.withdraw_date > '". $d1."' ";
	 				$cond_p = " AND PY.paid_date > '". $d1."' ";
	 				break;

				case 'b':
					$cond_i = " AND I.invoice_date BETWEEN  '". $d1."' AND '".  $d2."'  ";
					$cond_w = " AND CW.withdraw_date  BETWEEN '". $d1."'  AND '".  $d2."' ";
					$cond_p = " AND PY.paid_date BETWEEN  '". $d1."' AND '".  $d2."'  ";
					break;
				
				
			}
		
			
			$res = $db->query('(SELECT
							        invoice_id AS id,
									customer_full_name,
									customer_phone,
	                      		 	customer_phone2,
	                      		 	customer_address,
						         	invoice_number as voucher_no,
						         	invoice_date AS date_,
						         
						         	"Invoice" AS transaction_,
						         	invoice_type AS transaction_type,
						         	is_single ,
									  		 

							        (invoice_total_price_actual) as Debits,
									(0) AS credits,
							        invoice_note AS note
														
							 	FROM  invoice I 
								LEFT JOIN customer C ON (I.customer_id_fk =C.customer_id)
							  	WHERE  I.is_deleted = 0 AND  I.invoice_status <3 AND   I.customer_id_fk='.$id.' '.$cond_i.' )
                                  
                                UNION ALL
								 
								(SELECT
							        capital_withdraw_id,
                              		customer_full_name,
                              		customer_phone,
                                    customer_phone2,
                                    customer_address,
							        capital_withdraw_id,
							        withdraw_date,
							        "Withdraw",
							        "Withdraw",
							        "Withdraw",
							        withdraw_amount,
							  		(0) AS Credits,
							        withdraw_note														
								 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_w.' )
                                 
                                 
                                UNION ALL
                                 
                                
                                (SELECT payment_id,
		                                  customer_full_name,
		                                  customer_phone,
		                                  customer_phone2,
		                                  customer_address,
		                                  payment_number,
		                                  paid_date,
		                                  payment_transaction,
		                                  invoice_type,
		                                  item_name,
		                                  (0) AS Debits,
		                                  (paid_amount) AS Credits,
		                                  payment_note
                                  
                                 FROM  payments PY 
								 LEFT JOIN customer C ON (PY.customer_id_fk =C.customer_id)
								 LEFT JOIN item_type IT ON (PY.item_type_id_fk =IT.item_type_id)
								 WHERE  PY.is_returned=0 AND PY.is_deleted =0 AND (PY.payment_transaction = "Payment" OR PY.payment_transaction = "Discount") AND   PY.customer_id_fk='.$id.'  '.$cond_p.')


								UNION ALL

								
								(SELECT payment_id,
		                                  customer_full_name,
		                                  customer_phone,
		                                  customer_phone2,
		                                  customer_address,
		                                  payment_number,
		                                  paid_date,
		                                  payment_transaction,
		                                  invoice_type,
		                                  item_name,
		                                  (paid_amount) AS Debits,
		                                  (0) AS Credits,
		                                  payment_note
                                  
                                 FROM  payments PY 
								 LEFT JOIN customer C ON (PY.customer_id_fk =C.customer_id)
								 LEFT JOIN item_type IT ON (PY.item_type_id_fk =IT.item_type_id)
								 WHERE  PY.is_returned=0 AND PY.is_deleted =0 AND PY.payment_transaction = "Return" AND   PY.customer_id_fk='.$id.'  '.$cond_p.')

                                 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['customer_full_name']  	= $row['customer_full_name'];
					$result['date_']  				= date('Y-m-d',strtotime($row['date_'])) ;
					$result['customer_phone']  		= $row['customer_phone'];
					$result['customer_phone2']  	= $row['customer_phone2'];
					$result['customer_address']  	= $row['customer_address'];
					$result['voucher_no'] 			= $row['voucher_no'];
					$result['transaction_'] 		= $row['transaction_'];
					$result['Debits'] 				= $row['Debits'];
					$result['credits'] 				= $row['credits'];
					$result['note'] 				= $row['note'];
					$result['transaction_type'] 	= $row['transaction_type'];
					$result['is_single'] 			= $row['is_single'];
					
					
					array_push($op['invoice'],$result);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$id 		= $_POST['id'];
			$inv_type 	= $_POST['typ'];

			$cond 		= '';
			$cond_bill 	= '';
			
			if($inv_type == 'raw'){

				$cond 		=  ' AND I.invoice_type=0  AND I.is_single=0 ';
				$cond_bill 	=  ' AND IP.invoice_type="Raw" ';

			}elseif($inv_type == 'm'){
				$cond =  ' AND I.invoice_type=1  AND I.is_single=0 ';
				$cond_bill 	=  ' AND IP.invoice_type="Plural" ';

			}elseif($inv_type == 's'){
				$cond =  ' AND I.invoice_type=1  AND I.is_single=1 ';
				$cond_bill 	=  ' AND IP.invoice_type="Single" ';

			}

			$cond_i = "";
			$cond_s = "";
			
			$cond_p = "";
			$cond_w = "";
			$cond_w1 = "";


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


				$opt 		= $_POST['date_operation'];
				$d1 		= $_POST['date1'];
				$d2 		= $_POST['date2'];

				

				switch ($opt) {
					case 'e':
						$cond_i = " AND I.invoice_date = '". $d1."' ";
		 				$cond_w = " AND CW.withdraw_date = '". $d1."' ";
		 				$cond_w1 = " AND CW1.withdraw_date = '". $d1."' ";
		 				$cond_p = " AND IP.paid_date = '". $d1."' ";
		 				$cond_s = " AND SI.sell_date = '". $d1."' ";
		 				break;

					case 'l':
						$cond_i = " AND I.invoice_date < '". $d1."' ";
		 				$cond_w = " AND CW.withdraw_date < '". $d1."' ";
		 				$cond_w1 = " AND CW1.withdraw_date < '". $d1."' ";
		 				$cond_p = " AND IP.paid_date < '". $d1."' ";
		 				$cond_s = " AND SI.sell_date < '". $d1."' ";
		 				break;

					case 'g':
						$cond_i = " AND I.invoice_date > '". $d1."' ";
		 				$cond_w = " AND CW.withdraw_date > '". $d1."' ";
		 				$cond_w1 = " AND CW1.withdraw_date > '". $d1."' ";
		 				$cond_p = " AND IP.paid_date > '". $d1."' ";
		 				$cond_s = " AND SI.sell_date > '". $d1."' ";
		 				break;

					case 'b':
						$cond_i = " AND I.invoice_date BETWEEN  '". $d1."' AND '".  $d2."'  ";
						$cond_w = " AND CW.withdraw_date  BETWEEN '". $d1."'  AND '".  $d2."' ";
						$cond_w1 = " AND CW1.withdraw_date  BETWEEN '". $d1."'  AND '".  $d2."' ";
						$cond_p = " AND IP.paid_date BETWEEN  '". $d1."' AND '".  $d2."'  ";
						$cond_s = " AND SI.sell_date BETWEEN  '". $d1."' AND '".  $d2."'  ";
						break;
					
					
				}

			}	
		

			$res = $db->query("SELECT invoice_id, 
									  invoice_number, 
									  invoice_date, 
									  invoice_status, 
									  invoice_usd_rate, 
									  invoice_currency,
									  invoice_type,
									  is_single,
									  invoice_total_price_actual, 
									  invoice_note, 
									  customer_id_fk, 
									  customer_full_name,
									  customer_email,
									  customer_phone,
									  customer_address, 
																
								    

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

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

								    (SELECT sum(paid_amount) FROM payments IP 
								    	
								    	WHERE I.customer_id_fk = IP.customer_id_fk   AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction='Return'  $cond_bill  $cond_p
								    ) AS total_return,


								    

									(SELECT sum(actual_discount) FROM sell_item SI WHERE I.invoice_id = SI.invoice_id_fk AND SI.is_deleted =0  $cond_s
									) AS total_discount_invoice,

									(invoice_total_price_actual) as total_invoice_price



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

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

				$op  = array('invoice'=>array(),'details'=>array(),'account'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['invoice_id']  					= $row['invoice_id'];
					$result['invoice_number']  				= $row['invoice_number'];
					$result['invoice_date']  				= date('Y-m-d',strtotime($row['invoice_date'])) ;
					$result['invoice_status']  				= $row['invoice_status'];
					$result['invoice_usd_rate']  			= $row['invoice_usd_rate'];
					$result['invoice_currency']  			= $row['invoice_currency'];
					$result['invoice_total_price_actual'] 	= $row['total_invoice_price'];
					$result['invoice_note']  				= $row['invoice_note'];
					$result['customer_full_name']  			= $row['customer_full_name'];
					$result['customer_phone']  				= $row['customer_phone'];
					$result['customer_address']  			= $row['customer_address'];
					$result['total_paid']  					= $row['total_paid'];
					$result['total_return']  				= $row['total_return'];
					$result['total_discount']  				= $row['total_discount'];
					
					
					
					$result['invoice_type']  				= $row['invoice_type'];
					$result['is_single']  					= $row['is_single'];

					$result['total_withdraw_paid']  		= 0;
					$result['total_withdraw_remained']  	= 0;

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

				// now we should bring account statement for withdraw

				if($inv_type == ''){
					$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(withdraw_amount) FROM capital_withdraw CW1 WHERE  CW1.is_deleted = 0  AND CW1.gived_to_id_fk = CW.gived_to_id_fk  $cond_w1) 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  $cond_w");

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


						$result['invoice_id']  					= 0;
						$result['invoice_number']  				= $row['capital_withdraw_id'];
						$result['invoice_date']  				= date('Y-m-d',strtotime($row['withdraw_date'])) ;
						$result['invoice_status']  				= $row['withdraw_status'];
						$result['invoice_usd_rate']  			= $row['withdraw_usd_rate'];
						$result['invoice_currency']  			= $row['withdraw_currency'];
						$result['invoice_total_price_actual'] 	= $row['withdraw_amount'];
						$result['invoice_note']  				= $row['withdraw_note'];
						$result['customer_full_name']  			= $row['customer_full_name'];
						$result['customer_phone']  				= $row['customer_phone'];
						$result['customer_address']  			= $row['customer_address'];
						$result['total_discount']  				= 0;
						$result['total_paid']  					= 0;
						$result['total_withdraw_paid']  		= 0;
						$result['total_remained']  				= 0;
						$result['total_withdraw_remained']  	= $row['total_withdraw_price'] ;
						$result['invoice_type']  				= 'w';
						$result['is_single']  					= 'w';
							
						array_push($op['invoice'],$result);
								
						}		
						// echo json_encode($op);
						// exit;
					}
				}


				// bring back all customer accounts 


				$res = $db->query("SELECT customer_id,
									  
									
									(

				          			COALESCE((SELECT sum(invoice_total_price_actual) FROM invoice I 
							        WHERE  I.customer_id_fk = C.customer_id 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.gived_to_id_fk = C.customer_id ),0)
									
									
									) as total_invoice_price,



									(
										COALESCE((SELECT sum(paid_amount) FROM payments IP1 
       									
        								WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.customer_id_fk = C.customer_id AND IP1.payment_transaction ='Payment' ),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
        						
							



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

				while ($row = $res->fetch_assoc()) {
				   
					
					$result1['total_invoice_price_all'] = $row['total_invoice_price'];
					$result1['total_Paid_all']  		= $row['total_Paid'];
					$result1['total_payment_discount'] 	= $row['total_payment_discount'];
					$result1['total_payment_return']  	= $row['total_payment_return'];
					$result1['total_remained_all']  	= $row['total_invoice_price'] - $row['total_Paid'] - $row['total_payment_discount'] + $row['total_payment_return'];
					

					array_push($op['account'],$result1);
						
				}

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


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

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

			
			$cond_cwp = "";
			$cond_w = "";
			$cond_w1 = "";


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


				$opt 		= $_POST['date_operation'];
				$d1 		= $_POST['date1'];
				$d2 		= $_POST['date2'];

				

				switch ($opt) {
					case 'e':
						
		 				$cond_w = " AND CW.withdraw_date = '". $d1."' ";
		 				$cond_w1 = " AND CW1.withdraw_date = '". $d1."' ";
		 				$cond_cwp = " AND CWP.payment_withdraw_date = '". $d1."' ";
		 				
		 				break;

					case 'l':
						
		 				$cond_w = " AND CW.withdraw_date < '". $d1."' ";
		 				$cond_w1 = " AND CW1.withdraw_date < '". $d1."' ";
		 				$cond_cwp = " AND CWP.payment_withdraw_date < '". $d1."' ";
		 				
		 				break;

					case 'g':
						
		 				$cond_w = " AND CW.withdraw_date > '". $d1."' ";
		 				$cond_w1 = " AND CW1.withdraw_date > '". $d1."' ";
		 				$cond_cwp = " AND CWP.payment_withdraw_date > '". $d1."' ";
		 				
		 				break;

					case 'b':
						$cond_w = " AND CW.withdraw_date  BETWEEN '". $d1."'  AND '".  $d2."' ";
						$cond_w1 = " AND CW1.withdraw_date  BETWEEN '". $d1."'  AND '".  $d2."' ";
						$cond_cwp = " AND CWP.payment_withdraw_date BETWEEN  '". $d1."' AND '".  $d2."'  ";
						break;
					
					
				}

			}	


			$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   $cond_cwp) 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  $cond_w1 ) 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  $cond_w");

		
			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_one_product") {

			$productName = $_POST['p_val'];

			$res = $db->query("SELECT product_id,erbil_code,turkish_code FROM product P,  item_type IT  WHERE P.is_deleted = 0 AND P.item_type_id_fk = IT.item_type_id AND IT.is_have_purchase =0 AND P.erbil_code ='$productName' LIMIT 1");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['turkish_code'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$customer_id_fk 	= $_POST['customer_id_fk'];
			$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' ";
			}

			$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_paid1,

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

        							) 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,

																
									(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 payments IP1 WHERE				  IP1.customer_id_fk = I.customer_id_fk AND IP1.item_type_id_fk=S.item_type_id_fk AND IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.payment_transaction ='Payment' ) 
									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='$customer_id_fk'  AND I.is_deleted = 0 AND I.invoice_status <2
							 	
							  ");
			
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				$total_item_type_price 		=0;
				$total_item_type_paid	 	=0;

				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'];
	                  }
	                } 
				   	
					$total_item_type_price	= $total_item_type_price + $total_row_price;
					$total_item_type_paid 	= $total_item_type_paid + $row['total_paid_per_product'];
						
						
				}

				$total_item_type_remaind 	= $total_item_type_price - $total_item_type_paid;

				

				// we should add the withdraw also if he choose all 

				if($item_type_id_fk == '' || $item_type_id_fk == NULL){
					
					$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) {
						
						$total_item_type_price1 	=0;
						$total_item_type_paid1	 	=0;

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

							 
							$total_item_type_price1		= $row['total_amount'];
							$total_item_type_paid1 		= $row['total_paid'];
							$total_item_type_remaind1 	= $row['total_remained'];
								
								
						}


						$total_item_type_price  	= $total_item_type_price + $total_item_type_price1;
						$total_item_type_paid  		= $total_item_type_paid + $total_item_type_paid1;
						$total_item_type_remaind  	= $total_item_type_remaind + $total_item_type_remaind1;
						
					}

				}


				$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']=="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_pay_cust_id 	= '';
			$cond_pay_cust_typ 	= '';
			$cond_pay_inv_id 	= '';
			$cond_pay_date 		= '';
			$cond_inv_date 		= '';
			$with_cust_id 		= '';
			$cond_cw_date 		= '';
			$cond_cwp_date 		= '';
			$cond_cust_typ  	= '';
			$general_acc		= '';
			
			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'];
						$cond_pay_inv_id 	=  ' AND IP1.invoice_id_fk='.$_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'];
						$general_acc 	=  '  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'];
						$cond_pay_cust_id 	=  ' AND IP1.customer_id_fk='.$_POST['cust_id'];
						$general_acc 		= $general_acc . '  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.'"';		
						$cond_pay_date 	= ' AND IP1.paid_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.'"';	
						$cond_pay_date 	= ' AND IP1.paid_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.'"';	
						$cond_pay_date 	= ' AND IP1.paid_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.'"';
						$cond_pay_date 	= ' AND IP1.paid_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.'")';
						$cond_pay_date 	= ' AND year(IP1.paid_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.'")';	
						$cond_pay_date 	= ' AND  month(CWP1.paid_date) = month("'.$first_date.'") AND year(CWP1.paid_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_pay_date 	= ' AND week(IP1.paid_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 	= '';
						$cond_pay_date 	= '';
						break;	
				}
			}
			
			$cond 		= " AND I.invoice_status < 3 " . $cond_inv_id . " " . $cond_cust_id . " " . $cond_inv_date;
			
			$cond_pay 	=  $cond_pay_cust_id . " " . $cond_pay_inv_id . " " . $cond_pay_date . "   " .$cond_cust_typ;



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

			$res = $db->query("

								SELECT item_type_id,item_name,

											(SELECT sum(paid_amount) FROM payments IP1 
										       LEFT JOIN customer C ON (IP1.customer_id_fk = C.customer_id)
										   	WHERE IP1.is_returned=0 AND IP1.is_deleted =0   AND  IP1.item_type_id_fk = IT.item_type_id AND IP1.payment_transaction ='Payment' AND IP1.invoice_type='Single' $cond_pay
										   	) as total_Paid_curtain_single,

										   	(SELECT sum(paid_amount) FROM payments IP1 
										       LEFT JOIN customer C ON (IP1.customer_id_fk = C.customer_id)										             
										    WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.item_type_id_fk = IT.item_type_id AND IP1.payment_transaction ='Payment' AND IP1.invoice_type='Raw' $cond_pay 
										    ) as total_Paid_Raw,

										    (SELECT sum(paid_amount) FROM payments IP1 
										      	LEFT JOIN customer C ON (IP1.customer_id_fk = C.customer_id)									       
										    WHERE IP1.item_type_id_fk = IT.item_type_id AND IP1.is_deleted =0 AND IP1.payment_transaction ='Payment' AND IP1.invoice_type='Plural' $cond_pay
										    ) as total_Paid_curtain_plural,

										    (0) as total_other_Paid_Raw,


											(0) as total_other_Paid_S,

											(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=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(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(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(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(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(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(),'account'=>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,

										(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,

										(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)
										
										 ) 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);

						
				}



				
			}

			// add new thing to show all paid details because there is general payment not related to item_type or invoice_type so we should display it in new tab as general customer info.

			$res = $db->query("SELECT customer_id,
									  customer_full_name,
									  CONCAT(COALESCE(customer_phone,''),';', COALESCE(customer_phone2,''))	AS phones,  

									
									(

				          				COALESCE((SELECT sum(sell_item_detail_height * item_sell_price_per_meter) FROM sell_item_detail SID, sell_item S 
				          				LEFT JOIN invoice I ON (I.invoice_status <3  AND I.is_deleted = 0 )
								        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 AND I.customer_id_fk = C.customer_id),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 
				          				LEFT JOIN invoice I ON (I.invoice_status <3  AND I.is_deleted = 0 )
								        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 AND I.customer_id_fk = C.customer_id),0)
								    +
								   		COALESCE((SELECT sum(sell_item_detail_width * decorate_price_per_meter) FROM sell_item_detail SID, sell_item S 
				          				LEFT JOIN invoice I ON (I.invoice_status <3  AND I.is_deleted = 0 )
								        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 AND I.customer_id_fk = C.customer_id),0)

								    +
								    	COALESCE((SELECT sum(sell_item_quantity * item_sell_price_per_meter) FROM sell_item S  
										LEFT JOIN invoice I ON (I.invoice_status <3  AND I.is_deleted = 0 )
										WHERE I.invoice_id = S.invoice_id_fk AND  S.other_id_fk >0 AND S.is_deleted=0 AND I.customer_id_fk = C.customer_id),0)
									+

										COALESCE((SELECT sum(withdraw_amount) FROM capital_withdraw CW1 WHERE  CW1.is_deleted = 0  AND CW1.gived_to_id_fk = C.customer_id ),0)
									-
								 		COALESCE((SELECT sum(actual_discount) from sell_item 
						 					LEFT JOIN invoice I ON (I.invoice_status <3  AND I.is_deleted = 0 )
						 					where sell_item.invoice_id_fk = I.invoice_id AND sell_item.is_deleted=0 AND I.customer_id_fk = C.customer_id),0)
									
									) as total_invoice_price,



									(
										COALESCE((SELECT sum(paid_amount) FROM payments IP1 
       									
        								WHERE IP1.is_returned=0 AND IP1.is_deleted =0 AND IP1.customer_id_fk = C.customer_id AND IP1.payment_transaction ='Payment' ),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
        						
							



									FROM customer C 
									WHERE C.is_deleted=0  $general_acc");

				

				while ($row = $res->fetch_assoc()) {
				   
					
					$resultG['customer_full_name'] 		= $row['customer_full_name'];
					$resultG['total_invoice_price_all'] = $row['total_invoice_price'];
					$resultG['total_Paid_all']  		= $row['total_Paid'];
					$resultG['total_payment_discount'] 	= $row['total_payment_discount'];
					$resultG['total_payment_return']  	= $row['total_payment_return'];
					$resultG['total_remained_all']  	= $row['total_invoice_price'] - $row['total_Paid'] - $row['total_payment_discount'] + $row['total_payment_return'];
					

					array_push($op['account'],$resultG);
						
				}	

				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).uniqid();
			$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,
												group_no,
												created_by,
												last_action,
												last_action_by)
										VALUES( '$row_new_payment',
												'$paid_date',
												'".$_SESSION['USD_TO_IQD']."',
												'1',
												'$payment_note',
												'$id',
												'$rnd_no',
												'".$_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;
	}
?>
