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

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

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

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

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

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND Inv.customer_id_fk='.$_GET['id']:'';
			$cond1 = isset($_GET['ip'])? ' AND Inv.invoice_status='.$_GET['ip']:'';
			
			if(isset($_GET['pt']) && $_GET['pt'] ==0){ 
				// in term
				$cond1 = $cond1 . ' AND Inv.invoice_date BETWEEN DATE_SUB(CURDATE(), INTERVAL Inv.pay_term DAY) AND CURDATE() ';
			}elseif(isset($_GET['pt']) && $_GET['pt'] ==1){
				// out term
				  $cond1 = $cond1 . ' AND Inv.invoice_date NOT BETWEEN DATE_SUB(CURDATE(), INTERVAL Inv.pay_term DAY) AND CURDATE() ';
			}
			
			$table  =  '(
				(
					SELECT
						offer_id,
						offer_number,
						offer_date,
						offer_status,
						offer_usd_rate,
						offer_currency,
						offer_total_price_actual,
						offer_total_net_balance,
						offer_note,
						validity,
						discount,
						discount_type,
						Inv.actual_discount,
						offer_sequence_no,
						destination,
						customer_id_fk,
						pay_terms,
						request_for_quta_number,
						is_invoice,
						sum(offer_item_sell_price_per_unit * offer_sell_item_quantity) AS total_price,
						(sum(offer_item_sell_price_per_unit * offer_sell_item_quantity) - Inv.actual_discount) AS total_price_final,
											
						customer_full_name AS name,
						customer_email AS email,
						customer_phone AS phone
					 FROM
					 offer Inv
					 LEFT JOIN customer Cus ON (Inv.customer_id_fk=Cus.customer_id) 
					 ,offer_sell_item SI
				WHERE
					(SI.offer_id_fk = Inv.offer_id AND SI.is_deleted=0   AND Inv.is_deleted = 0  '.$cond.' '.$cond1.') GROUP BY SI.offer_id_fk
				)
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'offer_id';
			$columns = array(
		    	array( 'db' => 'offer_id', 'dt' => 0 ),
		    	array( 'db' => 'offer_number', 'dt' => 1 ),
		    	array( 'db' => 'offer_date', 'dt' => 2, 'formatter'=> function($d){
							return date('Y-m-d',strtotime($d));
					} ),
		    	array( 'db' => 'name', 'dt' => 3 ),
		    	array( 'db' => 'phone', 'dt' => 4 ),
		    	array( 'db' => 'total_price_final', 'dt' => 5 ),
				array( 'db' => 'validity', 'dt' => 6 ),
				array( 'db' => 'offer_status', 'dt' => 7 ),
				array( 'db' => 'is_invoice', 'dt' => 8 ),
				

			  	array( 'db' => 'offer_note', 'dt' => 9 ),
				array( 'db' => 'total_price', 'dt' => 10 ),
				array( 'db' => 'actual_discount', 'dt' => 11 ),
				array( 'db' => 'customer_id_fk', 'dt' => 12 ),
				
			);
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.php' );
			echo json_encode(
			    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '' )
			);
			exit;
		}


		if ($_POST['type']=="search") {
			$q = $_POST["q"];
			//$invid = $_POST["invid"];

			$res = $db->query( "(
					SELECT
						customer_id AS CID,
						customer_full_name AS name,
						customer_email AS email,
						customer_phone AS phone,
    					('0') AS type
					 FROM
					 customer
				WHERE
					(customer_full_name like '%$q%' OR customer_email like '%$q%' OR customer_phone like '%$q%' AND is_deleted = 0 )
				)
			LIMIT 0,15");
			$row=[];
			header('Content-Type: application/json');

			if ($res) {
				$i=0;
				while( $r = $res->fetch_assoc() ){
					$row[$i++] = array(
						"name"	 => $r['name'],
						"email"  => $r['email'],
						"phone"  => $r['phone'],
						"type"   => $r['type'],
						"cid"    => $r['CID']
					);
				}
				echo json_encode( ['status'=>true, 'error'=>null, 'data'=>["company"=>$row]]);
			}else{
				echo json_encode( ['status'=>false, 'error'=>null, 'data'=>["company"=>$row]]);
			}
			exit;
		}



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

			$id = $_POST['id'];


			$res = $db->query("SELECT 

										offer_id, 
										offer_number, 
										offer_date, 
										offer_status, 
										offer_usd_rate, 
										offer_currency,
										offer_total_price_actual, 
										offer_total_net_balance, 
										discount,
										discount_type, 
										I.actual_discount, 
										offer_note,
										offer_sequence_no,
										pay_terms, 
										destination,
										validity, 
										request_for_quta_number, 
										delivery_time, 
										term_and_conditions, 
										offer_transaction,
										is_invoice, 
										customer_id_fk,
										offer_sell_item_id,
										offer_sell_item_quantity, 
										offer_item_buy_price_per_unit, 
										offer_item_sell_price_per_unit, 
										offer_tax_per_unit, 
										offer_sell_item_barcode,
										offer_sell_item_notes,
										offer_sell_item_delivery_name, 
										SI.product_id_fk,
										offer_id_fk,
										product_serial_id_fk, 
										customer_full_name,
										customer_email,
										customer_phone,
										customer_address,									  
									  
									  	product_name,
									  	product_code,
									  	description_en,	
									  	serial_no,
									  	made_in,												
									  	(offer_item_sell_price_per_unit * offer_sell_item_quantity) AS row_price,	  
									(SELECT sum(offer_item_sell_price_per_unit * offer_sell_item_quantity) FROM offer_sell_item SI1 WHERE SI1.offer_id_fk = I.offer_id AND  SI1.is_deleted = 0) AS total_price

									
								  

										FROM offer I
										LEFT JOIN offer_sell_item SI ON (SI.offer_id_fk = I.offer_id AND SI.is_deleted=0)
										LEFT JOIN product Pr ON (SI.product_id_fk = Pr.product_id )
									    LEFT JOIN product_serials PS ON (SI.product_serial_id_fk = PS.product_serial_id )
					 	 				LEFT JOIN customer C ON (C.customer_id = I.customer_id_fk)

										WHERE I.offer_id='$id'  AND I.is_deleted = 0");
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {

					
				   
					$result['offer_id']  					= $row['offer_id'];
					$result['offer_number']  				= $row['offer_number'];
					$result['offer_date']  					= date('Y-m-d',strtotime($row['offer_date']));
					$result['offer_status']  				= $row['offer_status'];
					$result['offer_usd_rate']  				= $row['offer_usd_rate'];
					$result['offer_currency']  				= $row['offer_currency'];
					$result['offer_total_price_actual'] 	= $row['offer_total_price_actual'];
					$result['offer_total_net_balance']  	= $row['offer_total_net_balance'];
					$result['discount']  					= $row['discount'];
					$result['discount_type']  				= $row['discount_type'];
					$result['actual_discount']  			= $row['actual_discount'];
					$result['offer_note']  					= $row['offer_note'];
					$result['offer_sequence_no']  			= $row['offer_sequence_no'];
					$result['destination']  				= $row['destination'];
					$result['offer_number']  				= $row['offer_number'];
					$result['term_and_conditions']  		= $row['term_and_conditions'];
					// $result['offer_barcode']  				= $row['offer_barcode'];
					$result['customer_id_fk']  				= $row['customer_id_fk'];
					$result['offer_sell_item_id']  			= $row['offer_sell_item_id'];
					$result['offer_sell_item_quantity']  	= $row['offer_sell_item_quantity'];
					$result['offer_item_buy_price_per_unit']= $row['offer_item_buy_price_per_unit'];
					$result['offer_item_sell_price_per_unit']= $row['offer_item_sell_price_per_unit'];
					$result['offer_tax_per_unit']  			= $row['offer_tax_per_unit'];
					$result['offer_sell_item_barcode']  	= $row['offer_sell_item_barcode'];
					$result['offer_sell_item_notes']  		= $row['offer_sell_item_notes'];
					$result['offer_sell_item_delivery_name']= $row['offer_sell_item_delivery_name'];
					$result['product_id_fk']  				= $row['product_id_fk'];
					$result['product_serial_id_fk']  		= $row['product_serial_id_fk'];
					$result['customer_full_name']  			= $row['customer_full_name'];
					$result['customer_phone']  				= $row['customer_phone'];
					$result['customer_address']  			= $row['customer_address'];
					$result['customer_email']  				= $row['customer_email'];
					$result['product_name']  				= $row['product_name'];
					$result['request_for_quta_number']  	= $row['request_for_quta_number'];
					
					
					$result['validity']  					= $row['validity'];
					$result['product_code']  				= $row['product_code'];
					$result['made_in']  					= $row['made_in'];
					$result['delivery_time']  				= $row['delivery_time'];
					$result['pay_terms']  					= $row['pay_terms'];
					$result['description_en']  				= $row['description_en'];
					$result['row_price']  					= $row['row_price'];
					$result['total_price']  				= $row['total_price'];
					$result['serial_no']  					= $row['serial_no'];
					$result['total_remained']  				= $row['total_price']-$row['actual_discount'] ;
					$result['is_invoice']  					= $row['is_invoice'];
					
						array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id = $_POST['id'];


			$res = $db->query("SELECT invoice_id, 
																invoice_number, 
																invoice_date, 
																invoice_status, 
															  invoice_usd_rate, 
															  invoice_currency,
															  invoice_total_price_actual, 
															  invoice_note, 
															  sell_item_quantity, 
															  I.customer_id_fk, 
															  sell_discount, 
															  sell_discount_type, 
															  actual_discount,
															  item_sell_price_per_meter,
															  decorate_price_per_meter, 
															  is_paid,
															  sell_item_notes, 
															  S.item_type_id_fk, 
															  other_id_fk, 
															  S.product_id_fk, 
															  sell_item_id,
															  customer_full_name,
															  customer_email,
															  customer_phone,
															  customer_address,
															  invoice_payment_id,
																pay_usd_rate,
																pay_currency,
																paid_amount,
																paid_date,
																next_payment_date,
																next_payment_amount,
																payment_note, 
																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(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)
															    +
															    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(actual_discount) FROM sell_item SI WHERE I.invoice_id = SI.invoice_id_fk AND SI.is_deleted =0) AS total_discount,
																(SELECT sum(sell_item_detail_height) FROM sell_item_detail SID WHERE SID.invoice_id_fk = '$id' AND SID.sell_item_id_fk=S.sell_item_id AND part_status=0 AND SID.is_deleted = 0) AS total_length

												FROM invoice I
													LEFT JOIN invoice_payment IPP ON (I.invoice_id = IPP.invoice_id_fk AND IPP.is_returned=0 AND IPP.is_deleted =0)
											 		LEFT JOIN sell_item S ON (S.sell_item_id = IPP.sell_item_id_fk AND S.is_deleted=0)
											 		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.invoice_id='$id'  AND I.is_deleted = 0");
			if ($res) {
				//$row = $res->fetch_all();
				//echo json_encode($row);

				$op  = array('invoice'=>array(),'details'=>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['sell_item_quantity']  				= $row['sell_item_quantity'];
					$result['sell_discount']  						= $row['sell_discount'];
					$result['sell_discount_type']  				= $row['sell_discount_type'];
					$result['actual_discount']  					= $row['actual_discount'];
					$result['item_sell_price_per_meter']  = $row['item_sell_price_per_meter'];
					$result['decorate_price_per_meter']  	= $row['decorate_price_per_meter'];
					$result['is_paid']  									= $row['is_paid'];
					$result['sell_item_notes']  					= $row['sell_item_notes'];
					$result['product_name']  							= $row['product_name'];
					$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['product_id_fk']  						= $row['product_id_fk'];
					$result['other_id_fk']  							= $row['other_id_fk'];
					$result['sell_item_id']  							= $row['sell_item_id'];
					$result['total_discount']  						= $row['total_discount'];
					$result['total_remained']  						= $row['total_invoice_price'] - $row['total_paid'];
					$result['total_length']  							= $row['total_length'];
					$result['invoice_payment_id']  				= $row['invoice_payment_id'];
					$result['pay_usd_rate']  							= $row['pay_usd_rate'];
					$result['pay_currency']  							= $row['pay_currency'];
					$result['paid_amount']  							= $row['paid_amount'];
					$result['paid_date']  								= date('Y-m-d',strtotime($row['paid_date']));
					$result['next_payment_date']  				= $row['next_payment_date'];
					$result['next_payment_amount']  			= $row['next_payment_amount'];
					$result['payment_note']  							= $row['payment_note'];
					
						array_push($op['invoice'],$result);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id = $_POST['id'];

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

									  (
				          			  COALESCE((SELECT sum(item_sell_price_per_unit * sell_item_quantity) 			 
				          						FROM sell_item S 
				          							 LEFT JOIN invoice I ON (I.invoice_status <3  AND I.is_deleted = 0 )
								        			WHERE  S.invoice_id_fk = I.invoice_id 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.staff_customer=0  AND CW1.gived_to_id_fk = C.customer_id ),0)
								        -

								        COALESCE((SELECT sum(actual_discount) from invoice I WHERE I.invoice_status <3  AND I.is_deleted = 0  AND I.customer_id_fk = C.customer_id),0)

								    ) AS total_invoices_price,

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

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

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

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

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

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


		if ($_POST['type']=="PDF" || $_POST['type']=="Print") {

				$invoice_html = $_POST['html'];
				$inv_no		  	= $_POST['inv_no'];
				$pay    	  	= $_POST['pay'];

				if($pay != NULL || $pay !=''){ // print Payments
						$mpdf = new mPDF('utf-8','A4',0,'sans-serif',15,15,12,12, 0, 0, 'P');
						$mpdf->autoScriptToLang = true;
						$mpdf->autoLangToFont = true;
						$mpdf->allow_charset_conversion = false;

						$mpdf->WriteHTML($invoice_html);
						$inv_dir = 'invoices/'.$inv_no;
						if(! file_exists('../'.$inv_dir)){
							mkdir('../'.$inv_dir);
						}
						$invoice_url = $inv_dir.'/'.$inv_no.'_Payments.pdf';
						$invoice_real_url = '../'.$invoice_url;
						$mpdf->Output($invoice_real_url,'F');
				}else{
						$mpdf = new mPDF('utf-8','A4',0,'sans-serif',15,15,12,12, 0, 0, 'P');
						$mpdf->WriteHTML($invoice_html);
						$inv_dir = 'invoices/'.$inv_no;
						if(! file_exists('../'.$inv_dir)){
							mkdir('../'.$inv_dir);
						}
						$invoice_url = $inv_dir.'/'.$inv_no.'.pdf';
						$invoice_real_url = '../'.$invoice_url;
						$mpdf->Output($invoice_real_url,'F');
				}



					$out['is_success'] = true;
					$out['data'] 	   = $invoice_url;
				echo json_encode($out);

		}

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

			$id 		= $_POST['cust_id'];
			$total_paid = $_POST['row_payments'];
			$notes 		= $_POST['notes'];

			$lastaction = "Add New Payment";
			$invoice_currency					= 1; //USD
			if(!isset($_POST['paid_date'])){
				$reg_date = date("Y-m-d h:i:s", time());
			}else{
				$reg_date = $_POST['paid_date'];
			}
			
			$dd 	  = date("y", time());
			
			$next_payment_date ='';
			$next_payment_amount = '';



			$successfully = false;
			for ($i=0;$i<count($total_paid);$i++){

				if($total_paid[$i] > 0){

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

						
						$resP = $db->query("SELECT pay_sequence_no FROM payments ORDER BY payment_id DESC LIMIT 1");
						$rowP = $resP->fetch_assoc();
						$pay_sequence_no 	= $rowP['pay_sequence_no'] +1;

				
						$payment_number = "PAY".$dd.($pay_sequence_no);
						$payment_transaction = 'Payment';
						$payment_note = $notes[$i];

						$sql_p ="INSERT INTO payments(payment_number,
				 									  pay_usd_rate,
				 									  pay_currency,
				 									  paid_amount,
				 									  paid_date,
				 									  payment_note,
				 									  payment_transaction,
				 									  pay_sequence_no,
				 									  invoice_id_fk,
				 									  customer_id_fk,
				 									  created_by,
				 									  last_action,
				 									  last_action_by)
				 							   VALUES('$payment_number',
				 							   		  '".$_SESSION['USD_TO_IQD']."',
				 							    	  '$invoice_currency',
				 							    	  '$total_paid[$i]',
				 							    	  '$reg_date',
				 							    	  '$payment_note',
				 							    	  '$payment_transaction',
				 							    	  '$pay_sequence_no',
				 							    	  '',
				 							    	  '$id',
				 							    	  '".$_SESSION['user_id']."',
				 							    	  '$lastaction',
				 							    	  '".$_SESSION['user_id']."')";
						$res_P = $db->query($sql_p);
						if (!$res_P){
							$db->rollback();
							$op['is_success'] = false;
							$op['data'] 	  = "هناك خطأ : لم يتم اضافة الدفوعات الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
							echo json_encode($op);
							exit;
						}else{
							$successfully = true;
						}
				} // if total_paid >0

			}  // for i

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


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

			$id 								= $_POST['inv_id'];
			$delivery_status 					= $_POST['delivery_status'];
			

			$lastaction 						= "Update offer type";
			
			$reg_date 							= date("Y-m-d h:i:s", time());

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

			if($delivery_status == 1){ // it mean convert it to invoice and we should make transactions

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

				$res = $db->query("SELECT invoice_sequence_no FROM invoice ORDER BY invoice_id DESC LIMIT 1");
				$row = $res->fetch_assoc();
				$invoice_sequence_no 	= $row['invoice_sequence_no'] +1;

				$dd = date("y", time());
				$invoice_number = "V".$dd.($invoice_sequence_no);
				// extract array VALUES

				$invoice_transaction = "Invoice";
				
				$invoice_date = date("Y-m-d h:i:s", time());

				$sql ="INSERT INTO invoice (
										invoice_usd_rate, 
										invoice_currency, 
										invoice_total_price_actual, 
										invoice_total_net_balance, 
										discount, 
										discount_type, 
										actual_discount, 
										invoice_note, 
										pay_terms, 
										delivery_time, 
										term_and_conditions, 
										offer_number, 
										request_for_quta_number, 
										date_of_offer, 
										 
										customer_id_fk, 
										created_by, 
										last_action, 
										last_action_by)

								SELECT  offer_usd_rate,
										offer_currency,
										offer_total_price_actual,
										offer_total_net_balance,
										discount,
										discount_type,
										actual_discount,
										offer_note,
										pay_terms,
										delivery_time,
										term_and_conditions,
										offer_number,
										request_for_quta_number,
										offer_date,
										customer_id_fk,
										created_by, 
										last_action, 
										last_action_by

								FROM offer WHERE offer_id ='$id'";
			
				$res = $db->query($sql);

				if ($res) {

					$invoice_inserted_id = $db->insert_id;

					$chek_insertion = true;



					

					// now we should update invoice table to add invoice_number and squence and etc

					$sql1 ="UPDATE invoice SET invoice_date='$reg_date', invoice_number = '$invoice_number', invoice_sequence_no = '$invoice_sequence_no', invoice_transaction = '$invoice_transaction', last_action='$lastaction', last_action_by='".$_SESSION['user_id']."'  WHERE invoice_id = '$invoice_inserted_id' ";
					
					$res1 = $db->query($sql1);
					if (!$res1) {
						$db->rollback();
						$op['is_success'] = false;
						$op['data'] 	  = "حصل خطأ : لم يتم تحديث حالة التسليم بنجاح ";
						echo json_encode($op);
						exit;
					}
					// insert into sell items the sold products
					$lastaction = "Add New Sell Product";

					$sql2 ="INSERT INTO sell_item (	sell_item_quantity, 
													item_buy_price_per_unit,
													item_sell_price_per_unit,
													tax_per_unit,
													sell_item_barcode,
													sell_date,
													sell_item_notes,
													sell_item_delivery_name,
													product_serial_id_fk,
													product_id_fk,
													invoice_id_fk,
													created_by,
													last_action,
													last_action_by)
											SELECT  offer_sell_item_quantity,
													offer_item_buy_price_per_unit,
													offer_item_sell_price_per_unit,
													offer_tax_per_unit,
													offer_sell_item_barcode,
													offer_sell_date,
													offer_sell_item_notes,
													offer_sell_item_delivery_name,
													product_serial_id_fk,
													product_id_fk,
													'$invoice_inserted_id' AS inv_id,
													created_by, 
													last_action, 
													last_action_by

											FROM offer_sell_item WHERE offer_id_fk ='$id'";


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

					if ($res2) {
						
						$last_inserted_sell_item_id = $db->insert_id;

						// we should store this qty in stock also

						// check if it booking in stock or not

						$resB = $db->query("SELECT offer_status FROM offer WHERE offer_id='$id'");
						$rowB = $resB->fetch_assoc();
						$offer_status 	= $rowB['offer_status'];

						if($offer_status == 1){ // it mean it have book and we should just change the transaction from Offer to Invoice
							$trans__ = "Offer";
						}else{ // it mean we should 
							$trans__ = "Fake_Offer";

						}

						$sqlS = "UPDATE product_stock SET  stock_transaction='Invoice',  last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id_fk = $id AND stock_transaction='$trans__'";

						
						// $sqlS ="INSERT INTO product_stock (recieved_quantity,
						// 							  stock_transaction,
						// 							  transaction_date,
						// 							  invoice_id_fk,
						// 							  sell_item_fk,
						// 							  product_id_fk,
						// 							  product_serial_id_fk,
						// 							  stock_id_fk,
						// 							  created_by,
						// 							  last_action,
						// 							  last_action_by)

						// 					SELECT  sell_item_quantity,
						// 							'Invoice' AS trans,
						// 							'$reg_date' AS date_,
						// 							'$invoice_inserted_id' AS inv_id,
						// 							sell_item_id,
						// 							product_id_fk,
						// 							product_serial_id_fk,
						// 							'1' as stock_id,
						// 							created_by, 
						// 							last_action, 
						// 							last_action_by

						// 					FROM sell_item WHERE invoice_id_fk ='$invoice_inserted_id'
						// 					   ";

						$res_S = $db->query($sqlS);
						// now we should update offer status and free stocks from offer
						if($res_S){

							$lastaction = "Change Offer to Invoice";

							$res3 = $db->query("UPDATE offer SET is_invoice=1, offer_status = 0 ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE offer_id=$id");

							if ($res3){

								// $update_qry2 = "UPDATE product_stock SET  is_deleted = 1, deleted_at='$reg_date', last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id_fk = $id AND stock_transaction='Offer'";

								// $res2 = $db->query($update_qry2);
								$db->commit();
									$op['is_success'] = true;
									$op['data'] 	  = "تمت عملية التحديث بنجاح";
									echo json_encode($op);
									exit;

								// if ($res2) {
								// 	$db->commit();
								// 	$op['is_success'] = true;
								// 	$op['data'] 	  = "تمت عملية التحديث بنجاح";
								// 	echo json_encode($op);
								// 	exit;
								// }else{
								// 	$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;
							}
							
						}else{

							$chek_insertion = false;

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


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

						$chek_insertion = false;
						$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;
				}
				

			}else{

				$sql ="UPDATE offer SET is_invoice = '$delivery_status', last_action='$lastaction', last_action_by='".$_SESSION['user_id']."'  WHERE offer_id = '$id' ";
					
				$res = $db->query($sql);

				if ($res){
					$db->commit();
					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية التحديث بنجاح";
					echo json_encode($op);
					exit;
				}else{
					$db->rollback();
					$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ : لم يتم تحديث حالة التسليم بنجاح ";
					echo json_encode($op);
					exit;
				}

			}
			

			
		}

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

			$id 								= $_POST['inv_id'];
			
			$lastaction 						= "Free Booking";
			
			$reg_date 							= date("Y-m-d h:i:s", time());

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

			
			$res = $db->query("UPDATE offer SET offer_status = 0 ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE offer_id=$id");

			if ($res){

				$update_qry2 = "UPDATE product_stock SET  is_deleted = 1, deleted_at='$reg_date', last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id_fk = $id AND stock_transaction='Offer'";

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

				if ($res2) {
					$db->commit();
					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية التحديث بنجاح";
					echo json_encode($op);
					exit;
				}else{
					$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;
			}
			
			

			
		}

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

			$id 										= $_POST['inv_id'];
			$total_paid 						= $_POST['paid'];
			$sell_ids 							= $_POST['sell_ids'];
			$notes 									= $_POST['notes'];
			$payment_id 						= $_POST['payment_id'];


			$lastaction 						= "Update Payment";
			$invoice_currency				= 1; //USD
			$reg_date 							= date("Y-m-d h:i:s", time());
			
			$next_payment_date 			=	'';
			$next_payment_amount 		= '';

			$res = $db->query("SELECT customer_id_fk FROM invoice WHERE invoice_id = $id");
			if ($res) {
				$row = $res->fetch_assoc();
				$customer_id_fk = $row['customer_id_fk'];
				
			}

			if($total_paid > 0){

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

					$sql ="UPDATE invoice_payment SET paid_amount = '$total_paid', payment_note='$notes', customer_id_fk='$customer_id_fk',
					 created_by='".$_SESSION['user_id']."', last_action='$lastaction', last_action_by='".$_SESSION['user_id']."'  WHERE invoice_payment_id = '$payment_id' ";
					
					$res = $db->query($sql);

					if ($res){

										// 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 = '$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 * 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)
																					    	+
																					    	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_ids')
											 		
											 									WHERE I.invoice_id='$id'  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'];
										
										// compute total product price

										$total_product_price = 0;

										if($total_length > 0 && $total_length !=NULL){
											$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 ){
													$db->rollback();
													$op['is_success'] = false;
													$op['data'] 	  = "المبلغ المدفوع لهذه المادو اصبح اكبر من سعر المادة الكلي الرجاء التاكد من القيمة واعادة الادخال";
													echo json_encode($op);
													exit;

										}elseif($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;

										}

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

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

												// update invoice status

												$lastaction = "Update Invoice status after Adding payments";
												if($total_payments > $net_balance ){
													$db->rollback();
													$op['is_success'] = false;
													$op['data'] 	  = "المبلغ الكلي المدفوع لهذا الوصل اصبح اكبر من السعر  الكلي للوصل الرجاء التاكد من القيمة واعادة الادخال";
													echo json_encode($op);
													exit;

												}elseif($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 = $id";

												}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 = $id";
												}

												$res3 = $db->query($update_qry1);
												if ($res3) {

													$db->commit();
													$op['is_success'] = true;
													$op['data'] 	  = "تمت عملية التحديث بنجاح";
													echo json_encode($op);
													exit;
													
												}else{
													$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;
										}



					}else{
						// $op['data'] 	  =$db->error;

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

			}else{

				$op['is_success'] = false;
				$op['data'] 	  = "الرجاء قم بادخال قيمة مبلغ اكبر من 0";
				echo json_encode($op);
				exit;
			}
		}


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

			$id 										= $_POST['inv_id'];
			$total_paid 						= $_POST['paid'];
			$sell_ids 							= $_POST['sell_ids'];
			$notes 									= $_POST['notes'];
			$payment_id 						= $_POST['payment_id'];


			$lastaction 						= "Delete Payment";
			$invoice_currency				= 1; //USD
			$reg_date 							= date("Y-m-d h:i:s", time());
			
			$next_payment_date 			=	'';
			$next_payment_amount 		= '';



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

					$sql ="UPDATE invoice_payment SET is_deleted = '1', deleted_at = '$reg_date',
					 created_by='".$_SESSION['user_id']."', last_action='$lastaction', last_action_by='".$_SESSION['user_id']."'  WHERE invoice_payment_id = '$payment_id' ";
					
					$res = $db->query($sql);

					if ($res){

										// 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 = '$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 * 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)
																					    	+
																					    	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_ids')
											 		
											 									WHERE I.invoice_id='$id'  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'];
										
										// compute total product price

										$total_product_price = 0;

										if($total_length > 0 && $total_length !=NULL){
											$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 ){
													$db->rollback();
													$op['is_success'] = false;
													$op['data'] 	  = "المبلغ المدفوع لهذه المادو اصبح اكبر من سعر المادة الكلي الرجاء التاكد من القيمة واعادة الادخال";
													echo json_encode($op);
													exit;

										}elseif($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;

										}

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

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

												// update invoice status

												$lastaction = "Update Invoice status after Adding payments";
												if($total_payments > $net_balance ){
													$db->rollback();
													$op['is_success'] = false;
													$op['data'] 	  = "المبلغ الكلي المدفوع لهذا الوصل اصبح اكبر من السعر  الكلي للوصل الرجاء التاكد من القيمة واعادة الادخال";
													echo json_encode($op);
													exit;

												}elseif($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 = $id";

												}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 = $id";
												}else{
													$is_paid = 0; // Not paid
													$update_qry1 = "UPDATE invoice SET  invoice_status='$is_paid',last_action='$lastaction',
													last_action_by='".$_SESSION['user_id']."' WHERE invoice_id = $id";
												}

												$res3 = $db->query($update_qry1);
												if ($res3) {

													$db->commit();
													$op['is_success'] = true;
													$op['data'] 	  = "تمت عملية الحذف بنجاح";
													echo json_encode($op);
													exit;
													
												}else{
													$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;
										}



					}else{
						// $op['data'] 	  =$db->error;

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

			
		}


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

			$id = $_POST['id'];
					
			$res = $db->query("SELECT * FROM invoice_pay  WHERE invoice_id_fk ='$id' AND is_returned=0  AND is_deleted = 0");
								
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array('is_success'=>false, 'payments' => array(), 'sell'=>array());
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['invoice_pay_id'];
						$result[1]  = $row['pay_usd_rate'];
						$result[2]  = $row['pay_currency'];
						$result[3]  = $row['paid_amount'];
						$result[4]  = $row['paid_date'];
						$result[5]  = $row['is_returned'];
						$result[6]  = $row['returned_date'];
						$result[7]  = $row['invoice_id_fk'];
						array_push($op['payments'],$result);
				}

			}else{
				echo 0;
				exit;
			}

			$res = $db->query("SELECT S.* ,P.product
				FROM sell_item S, product P WHERE S.product_id_fk=P.product_id AND S.invoice_id_fk ='$id'  AND S.is_deleted = 0");
			if ($res) {
				
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['sell_item_id'];
						$result[1]  = $row['sell_quantity'];
						$result[2]  = $row['sell_discount'];
						$result[3]  = $row['sell_unit_price'];
						$result[4]  = $row['sell_date'];
						$result[5]  = $row['product_id_fk'];
						$result[6]  = $row['invoice_id_fk'];
						$result[7]  = $row['product'];
						$result[8]  = $row['sell_avg_price'];
						
						array_push($op['sell'],$result);
				}
				
			}else{
				echo 0;
				exit;
			}

			$op['is_success'] = true;

			echo json_encode($op);

			exit();
					
		}



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

			$p_id = $_POST['p_id'];

			// we should show item that can be sell 
			// 0 : avaialbe in store no damge
			// 2 : avaible in production no damge
			// 3 : in production used not finished
			// 5 : partially sold
			// 8 : avaiable in store with damage
			// 9 : used in production + partially sold
			// 11: available in production with damage
			// And we should also send the remianed length of each roll 

			$res = $db->query("SELECT purchase_item_detail_id, item_length,stock_id_fk, stock_name,item_status,
													(	COALESCE(item_length,0) - 
														(COALESCE(damage_length,0) + 
														COALESCE(used_length,0) + 	
														COALESCE((select sum(sell_item_detail_height) FROM sell_item_detail SID WHERE SID.purchase_item_detail_id_fk = PID.purchase_item_detail_id AND SID.part_status=0 AND SID.is_deleted=0),0) + 
														COALESCE((select sum(damage_length) FROM sell_item_detail SID WHERE SID.purchase_item_detail_id_fk = PID.purchase_item_detail_id AND SID.part_status=0 AND SID.is_deleted=0),0))

													) as remained_length
													FROM purchase_item_detail PID
													LEFT JOIN stock S ON (PID.stock_id_fk = S.stock_id)
													WHERE (PID.item_status= 0 || PID.item_status= 2 || PID.item_status= 3 || PID.item_status= 5 || PID.item_status= 8 || PID.item_status= 9 || PID.item_status= 11  ) 
													AND PID.is_deleted=0 AND PID.product_id_fk = $p_id");
			if ($res) {
				
				$op  = array('data'=>array(),'stocks'=>array());
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['purchase_item_detail_id'];
						$result[1]  = $row['item_length'];
						$result[2]  = $row['stock_name'];
						$result[3]  = $row['stock_id_fk'];
						$result[4]  = $row['item_status'];
						$result[5]  = $row['remained_length'];
						
						
						array_push($op['data'],$result);
				}
				$res1 = $db->query("SELECT stock_id, stock_name, stock_type,
														(SELECT COUNT(*) FROM purchase_item_detail P WHERE P.stock_id_fk = S.stock_id AND P.is_deleted=0 AND (P.item_status= 0 || P.item_status= 2 || P.item_status= 3 || P.item_status= 5 || P.item_status= 8 || P.item_status= 9 || P.item_status= 11  ) AND P.product_id_fk = $p_id) AS roll_no
														FROM stock S
														WHERE  S.is_deleted = 0");
				
				while ($row1 = $res1->fetch_assoc()) {
				   
						$result1[0]  = $row1['stock_id'];
						$result1[1]  = $row1['stock_name'];
						$result1[2]  = $row1['stock_type'];
						$result1[3]  = $row1['roll_no'];
						array_push($op['stocks'],$result1);
				}

				echo json_encode($op);

				exit;
			}else{
				echo 0;
				exit;
			}
		}

		

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



			$id 										= $_POST['obj_id'];

			$quantity								=$_POST["quantity"];
			$discount								=$_POST["discount"];
			$product_id							=$_POST["product_id"];
			$unit_price							=$_POST["unit_price"];
			$product_avg_price			=$_POST["product_avg_price"];
			$customer_id						=addslashes($_POST["customer_id"]);
			$pay_term 							=addslashes($_POST["pay_term"]);
			$customer_type					=addslashes($_POST["customer_type"]);
			$total_invoice			  	=addslashes($_POST["total_invoice"]);
			$net_balance				  	=addslashes($_POST["net_balance"]);
			$total_paid	  					=addslashes($_POST["total_paid"]);
			$is_offer								=addslashes($_POST["is_offer"]);

			if($is_offer == 1 AND $total_paid > 0){
				echo "This is an offer it can't contain Paid Price!!";
				echo 0;
				exit;
			}

			if($net_balance ==0 OR $net_balance =='' OR $net_balance ==NULL){
				echo "Please Enter Net Balance Price!!";
				echo 0;
				exit;
			}
			// check invoice status is it complete or partially or not paid

			$is_paid = 0; // not paid
			if($total_paid >= $net_balance AND $is_offer == 0){
				$is_paid = 2; // complete paid
				$pay_term = 0;
			}elseif($total_paid < $net_balance AND $total_paid >0 AND $is_offer == 0){
				$is_paid = 1; // partially paid
			}elseif($is_offer == 1){
				$is_paid = 4; // Offer
			}

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

			
			// extract array VALUES


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

			$sql = "UPDATE invoice SET  is_paid = '$is_paid', total_price_actual='$total_invoice',total_net_balance='$net_balance', pay_term ='$pay_term', customer_id_fk ='$customer_id',
										customer_type='$customer_type',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id = $id";

			$res = $db->query($sql);
				if ($res) {
						$last_inserted_id = $id;

						// insert into payment table the paid price
						/*$lastaction = "Add New Payment";
						if($total_paid > 0){
							$sql ="INSERT INTO invoice_pay (paid_amount, pay_usd_rate, pay_currency, invoice_id_fk, created_by, last_action, last_action_by)
										 VALUES('$total_paid','','','$last_inserted_id','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";
							$res = $db->query($sql);
							if (!$res){
								$db->rollback();
								echo $db->error;
								echo 0;
								exit;
							}
						}*/

						// delete all sold items for this invoice then we add the new sells
						$lastaction = "Delete items by updated invoice";

						$sql = "UPDATE sell_item SET  is_deleted = 1, deleted_at='$reg_date', last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id_fk = $id";

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

						if (!$res){
								$db->rollback();
								echo $db->error;
								echo 0;
								exit;
						}


						// insert into sell items the sold products
						$lastaction = "Add New Sell Product";
						$check_all_inserted = false;
						for ($i=0;$i<count($quantity);$i++){

							$sql ="INSERT INTO sell_item (sell_quantity, sell_discount, sell_unit_price, product_id_fk, invoice_id_fk,sell_avg_price, created_by, last_action, last_action_by)
										 VALUES('$quantity[$i]','$discount[$i]','$unit_price[$i]','$product_id[$i]','$last_inserted_id','$product_avg_price[$i]','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";
							$res = $db->query($sql);
							if ($res) {
								$check_all_inserted = true;
							}else{
								$check_all_inserted = false;
								$db->rollback();
								echo $db->error;
								echo 0;
								exit;
							}

						} // for i

						if($check_all_inserted == true){
							$db->commit();
							echo 1;
							exit;
						}else{
							$db->rollback();
							echo $db->error;
							echo 0;
							exit;
						}
				}else{
					$db->rollback();
					echo $db->error;
					echo 0;
				}


		}


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

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

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


			$res = $db->query("SELECT offer_status FROM offer WHERE offer_id =$id");
			$row = $res->fetch_assoc();
			$offer_status 	= $row['offer_status'];


			$db->autocommit(FALSE); // to rollback update if update fail
			$res = $db->query("UPDATE offer SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE offer_id=$id");
			if ($res){

					// update Product table for sell price and avarage price

					$sql1 ="UPDATE offer_sell_item SET is_deleted = '1',
								 deleted_at='$reg_date', last_action='$lastaction', last_action_by='".$_SESSION['user_id']."'  WHERE offer_id_fk = $id";

					$res1 = $db->query($sql1);

					if ($res1) {
							
							if ($offer_status ==1) {

								$update_qry2 = "UPDATE product_stock SET  is_deleted = 1, deleted_at='$reg_date', last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE invoice_id_fk = $id AND stock_transaction='Offer'";

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

								if ($res2) {
									$db->commit();
									$op['is_success'] = true;
									$op['data'] 	  = "تمت عملية الحذف بنجاح";
									echo json_encode($op);
									exit;
								}else{
									$db->rollback();
									$op['is_success'] = false;
									$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
									echo json_encode($op);
									exit;
								}
							}else{
									$db->commit();
									$op['is_success'] = true;
									$op['data'] 	  = "تمت عملية الحذف بنجاح";
									echo json_encode($op);
									exit;
							}
							
					}else{
						$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;
			}



		}

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

            $product_id						= $_POST["product_id"];
			$quantity						= $_POST["quantity"];
			$sell_price						= $_POST["sell_price"];
			// $discount								= $_POST["discount"];
			// $discount_type					= $_POST["discount_type"];
			// $discount_actual				= $_POST["discount_actual"];
			$sell_item_note					= $_POST["sell_item_note"];
			$row_price						= $_POST["row_price"];
			$serials_id						= $_POST["serials_id"];
			$last_buy_price					= $_POST["last_buy_price"];
			$delivery_item					= $_POST["delivery_item"];
			

			
			$customer_id_fk 				= addslashes($_POST["customer_id_fk"]);
			$validity						= addslashes($_POST["validity"]);
			$invoice_date			  		= addslashes($_POST["invoice_date"]);
			$delivery_time					= addslashes($_POST["delivery_time"]);
			$invoice_note	  				= addslashes($_POST["invoice_note"]);
			$offer_status					= addslashes($_POST["offer_status"]);
			$discount						= addslashes($_POST["discount"]);
			$discount_type					= addslashes($_POST["discount_type"]);
			$discount_actual				= addslashes($_POST["discount_actual"]);
			$stock_id_fk					= addslashes($_POST["stock_id_fk"]);
			$pay_terms						= addslashes($_POST["pay_terms"]);
			
			$total_invoice_no_disc			= addslashes($_POST["total_invoice_no_disc"]);
			$total_invoice					= addslashes($_POST["total_invoice"]);
			$request_for_quta_number		= addslashes($_POST["request_for_quta_number"]);
			
			
			$invoice_currency					= 1; //USD
			$term_and_conditions = "";

						

			

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

			$res = $db->query("SELECT offer_sequence_no FROM offer ORDER BY offer_id DESC LIMIT 1");
			$row = $res->fetch_assoc();
			$invoice_sequence_no 	= $row['offer_sequence_no'] +1;

			$dd = date("y", time());
			$invoice_number = "Q".$dd.($invoice_sequence_no);
			// extract array VALUES

			$invoice_transaction = "Offer";

			if($invoice_date == null || $invoice_date ==''){
				$invoice_date = date("Y-m-d h:i:s", time());
			}

			$db->autocommit(FALSE); // to rollback insertion if update fail
			$sql ="INSERT INTO offer   (offer_number,
										offer_date, 		
										offer_status,
										offer_usd_rate, 
										offer_currency, 
										offer_total_price_actual, 
										offer_total_net_balance, 
										discount, 
										discount_type, 
										actual_discount, 
										offer_note,
										offer_sequence_no, 
										validity,
										pay_terms, 
										delivery_time, 
										term_and_conditions, 
										request_for_quta_number,
										offer_transaction, 
										customer_id_fk, 
										created_by, 
										last_action, 
										last_action_by)
						 		VALUES( '$invoice_number',
						 				'$invoice_date',
						 				'$offer_status',
						 				'".$_SESSION['USD_TO_IQD']."',
						 				'$invoice_currency',
						 				'$total_invoice_no_disc',
						 				'$total_invoice',
						 				'$discount',
						 				'$discount_type',
						 				'$discount_actual',
						 				'$invoice_note',
						 				'$invoice_sequence_no',
						 				'$validity',
						 				'$pay_terms',
						 				'$delivery_time',
						 				'$term_and_conditions',
						 				'$request_for_quta_number',
						 				'$invoice_transaction',
						 				'$customer_id_fk',
						 				'".$_SESSION['user_id']."',
						 				'$lastaction',
						 				'".$_SESSION['user_id']."')";
			
			$res = $db->query($sql);
			if ($res) {

				$invoice_inserted_id = $db->insert_id;

				$chek_insertion = true;



				// insert into sell items the sold products
				$lastaction = "Add New Offer Sell Product";
				

				for ($i=1;$i<count($product_id);$i++){

					
					$barcode 					= '';
					$tax_per_unit 				= '';
					$sell_item_delivery_name 	= '';

					

					$sql2 ="INSERT INTO offer_sell_item (offer_sell_item_quantity, 
													offer_item_buy_price_per_unit,
													offer_item_sell_price_per_unit,
													offer_tax_per_unit,
													offer_sell_item_barcode,
													offer_sell_date,
													offer_sell_item_notes,
													offer_sell_item_delivery_name,
													product_serial_id_fk,
													product_id_fk,
													offer_id_fk,
													created_by,
													last_action,
													last_action_by)
 								 			VALUES( '$quantity[$i]',
	 								 				'$last_buy_price[$i]',
	 								 				'$sell_price[$i]',
	 								 				'$tax_per_unit',
	 								 				'$barcode',
	 								 				'$invoice_date',
	 								 				'$sell_item_note[$i]',
	 								 				'$delivery_item[$i]',
	 								 				'$serials_id[$i]',
	 								 				'$product_id[$i]',
	 								 				'$invoice_inserted_id',
	 								 				'".$_SESSION['user_id']."',
	 								 				'$lastaction',
	 								 				'".$_SESSION['user_id']."')";
					$res2 = $db->query($sql2);

					if ($res2) {
						
						$last_inserted_sell_item_id = $db->insert_id;

						// we should store this qty in stock also if the offer_status =1
						
						if($offer_status == 1){

							$trans__ = 'Offer';
						}else{
							$trans__ = 'Fake_Offer';

						}

						$sqlS ="INSERT INTO product_stock (recieved_quantity,
													  stock_transaction,
													  transaction_date,
													  invoice_id_fk,
													  sell_item_fk,
													  product_id_fk,
													  product_serial_id_fk,
													  stock_id_fk,
													  created_by,
													  last_action,
													  last_action_by)
											   VALUES('$quantity[$i]',
											   		  '$trans__',
											   		  '$reg_date',
											   		  '$invoice_inserted_id',
											   		  '$last_inserted_sell_item_id',
											   		  '$product_id[$i]',
											   		  '$serials_id[$i]',
											   		  '$stock_id_fk',
											   		  '".$_SESSION['user_id']."',
											   		  '$lastaction',
											   		  '".$_SESSION['user_id']."')";

							$res_S = $db->query($sqlS);
							// now we should update sequence no and check if new year here
							if(!$res_S){
								$chek_insertion = false;

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


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

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

				} // for i


				

				if($chek_insertion == true ){

					$db->commit();
					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية الاضافة بنجاح";
					echo json_encode($op);
					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;
			}

		} // if create

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