<?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
			$cond1 = isset($_GET['id'])? ' AND Pr.product_id_fk='.$_GET['id']:'';
			$cond2 = (isset($_GET['id']) && $_GET['branch_id'] > 0)? ' AND P.branch_id_fk='.$_GET['branch_id']:'';

			$cond 	= $cond1 . $cond2;

			$limits = "LIMIT 0";
			if( $_GET['search']['value'] !=''){
				$limits =  "";
			}

			for($i=0; $i<9;$i++){

				if( $_GET['columns'][$i]['search']['value'] !=''){
					$limits =  "";
				}
			}


			

				
			$table  =  '(
				SELECT
					purchase_id,
					purchase_number,
					purchase_auto_number,
					purchase_date,
					purchase_note,
					purchase_sequence_no,
					purchase_transaction,
					supplier_id_fk,
					supplier_full_name,
					P.stock_id_fk,
					purchase_item_id,
					purchase_quantity,
					attach_bill,
					cost_price,
					stock_name,
					branch_name,

					sum(cost_expenses * purchase_quantity) AS total_price,
					sum(cost_price * purchase_quantity) AS total_price_before_expenses
					
					 FROM
					 	 purchase P
					 	 LEFT JOIN stock S ON (S.stock_id = P.stock_id_fk)
					 	 LEFT JOIN branch B ON (B.branch_id = P.branch_id_fk)
					 	 LEFT JOIN suppliers SU ON (SU.supplier_id = P.supplier_id_fk)
					 	 , purchase_item PP 
					WHERE 
					(PP.purchase_id_fk = P.purchase_id AND P.is_deleted = 0 AND PP.is_deleted = 0 '.$cond.' )  GROUP BY PP.purchase_id_fk '.$limits.'
				
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'purchase_id';
			$columns = array(
			    array( 'db' => 'purchase_id', 'dt' => 0 ),

			    array( 'db' => 'purchase_auto_number', 'dt' => 1 ),
			    array( 'db' => 'purchase_number', 'dt' => 2 ),
			    
			    array( 'db' => 'purchase_date', 'dt' => 3, 'formatter'=> function($d){
							return date('Y-m-d',strtotime($d));
					} ),
			    array( 'db' => 'stock_name', 'dt' => 4 ),
			    array( 'db' => 'total_price_before_expenses', 'dt' => 5 ),
			    array( 'db' => 'total_price', 'dt' => 6 ),
				array( 'db' => 'supplier_full_name', 'dt' => 7 ),
				array( 'db' => 'purchase_note', 'dt' => 8 ),
				array( 'db' => 'branch_name', 'dt' => 9 ),
				array( 'db' => 'attach_bill', 'dt' => 10 )

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

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

			$user_id = $_POST['cusid'];

			$res = $db->query("SELECT * FROM users WHERE user_id = $user_id");
			if ($res) {
				$row = $res->fetch_assoc();
				echo json_encode($row);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id = $_POST['id'];


			$res = $db->query("SELECT purchase_id, 
									  purchase_number, 
									  purchase_auto_number, 
									  purchase_date, 
									  purchase_note,
									  total_expenses,
									  
									 
									  P.stock_id_fk,
									  P.branch_id_fk,
									  supplier_id_fk,
									  supplier_full_name,
									  purchase_item_id, 
									  purchase_quantity, 
									  PI.barcode, 
									  expire_date, 
									  cost_price, 
									  cost_expenses, 
									  PI.sell_price, 
									  purchase_item_note, 
									  PI.purchase_id_fk,
									  PI.product_id_fk, 
									  product_name,
									  stock_name,
									  branch_name,
									  
									(SELECT sum(cost_expenses * purchase_quantity ) FROM purchase_item PID WHERE PID.purchase_id_fk = P.purchase_id AND  PID.is_deleted = 0) AS total_price

								  

										FROM purchase P
										LEFT JOIN purchase_item PI ON (PI.purchase_id_fk = P.purchase_id AND PI.is_deleted=0)
										LEFT JOIN product Pr ON (PI.product_id_fk = Pr.product_id )
									    LEFT JOIN stock S ON (P.stock_id_fk = S.stock_id )
					 	 				LEFT JOIN suppliers SU ON (SU.supplier_id = P.supplier_id_fk)
					 	 				LEFT JOIN branch B ON (B.branch_id = P.branch_id_fk)

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

				$op  = array('purchase'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['purchase_id']  			= $row['purchase_id'];
					$result['purchase_number']  		= $row['purchase_number'];
					$result['purchase_date']  			= date('Y-m-d',strtotime($row['purchase_date'])) ;
					$result['purchase_auto_number']  	= $row['purchase_auto_number'];
					$result['purchase_note']  			= $row['purchase_note'];
					$result['supplier_full_name']  		= $row['supplier_full_name'];
					$result['purchase_item_id'] 		= $row['purchase_item_id'];
					$result['purchase_quantity']  		= $row['purchase_quantity'];
					$result['barcode']  				= $row['barcode'];
					$result['expire_date']  			= $row['expire_date'];
					$result['cost_price']  				= $row['cost_price'];
					$result['cost_expenses']  			= $row['cost_expenses'];
					$result['sell_price']  				= $row['sell_price'];
					$result['purchase_item_note']  		= $row['purchase_item_note'];
					$result['product_id_fk']  			= $row['product_id_fk'];
					$result['product_name']  			= $row['product_name'];
					$result['stock_name']  				= $row['stock_name'];
					$result['total_price']  			= $row['total_price'];
					$result['branch_name']  			= $row['branch_name'];
					$result['total_expenses']  			= $row['total_expenses'];
					
					array_push($op['purchase'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$id 		= $_POST['id'];
			// $cust_id 	= $_POST['cust_id'];

			$res = $db->query("SELECT 
									  supplier_full_name,
									  
									  sum(cost_expenses * purchase_quantity )  AS total_price,

									  

									  (SELECT sum(paid_amount) FROM supplier_payments IP WHERE IP.supplier_id_fk = P.supplier_id_fk AND IP.is_returned=0 AND IP.is_deleted =0 AND IP.payment_transaction ='Payment') AS total_paid

									FROM purchase_item PP
								 		
					 	 				LEFT JOIN purchase P ON (PP.purchase_id_fk = P.purchase_id)

										LEFT JOIN suppliers S ON (P.supplier_id_fk = S.supplier_id )
								 	WHERE P.supplier_id_fk='$id' AND PP.purchase_id_fk = P.purchase_id AND P.is_deleted = 0 AND P.purchase_transaction='Purchase'");

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

				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					
					$result['supplier_full_name'] 		= $row['supplier_full_name'];
					$result['total_price']  			= $row['total_price'];
					$result['total_paid']  				= $row['total_paid'];
					$result['total_remained']  			= $row['total_price'] - $row['total_paid'] ;
					
					array_push($op['invoice'],$result);
						
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$id = $_POST['id'];


			$res = $db->query("SELECT purchase_id, 
									  purchase_number, 
									  purchase_auto_number, 
									  purchase_date, 
									  purchase_note,
									  total_expenses,
									  P.stock_id_fk,
									  P.branch_id_fk,

									  supplier_id_fk,
									  supplier_full_name,
									  purchase_item_id, 
									  purchase_quantity, 
									  PI.barcode, 
									  expire_date,

									  cost_price, 
									  cost_expenses, 
									  PI.sell_price, 
									  purchase_item_note, 
									  PI.purchase_id_fk,
									  PI.product_id_fk, 
									  product_name,
									  stock_name,
									  branch_name, 
									   
									  
									  
									  (SELECT sum(cost_expenses * purchase_quantity ) FROM purchase_item PID WHERE PID.purchase_id_fk = P.purchase_id AND  PID.is_deleted = 0 AND PID.purchase_item_id = PI.purchase_item_id) AS total_row_price,

									  (SELECT sum(cost_expenses * purchase_quantity ) FROM purchase_item PID WHERE PID.purchase_id_fk = P.purchase_id AND  PID.is_deleted = 0) AS total_price

								  

								FROM purchase P
										LEFT JOIN purchase_item PI ON (PI.purchase_id_fk = P.purchase_id AND PI.is_deleted=0)
										LEFT JOIN product Pr ON (PI.product_id_fk = Pr.product_id )
									    LEFT JOIN stock S ON (P.stock_id_fk = S.stock_id )
					 	 				LEFT JOIN suppliers SU ON (SU.supplier_id = P.supplier_id_fk)
					 	 				LEFT JOIN branch B ON (B.branch_id = P.branch_id_fk)

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

				$op  = array('purchase'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['purchase_id']  			= $row['purchase_id'];
					$result['purchase_number']  		= $row['purchase_number'];
					$result['purchase_date']  			= date('Y-m-d',strtotime($row['purchase_date'])) ;
					$result['purchase_auto_number']  	= $row['purchase_auto_number'];
					$result['purchase_note']  			= $row['purchase_note'];
					$result['supplier_id_fk']  			= $row['supplier_id_fk'];
					$result['supplier_full_name']  		= $row['supplier_full_name'];
					$result['purchase_item_id'] 		= $row['purchase_item_id'];
					$result['purchase_quantity']  		= $row['purchase_quantity'];
					$result['barcode']  				= $row['barcode'];
					$result['expire_date']  			= $row['expire_date'];
					$result['cost_price']  				= $row['cost_price'];
					$result['cost_expenses']  			= $row['cost_expenses'];
					$result['sell_price']  				= $row['sell_price'];
					$result['purchase_item_note']  		= $row['purchase_item_note'];
					$result['product_id_fk']  			= $row['product_id_fk'];
					$result['product_name']  			= $row['product_name'];
					$result['stock_name']  				= $row['stock_name'];
					$result['stock_id_fk']  			= $row['stock_id_fk'];
					$result['total_price']  			= $row['total_price'];
					$result['total_expenses']  			= $row['total_expenses'];
					$result['barcode']  				= $row['barcode'];
					$result['branch_id_fk']  			= $row['branch_id_fk'];
					
					$result['total_row_price']  		= $row['total_row_price'];

					array_push($op['purchase'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				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 = 'purchases/'.$inv_no;
						if(! file_exists('../'.$inv_dir)){
							mkdir('../'.$inv_dir);
						}
						$invoice_url = $inv_dir.'/'.$inv_no.'_Purchase.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 = 'purchases/'.$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'] == "update") {

			$id 								= $_POST['item_id'];
			
			$purchase_number					= addslashes($_POST["purchase_number"]);
			$purchase_date						= addslashes($_POST["purchase_date"]);
			$stock_id_fk						= addslashes($_POST["stock_id_fk"]);
			$purchase_note						= addslashes($_POST["purchase_note"]);
			$supplier_id_fk						= addslashes($_POST["supplier_id_fk"]);
			$branch_id_fk						= addslashes($_POST["branch_id_fk"]);
			// $purchase_transaction				= addslashes($_POST["purchase_transaction"]);
			$total_expenses 					= addslashes($_POST["total_expenses"]);

			$product_id_fk						= $_POST["product_id_fk"];
			$purchase_quantity					= $_POST["purchase_quantity"];
			$barcode							= $_POST["barcode"];
			$expire_date						= $_POST["expire_date"];
			$cost_price							= $_POST["cost_price"];
			$cost_expense						= $_POST["cost_expense"];
			$sell_price							= $_POST["sell_price"];
			$purchase_item_note					= $_POST["purchase_item_note"];
			$expenses_currency					= 1; //USD

			
			$reg_date = date("Y-m-d H:i:s", time());

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

			$res = $db->query("SELECT * FROM purchase  WHERE purchase_id = $id");
			$row = $res->fetch_assoc();
			$purchase_transaction 	= $row['purchase_transaction'];


			$lastaction = "Update Purchase";
			$db->autocommit(FALSE); // to rollback update if update fail
			$update_qry = "UPDATE purchase SET  purchase_number = '$purchase_number',
												purchase_date 	= '$purchase_date',
												total_expenses 	= '$total_expenses',

												stock_id_fk 	= '$stock_id_fk',
												purchase_note 	= '$purchase_note',
												supplier_id_fk 	= '$supplier_id_fk',
												branch_id_fk 	= '$branch_id_fk',
												updated_at 		= '$reg_date',
												last_action 	= '$lastaction',
												last_action_by  = '".$_SESSION['user_id']."' 
							WHERE purchase_id = $id";

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

				// delete all items from purchase_item and product_stock then insert it again

				$delete_qry = "DELETE FROM purchase_item WHERE purchase_id_fk = $id";

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

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

				$delete_qry1 = "DELETE FROM product_stock WHERE purchase_id_fk = $id";

				$res3 = $db->query($delete_qry1);

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

				// end Delete old Items and now we need to insert them again

				$last_inserted_purchase_id = $id;

				// insert purchase_items Table

				$chek_insertion = true;

				for ($i=1;$i<count($product_id_fk);$i++){
				    
				    if($cost_price[$i]==''){
					    $cost_price[$i]=0;
					}
					
					if($cost_expense[$i]=='' || $cost_expense[$i]=='null'){
					    $cost_expense[$i]=0;
					}

					$sql2 ="INSERT INTO purchase_item (purchase_quantity,
													  barcode,
													  expire_date,
													  purchase_usd_rate,
													  purchase_currency,
													  cost_price,
													  cost_expenses,
													  sell_price,
													  purchase_item_note,
													  purchase_id_fk,
													  product_id_fk,
													  branch_id_fk,
													  created_by,
													  created_at,
													  updated_at,
													  last_action,
													  last_action_by)
											   VALUES('$purchase_quantity[$i]',
											   		  '$barcode[$i]',
											   		  '$expire_date[$i]',
											   		  '".$_SESSION['USD_TO_IQD']."',
											   		  '$expenses_currency',
											   		  '$cost_price[$i]',
											   		  '$cost_expense[$i]',
											   		  '$sell_price[$i]',
											   		  
											   		  '$purchase_item_note[$i]',
											   		  '$last_inserted_purchase_id',
											   		  '$product_id_fk[$i]',
											   		  '$branch_id_fk',
											   		  '".$_SESSION['user_id']."',
											   		  '$reg_date',
											   		  '$reg_date',
											   		  '$lastaction',
											   		  '".$_SESSION['user_id']."')";
					
					$res4 = $db->query($sql2);




					if ($res4) {
						
						// we should store this qty in stock also
						$last_inserted_purchase_item_id = $db->insert_id;

						$sqlS ="INSERT INTO product_stock (
													  recieved_quantity,
													  stock_transaction,
													  stock_transaction_type,
													  transaction_date,
													  barcode,
													  expire_date,
													  buy_price,
													  purchase_id_fk,
													  purchase_item_id_fk,
													  product_id_fk,
													  stock_id_fk,
													  branch_id_fk,
													  supplier_id_fk,
													  created_by,
													  created_at,
													  updated_at,
													  last_action,
													  last_action_by)
											   VALUES('$purchase_quantity[$i]',
											   		  '$purchase_transaction',
											   		  '1',
											   		  '$reg_date',
											   		  '$barcode[$i]',
											   		  '$expire_date[$i]',
											   		  '$cost_price[$i]',
											   		  '$last_inserted_purchase_id',
											   		  '$last_inserted_purchase_item_id',
											   		  '$product_id_fk[$i]',
											   		  '$stock_id_fk',
											   		  '$branch_id_fk',
											   		  '$supplier_id_fk',
											   		  '".$_SESSION['user_id']."',
											   		  '$reg_date',
											   		  '$reg_date',
											   		  '$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{
						$chek_insertion = false;

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

				}	// for i


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


			if($chek_insertion == true){
				

				$db->commit();

				$op['is_success'] = true;
				$op['data'] 	  = "تمت عملية التحديث بنجاح";
				echo json_encode($op);
				exit;
			}

		}


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

			$id	 = addslashes($_POST["obj_id"]);
			$op  = array('is_success'=>false, 'data' => '');

			

			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Purchase";


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

			if ($res){

				$update_qry = "UPDATE purchase_item SET  is_deleted = 1, deleted_at='$reg_date', last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_id_fk = $id";

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

				if ($res) {

					$update_qry1 = "UPDATE product_stock SET  is_deleted = 1, deleted_at='$reg_date', last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE purchase_id_fk = $id";

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

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





		}

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

			$purchase_number					= addslashes($_POST["purchase_number"]);
			$purchase_date						= addslashes($_POST["purchase_date"]);
			$stock_id_fk						= addslashes($_POST["stock_id_fk"]);
			$purchase_note						= addslashes($_POST["purchase_note"]);
			$supplier_id_fk						= addslashes($_POST["supplier_id_fk"]);
			$branch_id_fk						= addslashes($_POST["branch_id_fk"]);
			$purchase_transaction				= addslashes($_POST["purchase_transaction"]);
			$total_expenses 					= addslashes($_POST["total_expenses"]);
			$total_paid 						= addslashes($_POST["total_paid"]);

			$product_id_fk						= $_POST["product_id_fk"];
			$purchase_quantity					= $_POST["purchase_quantity"];
			$barcode							= $_POST["barcode"];
			$expire_date						= $_POST["expire_date"];
			$cost_price							= $_POST["cost_price"];
			$cost_expense						= $_POST["cost_expense"];
			$sell_price							= $_POST["sell_price"];
			$purchase_item_note					= $_POST["purchase_item_note"];
			$expenses_currency					= 1; //USD



			$product_id_fk 			= explode(',', $product_id_fk);
			$purchase_quantity 		= explode(',', $purchase_quantity);
			$barcode 				= explode(',', $barcode);
			$expire_date 			= explode(',', $expire_date);
			$cost_price 			= explode(',', $cost_price);
			$cost_expense 			= explode(',', $cost_expense);
			$sell_price 			= explode(',', $sell_price);
			$purchase_item_note 	= explode(',', $purchase_item_note);


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

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

			$res = $db->query("SELECT * FROM purchase  ORDER BY purchase_id DESC LIMIT 1");
			$row = $res->fetch_assoc();
			$purchase_sequence_no 	= $row['purchase_sequence_no'] +1;

			$dd = date("y", time());

			if($purchase_transaction =='Initial'){
				$purchase_auto_number = "INT".$dd."".($purchase_sequence_no);
				$purchase_transaction = "Initial";

			}else{
				$purchase_auto_number = "PR".$dd."".($purchase_sequence_no);
				$purchase_transaction = "Purchase";

			}

			// Upadte purchase_sequence_no




			$db->autocommit(FALSE); // to rollback insertion if update fail
			$sql ="INSERT INTO purchase (purchase_number,
										 purchase_auto_number,
										 purchase_sequence_no,
										 purchase_date,
										 purchase_note,
										 purchase_transaction,
										 total_expenses,
										 supplier_id_fk,
										 stock_id_fk,
										 branch_id_fk,
										 created_by,
										 created_at,
										 updated_at,
										 last_action,
										 last_action_by)
								  VALUES('$purchase_number',
								  		 '$purchase_auto_number',
								  		 '$purchase_sequence_no',
								  		 '$purchase_date',
								  		 '$purchase_note',
								  		 '$purchase_transaction',
								  		 '$total_expenses',
								  		 '$supplier_id_fk',
								  		 '$stock_id_fk',
								  		 '$branch_id_fk',
								  		 '".$_SESSION['user_id']."',
								  		 '$reg_date',
								  		 '$reg_date',
								  		 '$lastaction',
								  		 '".$_SESSION['user_id']."')";
						
			$res = $db->query($sql);

			if ($res) {

				$last_inserted_purchase_id = $db->insert_id;

				// insert purchase_items Table

				$chek_insertion = true;

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

					if($cost_price[$i]==''){
					    $cost_price[$i]=0;
					}
					
					if($cost_expense[$i]=='' || $cost_expense[$i]=='null'){
					    $cost_expense[$i]=0;
					}

					$sql2 ="INSERT INTO purchase_item (purchase_quantity,
													  barcode,
													  expire_date,
													  purchase_usd_rate,
													  purchase_currency,
													  cost_price,
													  cost_expenses,
													  sell_price,
													  purchase_item_note,
													  purchase_id_fk,
													  product_id_fk,
													  branch_id_fk,
													  created_by,
													  created_at,
													  updated_at,
													  last_action,
													  last_action_by)
											   VALUES('$purchase_quantity[$i]',
											   		  '$barcode[$i]',
											   		  '$expire_date[$i]',
											   		  '".$_SESSION['USD_TO_IQD']."',
											   		  '$expenses_currency',
											   		  '$cost_price[$i]',
											   		  '$cost_expense[$i]',
											   		  '$sell_price[$i]',
											   		  
											   		  '$purchase_item_note[$i]',
											   		  '$last_inserted_purchase_id',
											   		  '$product_id_fk[$i]',
											   		  '$branch_id_fk',
											   		  '".$_SESSION['user_id']."',
											   		  '$reg_date',
											   		  '$reg_date',
											   		  '$lastaction',
											   		  '".$_SESSION['user_id']."')";

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




					if ($res2) {
						
						// we should store this qty in stock also
						$last_inserted_purchase_item_id = $db->insert_id;
						
						$sqlS ="INSERT INTO product_stock (
													  recieved_quantity,
													  stock_transaction,
													  stock_transaction_type,
													  transaction_date,
													  barcode,
													  expire_date,
													  buy_price,
													  purchase_id_fk,
													  purchase_item_id_fk,
													  product_id_fk,
													  stock_id_fk,
													  branch_id_fk,
													  supplier_id_fk,
													  created_by,
													  created_at,
													  updated_at,
													  last_action,
													  last_action_by)
											   VALUES('$purchase_quantity[$i]',
											   		  '$purchase_transaction',
											   		  '1',
											   		  '$reg_date',
											   		  '$barcode[$i]',
											   		  '$expire_date[$i]',
											   		  '$cost_price[$i]',
											   		  '$last_inserted_purchase_id',
											   		  '$last_inserted_purchase_item_id',
											   		  '$product_id_fk[$i]',
											   		  '$stock_id_fk',
											   		  '$branch_id_fk',
											   		  '$supplier_id_fk',
											   		  '".$_SESSION['user_id']."',
											   		  '$reg_date',
											   		  '$reg_date',
											   		  '$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;
						}
						
						// now we should update sell price in products tables

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

							$update_qry_prod = "UPDATE product SET  
															sell_price 		= '$sell_price[$i]',
						 									last_action 	= 'Update Sell Price',
						 									updated_at 		= '$reg_date',
						 									last_action_by 	= '".$_SESSION['user_id']."' 
						 					WHERE product_id = $product_id_fk[$i]";

							$res_pro = $db->query($update_qry_prod);

						}

						

														

							
					}else{
						$chek_insertion = false;

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

				}	// for i
					
			
			}else{
				$chek_insertion = false;

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

			}


			// add supplier payment

			$lastaction = "Add New Supplier Payment";
			if($total_paid > 0){

				

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

				
				$payment_number = "SPAY".$dd.($pay_sequence_no);
				$payment_transaction = 'Payment';
				$payment_note = "Add Payment for Purchase : ".$purchase_auto_number;
				$sql_p ="INSERT INTO supplier_payments(
											  payment_number,
		 									  pay_usd_rate,
		 									  pay_currency,
		 									  paid_amount,
		 									  paid_date,
		 									  payment_note,
		 									  payment_transaction,
		 									  pay_sequence_no,
		 									  supplier_id_fk,
		 									  purchase_id_fk,
		 									  branch_id_fk,
		 									  created_by,
		 									  last_action,
		 									  last_action_by)
		 							   VALUES('$payment_number',
		 							   		  '".$_SESSION['USD_TO_IQD']."',
		 							    	  '$expenses_currency',
		 							    	  '$total_paid',
		 							    	  '$purchase_date',
		 							    	  '$payment_note',
		 							    	  '$payment_transaction',
		 							    	  '$pay_sequence_no',
		 							    	  '$supplier_id_fk',
		 							    	  '$last_inserted_purchase_id',
		 							    	  '$branch_id_fk',
		 							    	  '".$_SESSION['user_id']."',
		 							    	  '$lastaction',
		 							    	  '".$_SESSION['user_id']."')";
				


				$res_P = $db->query($sql_p);

				if ($res_P){
					
					// now we should insert it in Safe
						$last_inserted_payment_id = $db->insert_id;

						$res = $db->query("SELECT * FROM safe  ORDER BY safe_id DESC LIMIT 1");
						$row = $res->fetch_assoc();
						$safe_sequence_no 	= $row['safe_sequence_no'] +1;

						$dd = date("y", time());
						$safe_number = "SP".$dd.($safe_sequence_no);

						// Upadte purchase_sequence_no

						$safe_transaction = "Purchase";
						$transaction_type = "2";  // 1: add ; 2:subtract;
					
						

						$reg_date 	= date("Y-m-d H:i:s", time());
						$lastaction = "Add New Supplier Payment";
						$safe_note 	= "Add New Supplier Payment  ID : " . $last_inserted_payment_id;

						$sql1 ="INSERT INTO safe 
										   (safe_number,
											safe_amount,
											date_of_add,
											safe_transaction,
											transaction_type,
											capital_usd_rate,
											capital_currency,
											table_name,
											id_fk,
											safe_sequence_no,
											safe_note,
											staff_id_fk,
											branch_id_fk,
											created_by,
											created_at,
										    updated_at,
											last_action,
											last_action_by)
									VALUES( '$safe_number',
											'$total_paid',
											'$reg_date',
											'$safe_transaction',
											'$transaction_type',
											'".$_SESSION['USD_TO_IQD']."',
											'$expenses_currency',
											'supplier_payments',
											'$last_inserted_payment_id',
											'$safe_sequence_no',
											'$safe_note',
											'".$_SESSION['user_id']."',
											'$branch_id_fk',
											'".$_SESSION['user_id']."',
											'$reg_date',
											'$reg_date',
											'$lastaction',
											'".$_SESSION['user_id']."')";

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

						if(!$res1){

							$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 supplier payment
							
			if($chek_insertion == true){


				$last_inserted_id = $last_inserted_purchase_id;

				/// for file upload
				$target_dir = '../purchases/'.$last_inserted_id;
				if(! file_exists($target_dir)){
					mkdir($target_dir);
				}
				

				$count=0;

				$image_path		='';
                $manual_path 	='';
                $State 			=true;
                $State1			=true;
                $error 			= '';			
                $error1			= '';


				
				if($_FILES['attach_bill']['size'] > 0 ){
					
					$ext11  = pathinfo(basename($_FILES['attach_bill']['name']),PATHINFO_EXTENSION);
					
					$image_file = $last_inserted_id."_".rand(100000,10000000) ."_.".$ext11;
									
					// $image_file = rand(10000000,1000000000) . "-" .$_FILES['attach_bill']['name'];
					
					$target_file 		= $target_dir .'/'. basename($image_file);
					
					$uploadOk = 1;
					$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
										
					$State1=true;
					// Check file size
					if ($_FILES["attach_bill"]["size"] > 4000000) {
							$error1= " Sorry, your file is too large. ";
							$State1=false;
					}

					
					// Allow certain file formats
					if(strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "gif" && strtolower($imageFileType) != "bmp" && strtolower($imageFileType) != "pdf" ) {
						$error1= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
						$State1=false;
					}

					// Check if $uploadOk is set to 0 by an error
					if ($State1 == true) {
					
						if (move_uploaded_file($_FILES["attach_bill"]["tmp_name"], $target_file)){

							$image_path  = 'purchases/'.$last_inserted_id .'/'.$image_file;
							$State1=true;											  

						} else {
								$error1= " Sorry, there was an error uploading your file. ";
								$State1=false;
						}
					}
				}		
                
                $tmp 			='';
		        
		        $sql ="UPDATE  purchase SET attach_bill = '$image_path' WHERE purchase_id ='$last_inserted_id'";
							
				$query = $db->query($sql);
				if (!$query) {
					$msgg= "Image Not Uploaded";
					$State=false;

				}else{
					$msgg= "Successfully Added ";
					$State=true;
				}		   


			

				
				$db->commit();

				$op['is_success'] = true;
				$op['data'] 	  = "تمت عملية الاضافة بنجاح";
				$op['image'] 	  = $error;
				echo json_encode($op);
				exit;
			}

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