Find this useful? Enter your email to receive occasional updates for securing PHP code.

Signing you up...

Thank you for signing up!

PHP Decode

<?php defined('BASEPATH') OR exit('No direct script access allowed'); include_once('vend..

Decoded Output download

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
include_once('vendor/autoload.php'); 
class Purchase extends CI_Controller  
{ 
	function __construct() 
	{ 
		parent::__construct(); 
		$this->load->database(); 
        $this->load->library('session'); 
       
        #Cache Control 
		$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); 
		$this->output->set_header('Pragma: no-cache'); 
	} 
	 
	function ManagePurchase($type = '', $id = '', $status = '') 
    { 
   	    //echo phpinfo();exit; 
     
		if (empty($this->user_id)) 
        { 
			redirect(base_url() . 'admin/adminLogin', 'refresh'); 
		} 
	 
		$page_data['type'] = $type; 
		$page_data['id'] = $id; 
		 
		$page_data['ManagePurchase'] = 1; 
		$page_data['page_name']  = 'purchase/ManagePurchase'; 
		$page_data['page_title'] = 'Purchase Orders'; 
		 
		if(isset($_POST['delete']) && isset($_POST['checkbox'])) 
		{ 
			$cnt=array(); 
			$cnt=count($_POST['checkbox']); 
			 
			for($i=0;$i<$cnt;$i++) 
			{ 
				$del_id=$_POST['checkbox'][$i]; 
				  
				$this->db->where('purchase_id', $del_id); 
				$this->db->delete('purchase_items'); 
				 
				$this->db->where('purchase_id', $del_id); 
				$this->db->delete('purchases'); 
			} 
			$this->session->set_flashdata('flash_message' , "Purchase deleted successfully!"); 
			redirect($_SERVER['HTTP_REFERER'], 'refresh'); 
		} 
		 
		switch($type) 
		{ 
			case "add": #View 
				$page_data['warehouse'] = $this->purchase_model->getWarehouse(); 
				 
				if($_POST) 
				{ 
					$data1['invoice_add_date'] = $this->input->post('date'); 
					 
					$invoice_add_date = strtotime($data1['invoice_add_date']); 
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date)); 
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020 
					 
					$warehouse_id = $this->input->post('warehouse'); 
 
					$po_status = 1; 
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0; 
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0; 
					 
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0) 
					{ 
					    $total_tax = $_POST['total_tax']; 
					} 
					else 
					{ 
					    $total_tax = 0; 
					} 
					 
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0) 
					{ 
					    $total_discount = $_POST['total_discount']; 
					} 
					else 
					{ 
					    $total_discount = 0; 
					} 
					 
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type'])) 
					{ 
						$additionalChargeType = $_POST['additional_charge_type']; 
					} 
					else 
					{ 
						$additionalChargeType = 0; 
					} 
 
					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge'])) 
					{ 
						$additionalCharge = $_POST['additional_charge']; 
					} 
					else 
					{ 
						$additionalCharge = 0; 
					} 
 
					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0; 
					 
					$data = array( 
						"date" 				      =>  date('Y-m-d',$invoice_add_date), 
						"invoice_add_date" 	      =>  $this->input->post('date'), 
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)), 
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date), 
						"warehouse_id" 		      =>  $warehouse_id, 
						"supplier_id" 		      => isset($_POST["supplier"]) ? $_POST["supplier"] : 0, 
						 
						 
						"supplier_site" 		  =>  $supplier_site, 
						"total" 			      =>  $grand_total, 
						"discount_value"	      =>  $total_discount, 
						"tax_value" 		      =>  $total_tax, 
 
						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0, 
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0, 
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0, 
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0, 
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0, 
						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0, 
						"note" 				      =>  $this->input->post('note'), 
						"tax_type" 				  =>  $tax_type, 
						"po_status" 			  =>  $po_status, #Pending 
						"created_date" 			  =>  time(), 
						"additional_charge_type"     =>  $additionalChargeType, 
						"additional_charge" 	     =>  $additionalCharge, 
					); 
					#print_r($data);exit; 
					$this->db->insert('purchases', $data); 
					$purchase_id = $this->db->insert_id(); 
					 
					if($purchase_id) 
					{ 
						#purchase ID Start here 
						$sequenceQry = "select purchase_id,increment_id from purchases  
								where fin_year_status = 0 order by increment_id desc"; 
 
						$results = $this->db->query($sequenceQry)->result_array(); 
						 
						if( count($results) == 1 ) 
						{ 
							$incrementID = 0; 
						} 
						else if( count($results) == 2 ) 
						{ 
							$incrementID = 1; 
						} 
						else 
						{ 
							$incID = isset($results[0]['increment_id']) ? $results[0]['increment_id'] : 1; 
							$incrementID = $incID + 1; 
						} 
 
						/* $random_user_id =  $incrementID; 
						$UpdateData['reference_no'] = 'RE-'.$random_user_id; 
						$UpdateData['increment_id'] = $incrementID; */ 
 
						/* 	$UpdateData['reference_no'] = PURCHASE_NUMBER_PREFIX."".str_pad($incrementID, PURCHASE_NUMBER_LENGTH, "0", STR_PAD_LEFT); 
						$UpdateData['increment_id'] = $incrementID; 
						*/ 
 
						$getPrefix = $this->db->query("select prefix_name, prefix_length, from_year, prefix_starting_number from org_prefix_length where prefix_type = 2")->result_array(); 
						$startingNumber = $getPrefix[0]['prefix_starting_number']; 
						$incNumber = $startingNumber + $incrementID; 
						$randomUserId = $getPrefix[0]['prefix_name']."".$incNumber; 
 
 
						$UpdateData['reference_no'] = $randomUserId; 
						$UpdateData['increment_id'] = $incrementID; 
 
						$this->db->where('purchase_id', $purchase_id); 
						$resultUpdateData = $this->db->update('purchases', $UpdateData); 
						#Purchase ID end here 
						 
						$PurchaseItems = $this->input->post('table_data'); 
						$js_data = json_decode($PurchaseItems); 
                     
                   		if(!empty($js_data)) 
                        { 
						foreach ($js_data as $key => $value)  
						{ 
							if($value==null) 
							{ 
								 
							} 
							else 
							{ 
								$product_id = $value->product_id; 
								$quantity = $value->quantity; 
								 
								if(isset($value->expiry_date) && $value->expiry_date !="") 
								{ 
									$expiry_date1 = date("d")."-".$value->expiry_date; 
 
									$expiry_date =  date("Y-m-d",strtotime($expiry_date1)); 
								} 
								else 
								{ 
									$expiry_date = null; 
								} 
 
								/*  
								#Lot No start here 
								if(isset($value->batch_no) && $value->batch_no !=""){ 
									$batch_no = $value->batch_no; 
								}else{ 
									$batch_no = null; 
								} 
 
								if(LOT_CONTROL_LEVEL == 1) #Product 
								{ 
									$increment_id = 0; 
								} 
								else if(LOT_CONTROL_LEVEL == 2) #Org 
								{ 
									$increment_id = isset($value->increment_id) ? $value->increment_id : 0; 
								} #Lot No end here 
								*/ 
 
								$data1 = array( 
									#"increment_id"      => $increment_id, 
									"product_id"         => $value->product_id, 
									"quantity"           => $value->quantity, 
									"gross_total"        => $value->total, 
									"discount_id"        => $value->discount_id, 
									"discount_value"     => $value->discount_value, 
									"discount"           => $value->discount, 
									"tax_id"             => $value->tax_id, 
									"tax_value"          => $value->tax_value, 
									"tax"                => $value->tax, 
									"cost"               => $value->cost, 
									#"batch_no"          => $batch_no, 
									#"expiry_date"       => $expiry_date, 
									"purchase_id"        => $purchase_id, 
									"purchase_item_date" => time(), 
 
									"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"", 
								); 
								 
 
								#add Product in warehouse start here 
								/* $warehouse_data = array( 
									"product_id"   => $value->product_id, 
									"warehouse_id" => $warehouse_id, 
									"quantity"     => $value->quantity 
								); 
								 
								$this->purchase_model->addProductInWarehouse($product_id,$quantity,$warehouse_id,$warehouse_data); 
						 		*/ 
								#add Product in warehouse end here 
								 
								$this->db->insert('purchase_items', $data1); 
								$purchase_items  = $this->db->insert_id(); 
							} 
						} 
                        } 
						 
						#getPR Amount start here 
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$purchase_id."'"; 
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array(); 
 
						$totalAmount = 0; 
						foreach($getPurchaseItems as $purchaseItems) 
						{ 
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"]; 
						} 
 
						$reRequestData = array( 
							"request_id"     => $purchase_id, 
							"request_status" => $po_status, 
							"request_type"   => 1, //Purchase Order 
							"request_date"   => time(), 
							"total_amount"   => $totalAmount, 
							"created_by"     => $this->user_id, 
						); 
 
						$this->db->insert('pr_po_rerequest', $reRequestData); 
						$rerequest_id = $this->db->insert_id(); 
						#getPR Amount end here 
 
						#Audit Trails Start here 
						/* $tableName = purchase_tbl; 
						$createdMessage = $UpdateData['reference_no']." created successfully!"; 
						auditTrails($createdMessage,$tableName,$type); */ 
						#Audit Trails end here 
 
						$this->session->set_flashdata('flash_message' , "Purchase order created successfully!"); 
						redirect(base_url() . 'purchase/ManagePurchase', 'refresh'); 
					} 
				} 
			break; 
			 
			case "edit": #edit 
				$page_data['warehouse'] = $this->purchase_model->getWarehouse();  
				$page_data['data'] = $this->purchase_model->getRecord($id); 
				 
				$page_data['discount'] = $this->purchase_model->getDiscount(); 
				$page_data['tax'] = $this->purchase_model->getTax(); 
				 
				foreach ($page_data['data'] as $key)  
				{ 
					$purchase_id = $key->purchase_id; 
					$warehouse_id = $key->warehouse_id; 
					$page_data['items'] = $this->purchase_model->getPurchaseItems($purchase_id,$warehouse_id);	 
				} 
 
				$page_data['purchase_id'] = $purchase_id = $id; 
				 
                if($_POST) 
				{ 
 
				   // print_r($_POST);exit; 
 
					$data1['invoice_add_date'] = $this->input->post('date'); 
					 
					$invoice_add_date = strtotime($data1['invoice_add_date']); 
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date)); 
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020 
					 
					$warehouse_id = $this->input->post('warehouse'); 
 
					$purchase_request_type = $this->input->post('purchase_request_type'); 
					 
					if( $status == "re_request" ) 
					{ 
						$po_status = 1; #Draft 
					} 
					else 
					{ 
						$po_status = 1; 
					} 
					 
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0; 
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0; 
					 
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0) 
					{ 
					    $total_tax = $_POST['total_tax']; 
					} 
					else 
					{ 
					    $total_tax = 0; 
					} 
					 
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0) 
					{ 
					    $total_discount = $_POST['total_discount']; 
					} 
					else 
					{ 
					    $total_discount = 0; 
					} 
					 
					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0; 
 
					 
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type'])) 
					{ 
						$additionalChargeType = $_POST['additional_charge_type']; 
					} 
					else 
					{ 
						$additionalChargeType = 0; 
					} 
 
					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge'])) 
					{ 
						$additionalCharge = $_POST['additional_charge']; 
					} 
					else 
					{ 
						$additionalCharge = 0; 
					} 
					 
					 
					$data = array( 
						"date" 				      =>  date('Y-m-d',$invoice_add_date), 
						"invoice_add_date" 	      =>  $this->input->post('date'), 
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)), 
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date), 
						"warehouse_id" 		      =>  $warehouse_id, 
						 
						"supplier_id" 		      =>  isset($_POST["supplier"]) ? $_POST["supplier"] : 0, 
						 
						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0, 
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0, 
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0, 
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0, 
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0, 
 
						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0, 
 
						"supplier_site" 		  =>  $supplier_site, 
						"total" 			      =>  $grand_total, 
						"discount_value"	      =>  $total_discount, 
						"tax_value" 		      =>  $total_tax, 
 
						"note" 				      =>  $this->input->post('note'), 
						"tax_type" 				  =>  $tax_type, 
						"po_status" 		      =>  $po_status, 
						"additional_charge_type"     =>  $additionalChargeType, 
						"additional_charge" 	     =>  $additionalCharge, 
					); 
					#print_r($data);exit; 
					$this->db->where('purchase_id', $id); 
					$result = $this->db->update('purchases', $data); 
					 
					if($result) 
					{ 
						$js_data = json_decode($this->input->post('table_data1'));			 
						$php_data = json_decode($this->input->post('table_data')); 
                     
                    	#print_r($_POST["table_data"]);exit; 
						 
						if(!empty($js_data)) 
						{ 
							foreach (array_filter($js_data) as $key => $value)  
							{ 
								if($value=='delete') 
								{ 
									 
									$product_id =  $php_data[$key]; 
									if($this->purchase_model->deletePurchaseItems($id,$product_id,$warehouse_id)) 
									{ 
										 
									} 
								} 
								else if($value==null) 
								{ 
									 
								} 
								else 
								{ 
									$product_id = $value->product_id; 
									$quantity = $value->quantity; 
 
									if(isset($value->expiry_date) && $value->expiry_date !="") 
									{ 
										$expiry_date1 = date("d")."-".$value->expiry_date; 
 
										$expiry_date =  date("Y-m-d",strtotime($expiry_date1)) ; 
									} 
									else 
									{ 
										$expiry_date = null; 
									} 
 
	 
									/*  
									#Lot No start here 
									if(isset($value->batch_no) && $value->batch_no !=""){ 
										$batch_no = $value->batch_no; 
									}else{ 
										$batch_no = null; 
									} 
 
									if(LOT_CONTROL_LEVEL == 1) #Product 
									{ 
										$increment_id = 0; 
									} 
									else if(LOT_CONTROL_LEVEL == 2) #Org 
									{ 
										$increment_id = isset($value->increment_id) ? $value->increment_id : 0; 
									}  
									#Lot No end here 
									*/ 
									 
									$data = array( 
										#"increment_id"     => $increment_id, 
										"product_id"       => $value->product_id, 
										"quantity"         => $value->quantity, 
										"gross_total"      => $value->total, 
										"discount_id"      => $value->discount_id, 
										"discount_value"   => $value->discount_value, 
										"discount"         => $value->discount, 
										"tax_id"           => $value->tax_id, 
										"tax_value"        => $value->tax_value, 
										"tax"              => $value->tax, 
										"cost"             => $value->cost, 
										#"expiry_date"      => $expiry_date, 
										#"batch_no"         => $batch_no, #Lot No 
										"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"", 
										"purchase_id"      => $id 
									); 
 
									$warehouse_data = array( 
										"product_id"     => $value->product_id, 
										"warehouse_id"   => $warehouse_id, 
										"quantity"       => $value->quantity 
									); 
 
									if($this->purchase_model->addUpdatePurchaseItem($id,$product_id,$warehouse_id,$quantity,$data,$warehouse_data)) 
									{ 
										 
									} 
									else 
									{ 
 
									} 
								} 
							} 
						} 
 
						#getPR Amount start here 
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$id."'"; 
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array(); 
 
						$totalAmount = 0; 
						foreach($getPurchaseItems as $purchaseItems) 
						{ 
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"]; 
						} 
						#getPR Amount end here 
						 
						if ( $status == "re_request" ) #PR Re Request 
						{ 
							$reRequestData = array( 
								"request_id"     => $id, 
								"request_status" => $po_status, 
								"request_type"   => 1, 
								"request_date"   => time(), 
								"total_amount"   => $totalAmount, 
								"created_by"     => $this->user_id, 
							); 
 
							$this->db->insert('pr_po_rerequest', $reRequestData); 
							$rerequest_id = $this->db->insert_id(); 
 
							$submit_levelData["submit_level"] =1; //all levels Completed 
							$this->db->where('submit_level', 0); 
							//$this->db->where('submit_level !=', 1); 
							$this->db->where('request_id', $id); 
							$this->db->where('approval_type', 1); 
							$result = $this->db->update('org_approval_status', $submit_levelData); 
						} 
						#re_request end here 
						 
						$this->session->set_flashdata('flash_message' , "Purchase order updated successfully!"); 
						redirect(base_url() . 'purchase/ManagePurchase/'.$id, 'refresh'); 
					} 
				} 
			break; 
			 
			case "delete": #Delete 
				$this->db->where('sales_id', $id); 
				$this->db->delete('sales'); 
				 
				$this->db->where('sales_id', $id); 
				$this->db->delete('sales_items'); 
				 
				/* $this->db->where('invoice_id', $id); 
				$this->db->delete('invoice_payment'); */ 
				 
				$this->session->set_flashdata('flash_message' , "Sale deleted successfully!"); 
				redirect(base_url() . 'sales/ManageSales', 'refresh'); 
			break; 
 
			case "approval_status": #approval_status 
				if($status == 5) #Close 
				{ 
					$successMsg = "Purchase order closed successfully!"; 
				} 
				else if($status == 4) #Cancel 
				{ 
					$successMsg = "Purchase order cancelled successfully!"; 
				} 
  
				$updateData["po_status"] = $status; 
 
				$this->db->where('purchase_id', $id); 
				 
				$result = $this->db->update('purchases', $updateData); 
 
				$this->session->set_flashdata('flash_message' , $successMsg); 
				redirect(base_url() . 'purchase/ManagePurchase', 'refresh'); 
			break; 
 
			default : #Manage 
				$page_data["totalRows"] = $totalRows = $this->purchase_model->getManagePurchaseCount(); 
	 
				if(!empty($_SESSION['PAGE'])) 
				{$limit = $_SESSION['PAGE']; 
				}else{$limit = 10;} 
				 
				if (!empty($_GET['keywords'])) { 
					$base_url = base_url('purchase/ManagePurchase?keywords='.$_GET['keywords']); 
				} else { 
					$base_url = base_url('purchase/ManagePurchase?keywords='); 
				} 
				 
				$config = PaginationConfig($base_url,$totalRows,$limit); 
				$this->pagination->initialize($config); 
				$str_links = $this->pagination->create_links(); 
				$page_data['pagination'] = explode('', $str_links); 
				$offset = 0; 
				if (!empty($_GET['per_page'])) { 
					$pageNo = $_GET['per_page']; 
					$offset = ($pageNo - 1) * $limit; 
				} 
				 
				if($offset == 1 || $offset== "" || $offset== 0){ 
					$page_data["first_item"] = 1; 
				}else{ 
					$page_data["first_item"] = $offset + 1; 
				} 
				 
				$page_data['resultData']  = $result= $this->purchase_model->getManagePurchase($limit, $offset); 
				 
				#show start and ending Count 
				$total_counts = $total_count= 0; 
				$pages=$page_data["starting"] = $page_data["ending"]=""; 
				$pageno = isset($pageNo) ? $pageNo :""; 
				 
				if( $totalRows == 0 ){ 
					$page_data["starting"] = 0; 
				}else if( $pageno==1 || $pageno=="" ){ 
					$page_data["starting"] = 1; 
				}else{ 
					$pages = $pageno-1; 
					$total_count = $pages * $config["per_page"]; 
					$page_data["starting"] = ( $config["per_page"] * $pages )+1; 
				} 
				 
				$total_counts = $total_count + count($result); 
				$page_data["ending"]  = $total_counts; 
				#show start and ending Count end 
			break; 
		}	 
		$this->load->view($this->adminTemplate, $page_data); 
	} 
	 
	function generatePDF($purchase_id="") 
    { 
		 $page_data['id'] = $id = $purchase_id; 
		 
		  
		/* $userQuery = "select  
			users.first_name, 
			users.last_name, 
			users.random_user_id, 
			emp_periods.month, 
			emp_periods.year 
			from emp_payslip_header  
		 
		left join users on  
			users.user_id = emp_payslip_header.user_id 
 
		left join org_financial_years on  
			org_financial_years.financial_year_id = emp_payslip_header.financial_year_id 
		 
		left join emp_periods on  
			emp_periods.period_id = emp_payslip_header.period_id 
 
		where emp_payslip_header.header_id='".$payslip_id."' "; 
		$userDetails = $this->db->query($userQuery)->result_array(); 
 
		$random_user_id = $userDetails[0]["random_user_id"]; 
		$employee_name = ucfirst($userDetails[0]["first_name"])." ".ucfirst($userDetails[0]["last_name"]); 
		 
		$period_month = $userDetails[0]["month"]; 
		$year = $userDetails[0]["year"]; */ 
		$date = date('d-M-Y'); 
 
		ob_start(); 
		$html = ob_get_clean(); 
		$html = utf8_encode($html); 
		 
		$html = $this->load->view('backend/purchase/generatePurchasePDF',$page_data,true); 
		$pdf_name = $date; 
		$mpdf = new \Mpdf\Mpdf([ 
			'setAutoTopMargin' => 'stretch', 
            'curlAllowUnsafeSslRequests' => true 
		]); 
 
		//$mpdf->SetHTMLHeader($this->load->view('backend/purchase/generatePurchaseHeaderPDF',$page_data,true)); 
		 
        $mpdf->AddPage('L','','','','',7,7,7,7,7,7); 
		$mpdf->WriteHTML($html); 
		$mpdf->Output($pdf_name.'.pdf','I'); 
	} 
 
	/* public function getProduct($product_id="") 
	{ 
		$data = $this->db->select('p.product_id,cat.category_name,p.product_code,hsn_code.hsn_code as hsn_sac_code,p.unit,p.product_name,p.size,p.cost,p.price,p.alert_quantity,p.product_image,p.category_id,p.subcategory_id,p.tax_id,p.quantity,t.tax_value') 
				->from('products p') 
				->join('category cat','p.category_id = cat.category_id','left') 
				->join('tax t','p.tax_id = t.tax_id','left') 
				->join('inv_hsn_codes hsn_code','p.hsn_sac_code = hsn_code.hsn_code_id','left') 
				->where('p.product_id',$product_id) 
				->get() 
				->result(); 
		$data['discount'] = $this->db->get_where('discount',array('discount_status'=>1))->result(); 
		$data['tax'] = $this->db->get_where('tax',array('tax_status'=>1))->result(); 
	    echo json_encode($data); 
	} */ 
 
	public function getProduct($product_id="",$warehouse_id="") 
	{ 
		$data = $this->db->select(' 
				p.product_id, 
				hsn_code.hsn_code as hsn_sac_code, 
				p.product_code, 
				p.product_lot_prefix, 
				p.product_lot_last_number, 
				p.product_code, 
				p.unit, 
				p.product_name, 
				p.size, 
				pp.cost, 
				pp.price, 
				p.alert_quantity, 
				p.product_image, 
				p.category_id, 
				p.subcategory_id, 
				p.tax_id, 
				p.quantity, 
				t.tax_value, 
				 
				cat.category_name, 
				sec_cat.category_name as sec_category_name, 
				third_cat.category_name as third_category_name') 
				 
				->from('products p') 
				->join('product_price pp','p.product_id = pp.product_id','left') 
				 
				->join('category cat','p.category_id = cat.category_id','left') 
				->join('category sec_cat','p.subcategory_id = sec_cat.category_id','left') 
				->join('category third_cat','p.second_subcategory_id = third_cat.category_id','left') 
 
 
				->join('tax t','p.tax_id = t.tax_id','left') 
				->join('inv_hsn_codes hsn_code','p.hsn_sac_code = hsn_code.hsn_code_id','left') 
				->where('p.product_id',$product_id) 
				->get() 
				->result(); 
 
		$data['discount'] = $this->db->get_where('discount',array('discount_status'=>1))->result(); 
		$data['discount_type'] = $this->db->get_where('inv_discount_type',array('dicount_type_status'=>1))->result(); 
		 
		$data['tax'] = $this->db->get_where('tax',array('tax_status'=>1))->result(); 
 
		#Lot No Start here 
		$results = $this->db->query("select increment_id from purchase_items order by increment_id desc limit 1")->result_array(); 
		if( isset($results[0]['increment_id']) && $results[0]['increment_id'] == 0 ) 
		{ 
			$incrementID = 1; 
		} 
		else 
		{ 
			$incID = isset($results[0]['increment_id']) ? $results[0]['increment_id'] : 0; 
			$incrementID = $incID + 1; 
		} 
 
		$random_user_id =  $incrementID; 
 
		$data['lot_prefix_length'] = LOT_PREFIX_LENGTH; 
		$data['lot_number_prefix'] = LOT_NUMBER_PREFIX; 
		$data['lot_starting_number'] = LOT_STARTING_NUMBER; 
		$data['lot_no'] = $random_user_id; 
		#Lot No end here 
		 
	    echo json_encode($data); 
	} 
	 
	public function getDiscountValue($id="") 
	{ 
		$data = $this->db->get_where('discount',array('discount_id'=>$id,'discount_status'=>1))->result(); 
		echo json_encode($data); 
	} 
	 
	public function getTaxValue($id="") 
	{ 
		$data = $this->db->get_where('tax',array('tax_id'=>$id,'tax_status'=>1))->result(); 
		echo json_encode($data); 
	} 
	 
	 
	public function purchaseDetails($invoice_id="") 
	{ 
		if (empty($this->user_id)) 
        { 
			redirect(base_url() . 'admin/adminLogin', 'refresh'); 
		} 
	 
		$page_data['id'] = $id=$invoice_id; 
		 
		$page_data['ManagePurchase'] = 1; 
		 
		$page_data['page_name']  = 'purchase/purchaseDetails'; 
		$page_data['page_title'] = 'Purchase Details'; 
 
		$this->load->view($this->adminTemplate, $page_data); 
	} 
 
 
	#Ajax Select Supplir Site 
	public function ajaxSelectSupplirSite()  
	{ 
		 
		if (isset($this->user_id) && $this->user_id == '') 
            redirect(base_url() . 'admin/login', 'refresh'); 
			 
        $id = $_POST["id"];		 
		if($id) 
		{			 
			$data = $this->db->query("select supplier_site_id,site_name from supplier_sites  
			where supplier_id='".$id."' ")->result_array(); 
 
			$data1 = $this->db->query("select users.state_id,supplier_state.state_number from users  
 
			left join state as supplier_state on supplier_state.state_id = users.state_id 
 
			where user_id='".$id."' ")->result_array(); 
			 
			#print_r(ucfirst($data1[0]["state_number"])); 
 
			if( count($data) > 0) 
			{ 
				echo '<option value="">- Select Supplier Site -</option>'; 
				foreach($data as $val) 
				{ 
					echo '<option value="'.$val['supplier_site_id'].'">'.ucfirst($val['site_name']).'</option>'; 
				} 
			}else 
			{ 
				echo '<option value="">No supplier site under this supplier!</option>'; 
			} 
		} 
		die; 
    } 
 
	#Ajax Select Supplir Site 
	public function ajaxSelectSupplirState()  
	{ 
		 
		if (isset($this->user_id) && $this->user_id == '') 
            redirect(base_url() . 'admin/login', 'refresh'); 
			 
        $id = $_POST["id"];		 
		if($id) 
		{			 
			$data1 = $this->db->query("select users.state_id,supplier_state.state_number from users  
 
			left join state as supplier_state on supplier_state.state_id = users.state_id 
 
			where user_id='".$id."' ")->result_array(); 
			 
			echo $data1[0]["state_number"]; 
		} 
		die; 
    } 
 
	# Ajax  Change 
	public function ajaxSelectProducts()  
	{ 
        $id = $_POST["id"];		 
		if($id) 
		{		 
			$productQuery = "select products.product_id,products.product_code,products.product_name from inv_assign_product_locator_line  
			 
				left join inv_assign_product_locator_header on  
				inv_assign_product_locator_header.header_id = inv_assign_product_locator_line.header_id  
			 
				left join products on  
					products.product_id = inv_assign_product_locator_line.product_id  
				 
				where  
					inv_assign_product_locator_header.warehouse_id='".$id."' and  
					inv_assign_product_locator_header.assign_status=1 and  
					inv_assign_product_locator_line.assign_line_status=1 and  
					products.product_status=1  
					group by inv_assign_product_locator_line.product_id;"; 
							 
			$data =  $this->db->query($productQuery)->result_array(); 
		 
			if( count($data) > 0) 
			{ 
				echo '<option value="">- Select Product -</option>'; 
				foreach($data as $val) 
				{ 
					echo '<option value="'.$val['product_id'].'">'.ucfirst($val['product_code']).' - '.ucfirst($val['product_name']).'</option>'; 
				} 
			} 
			else 
			{ 
				echo '<option value="">No products under this warehouse!</option>'; 
			} 
		} 
		die; 
    } 
 
	public function viewApprovals($id="") 
	{ 
		if (empty($this->user_id)) 
        { 
			redirect(base_url() . 'admin/adminLogin', 'refresh'); 
		} 
		$page_data['ManageProject'] = 1; 
		$page_data['id'] = $id; 
 
		$page_data['page_name']  = 'purchase/viewApprovals'; 
		$page_data['page_title'] = 'Purchase Order Approval'; 
 
		if(isset($_POST["approval_status_btn"])) 
		{ 
			#"Approver not Found for this Request Amount start here 
			$approvalsQry = "select org_approval_line.level_id,org_approval_line.amount from org_approval_line  
				left join org_approval_header on 
					org_approval_header.header_id = org_approval_line.header_id 
				where  
					org_approval_line.approver_type = 1 
					 
					order by level_id desc limit 0,1"; 
			$getApprovals = $this->db->query($approvalsQry)->result_array(); 
 
			$finalApproverAmount = isset($getApprovals[0]["amount"]) ? $getApprovals[0]["amount"] : 0; 
			$finalApproverLevelID = isset($getApprovals[0]["level_id"]) ? $getApprovals[0]["level_id"] : 0; 
 
			$levelID = isset($_POST['level_id']) ? $_POST['level_id'] : 0; 
			$approvalAmount = isset($_POST['approval_amount']) ? $_POST['approval_amount'] : 0; 
 
			/* $prAmount = "select gross_total from purchase_items where purchase_id='".$id."' "; 
			$getprAmount = $this->db->query($prAmount)->result_array(); */ 
		 
			$prAmount = "select total from purchases where purchase_id='".$id."' "; 
			$getprAmount = $this->db->query($prAmount)->result_array(); 
 
			$prTotalAmount = 0; 
 
			foreach($getprAmount as $prAmount) 
			{ 
				#$prTotalAmount += $prAmount["gross_total"]; 
				$prTotalAmount += $prAmount["total"]; 
			} 
 
			if( $finalApproverLevelID == $levelID && $finalApproverAmount < $prTotalAmount ) 
			{ 
				$this->session->set_flashdata('error_message' , "Approver not found for this Request Amount!"); 
				redirect($_SERVER['HTTP_REFERER'], 'refresh'); 
			} 
			#"Approver not Found for this Request Amount end here 
 
 
			$re_request_id = isset($_POST["re_request_id"]) ? $_POST["re_request_id"] : 0; 
 
			$chkExistQry = "select approval_status_id from org_approval_status where  
				request_id='".$id."' and  
					user_id='".$this->user_id."' and  
						level_id='".$levelID."' and  
							approval_type = 1 and  
								submit_level = 0 
				 "; 
			$chkExist = $this->db->query($chkExistQry)->result_array(); 
			 
            if ( count($chkExist) == 0 )  #Insert 
			{ 
				$data = array( 
                    "request_id"         => $id, 
                    "user_id"            => $this->user_id, 
                    "level_id"           => $levelID, 
                    "approval_status"    => $_POST["approval_status"], 
                    "approval_remarks"   => $_POST["approval_remarks"], 
                    "approval_type"      => 1, 
                    "re_request_id"      => $re_request_id, 
                    "approval_date"      => time() 
                ); 
 
                $this->db->insert('org_approval_status', $data); 
                $purchase_id = $this->db->insert_id(); 
 
                if ($purchase_id)  
				{ 
					if($_POST["approval_status"] == 2 || $_POST["approval_status"] == 3) #2=>Rejected, 3=>Need More Information 
					{ 
						$purchaseData["po_status"] = 7; #Rejected 
                        $this->db->where('purchase_id', $id); 
                        $result = $this->db->update('purchases', $purchaseData); 
					} 
 
                    if ($levelID == 1 && $_POST["approval_status"] == 1)  
					{   
						#1st Level 
                        $purchaseData["po_status"] = 2; #InProcess 
                        $this->db->where('purchase_id', $id); 
                        $result = $this->db->update('purchases', $purchaseData); 
                    } 
 
					 
				} 
            } 
			else #Update 
			{ 
				$data = array( 
                    #"request_id"         => $id, 
                    #"user_id"            => $this->user_id, 
                    #"level_id"           => $levelID, 
                    "approval_status"    => $_POST["approval_status"], 
                    "approval_remarks"   => $_POST["approval_remarks"], 
                    #"approval_type"      => 1, 
                    #"approval_date"      => time() 
                ); 
 
				$this->db->where('request_id', $id); 
				$this->db->where('user_id', $this->user_id); 
				$this->db->where('level_id', $levelID); 
				$result = $this->db->update('org_approval_status', $data); 
			} 
 
			#Update Approval Datas start here 
			$approvalLevelQry = "select line_id from org_approval_line  
				where approver_type = 1"; 
			$getApprovalLevel = $this->db->query($approvalLevelQry)->result_array(); 
			$levelCount  = count($getApprovalLevel); 
			 
			$approvalStatusQry = "select approval_status_id from org_approval_status  
			where  
				request_id = '".$id."' and 
					approval_type = 1 and  
						submit_level = 0"; 
			$getApprovalStatus = $this->db->query($approvalStatusQry)->result_array(); 
			$approvalLevelCount  = count($getApprovalStatus); 
 
			$checkaRejectionReqQry = "select approval_status_id from org_approval_status  
			where  
				request_id = '".$id."' and 
					approval_type = 1 and 
						approval_status = 2 and 
							submit_level = 0 
				"; 
			$checkaRejectionReq = $this->db->query($checkaRejectionReqQry)->result_array(); 
 
			$rejectionCount = count($checkaRejectionReq); 
 
			if ($levelCount == $approvalLevelCount)  
			{ 
				if($rejectionCount == 0) 
				{ 
					if($_POST["approval_status"] == 2 || $_POST["approval_status"] == 3) #2=>Rejected, 3=>Need More Information 
					{ 
						$purchaseData["po_status"] = 7; 
					}else{ 
						$purchaseData["po_status"] = 3; 
					} 
 
					$this->db->where('purchase_id', $id); 
					$result = $this->db->update('purchases', $purchaseData); 
 
					#Update Rerquest Data 
					$ReRequestData["request_status"] = $_POST["approval_status"]; 
					$this->db->where('re_request_id', $re_request_id); 
					$this->db->where('request_id', $id); 
					$this->db->where('request_type', 1); 
					$result = $this->db->update('pr_po_rerequest', $ReRequestData); 
 
					/*$submit_levelData["submit_level"] =1; //all levels Completed 
					$this->db->where('submit_level !=', 1); 
					$this->db->where('request_id', $id); 
					$result = $this->db->update('org_approval_status', $submit_levelData);*/ 
				} 
			} 
			#Update Approval Datas start here 
 
			if( $prTotalAmount <= $approvalAmount && $_POST["approval_status"] == 1 ) #5015==20000 
			{ 
				#$purchaseData1["po_status"] = 3; #Approved 
 
				if($_POST["approval_status"] == 2 || $_POST["approval_status"] == 3) #2=>Rejected, 3=>Need More Information 
				{ 
					$purchaseData1["po_status"] = 7; 
				} 
				else 
				{ 
					$purchaseData1["po_status"] = 3; 
				} 
 
				$this->db->where('purchase_id', $id); 
				$result = $this->db->update('purchases', $purchaseData1); 
			} 
 
			$this->session->set_flashdata('flash_message' , "Approval status updated successfully!"); 
			redirect(base_url() . 'purchase/viewApprovals/'.$id, 'refresh'); 
		} 
		 
		$this->load->view($this->adminTemplate, $page_data); 
	} 
 
	public function detailedViewApprovals($id="") 
	{ 
		if (empty($this->user_id)) 
        { 
			redirect(base_url() . 'admin/adminLogin', 'refresh'); 
		} 
		$page_data['manageApproval'] = 1; 
		$page_data['id'] = $id; 
 
		$page_data['page_name']  = 'purchase/detailedViewApprovals'; 
		$page_data['page_title'] = 'Purchase Order Approvals'; 
 
		$this->load->view($this->adminTemplate, $page_data); 
	} 
	 
	function ManagePurchaseReturn($type = '', $id = '', $status = '') 
    { 
		if (empty($this->user_id)) 
        { 
			redirect(base_url() . 'admin/adminLogin', 'refresh'); 
		} 
	 
		$page_data['type'] = $type; 
		$page_data['id'] = $id; 
		 
		$page_data['ManagePurchaseReturn'] = 1; 
		$page_data['page_name']  = 'purchase/ManagePurchaseReturn'; 
		$page_data['page_title'] = 'Purchase Return'; 
		 
		if(isset($_POST['delete']) && isset($_POST['checkbox'])) 
		{ 
			$cnt=array(); 
			$cnt=count($_POST['checkbox']); 
			 
			for($i=0;$i<$cnt;$i++) 
			{ 
				$del_id=$_POST['checkbox'][$i]; 
				  
				$this->db->where('purchase_id', $del_id); 
				$this->db->delete('purchase_items'); 
				 
				$this->db->where('purchase_id', $del_id); 
				$this->db->delete('purchases'); 
			} 
			$this->session->set_flashdata('flash_message' , "Purchase deleted successfully!"); 
			redirect($_SERVER['HTTP_REFERER'], 'refresh'); 
		} 
		 
		switch($type) 
		{ 
			case "add": #View 
				$page_data['warehouse'] = $this->purchase_model->getWarehouse(); 
				 
				if($_POST) 
				{ 
					$data1['invoice_add_date'] = $this->input->post('date'); 
					 
					$invoice_add_date = strtotime($data1['invoice_add_date']); 
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date)); 
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020 
					 
					$warehouse_id = $this->input->post('warehouse'); 
 
					$po_status = 1; 
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0; 
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0; 
					 
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0) 
					{ 
					    $total_tax = $_POST['total_tax']; 
					} 
					else 
					{ 
					    $total_tax = 0; 
					} 
					 
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0) 
					{ 
					    $total_discount = $_POST['total_discount']; 
					} 
					else 
					{ 
					    $total_discount = 0; 
					} 
					 
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type'])) 
					{ 
						$additionalChargeType = $_POST['additional_charge_type']; 
					} 
					else 
					{ 
						$additionalChargeType = 0; 
					} 
 
					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge'])) 
					{ 
						$additionalCharge = $_POST['additional_charge']; 
					} 
					else 
					{ 
						$additionalCharge = 0; 
					} 
 
					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0; 
					 
					$data = array( 
						"date" 				      =>  date('Y-m-d',$invoice_add_date), 
						"invoice_add_date" 	      =>  $this->input->post('date'), 
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)), 
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date), 
						"warehouse_id" 		      =>  $warehouse_id, 
						"supplier_id" 		      => isset($_POST["supplier"]) ? $_POST["supplier"] : 0, 
						 
						 
						"supplier_site" 		  =>  $supplier_site, 
						"total" 			      =>  $grand_total, 
						"discount_value"	      =>  $total_discount, 
						"tax_value" 		      =>  $total_tax, 
 
						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0, 
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0, 
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0, 
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0, 
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0, 
						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0, 
						"note" 				      =>  $this->input->post('note'), 
						"tax_type" 				  =>  $tax_type, 
						"po_status" 			  =>  $po_status, #Pending 
						"created_date" 			  =>  time(), 
						"additional_charge_type"     =>  $additionalChargeType, 
						"additional_charge" 	     =>  $additionalCharge, 
					); 
					#print_r($data);exit; 
					$this->db->insert('purchases', $data); 
					$purchase_id = $this->db->insert_id(); 
					 
					if($purchase_id) 
					{ 
						#purchase ID Start here 
						$results = $this->db->query("select purchase_id,increment_id from purchases order by increment_id desc")->result_array(); 
						 
						if( count($results) == 1 ) 
						{ 
							$incrementID = 0; 
						} 
						else if( count($results) == 2 ) 
						{ 
							$incrementID = 1; 
						} 
						else 
						{ 
							$incID = isset($results[0]['increment_id']) ? $results[0]['increment_id'] : 1; 
							$incrementID = $incID + 1; 
						} 
 
						/* $random_user_id =  $incrementID; 
						$UpdateData['reference_no'] = 'RE-'.$random_user_id; 
						$UpdateData['increment_id'] = $incrementID; */ 
 
						/* 	$UpdateData['reference_no'] = PURCHASE_NUMBER_PREFIX."".str_pad($incrementID, PURCHASE_NUMBER_LENGTH, "0", STR_PAD_LEFT); 
						$UpdateData['increment_id'] = $incrementID; 
						*/ 
 
						$getPrefix = $this->db->query("select prefix_name, prefix_length, from_year, prefix_starting_number from org_prefix_length where prefix_type = 2")->result_array(); 
						$startingNumber = $getPrefix[0]['prefix_starting_number']; 
						$incNumber = $startingNumber + $incrementID; 
						$randomUserId = $getPrefix[0]['prefix_name']."".$incNumber; 
 
 
						$UpdateData['reference_no'] = $randomUserId; 
						$UpdateData['increment_id'] = $incrementID; 
 
						$this->db->where('purchase_id', $purchase_id); 
						$resultUpdateData = $this->db->update('purchases', $UpdateData); 
						#Purchase ID end here 
						 
						$PurchaseItems = $this->input->post('table_data'); 
						$js_data = json_decode($PurchaseItems); 
						 
						foreach ($js_data as $key => $value)  
						{ 
							if($value==null) 
							{ 
								 
							} 
							else 
							{ 
								$product_id = $value->product_id; 
								$quantity = $value->quantity; 
								 
								if(isset($value->expiry_date) && $value->expiry_date !="") 
								{ 
									$expiry_date1 = date("d")."-".$value->expiry_date; 
 
									$expiry_date =  date("Y-m-d",strtotime($expiry_date1)); 
								} 
								else 
								{ 
									$expiry_date = null; 
								} 
 
								/*  
								#Lot No start here 
								if(isset($value->batch_no) && $value->batch_no !=""){ 
									$batch_no = $value->batch_no; 
								}else{ 
									$batch_no = null; 
								} 
 
								if(LOT_CONTROL_LEVEL == 1) #Product 
								{ 
									$increment_id = 0; 
								} 
								else if(LOT_CONTROL_LEVEL == 2) #Org 
								{ 
									$increment_id = isset($value->increment_id) ? $value->increment_id : 0; 
								} #Lot No end here 
								*/ 
 
								$data1 = array( 
									#"increment_id"      => $increment_id, 
									"product_id"         => $value->product_id, 
									"quantity"           => $value->quantity, 
									"gross_total"        => $value->total, 
									"discount_id"        => $value->discount_id, 
									"discount_value"     => $value->discount_value, 
									"discount"           => $value->discount, 
									"tax_id"             => $value->tax_id, 
									"tax_value"          => $value->tax_value, 
									"tax"                => $value->tax, 
									"cost"               => $value->cost, 
									#"batch_no"          => $batch_no, 
									#"expiry_date"       => $expiry_date, 
									"purchase_id"        => $purchase_id, 
									"purchase_item_date" => time(), 
 
									"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"", 
								); 
								 
 
								#add Product in warehouse start here 
								/* $warehouse_data = array( 
									"product_id"   => $value->product_id, 
									"warehouse_id" => $warehouse_id, 
									"quantity"     => $value->quantity 
								); 
								 
								$this->purchase_model->addProductInWarehouse($product_id,$quantity,$warehouse_id,$warehouse_data); 
						 		*/ 
								#add Product in warehouse end here 
								 
								$this->db->insert('purchase_items', $data1); 
								$purchase_items  = $this->db->insert_id(); 
							} 
						} 
						 
						#getPR Amount start here 
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$purchase_id."'"; 
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array(); 
 
						$totalAmount = 0; 
						foreach($getPurchaseItems as $purchaseItems) 
						{ 
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"]; 
						} 
 
						$reRequestData = array( 
							"request_id"     => $purchase_id, 
							"request_status" => $po_status, 
							"request_type"   => 1, //Purchase Order 
							"request_date"   => time(), 
							"total_amount"   => $totalAmount, 
							"created_by"     => $this->user_id, 
						); 
 
						$this->db->insert('pr_po_rerequest', $reRequestData); 
						$rerequest_id = $this->db->insert_id(); 
						#getPR Amount end here 
 
						$this->session->set_flashdata('flash_message' , "Purchase order created successfully!"); 
						redirect(base_url() . 'purchase/ManagePurchaseReturn', 'refresh'); 
					} 
				} 
			break; 
			 
			case "edit": #edit 
				$page_data['warehouse'] = $this->purchase_model->getWarehouse();  
				$page_data['data'] = $this->purchase_model->getRecord($id); 
				 
				$page_data['discount'] = $this->purchase_model->getDiscount(); 
				$page_data['tax'] = $this->purchase_model->getTax(); 
				 
				foreach ($page_data['data'] as $key)  
				{ 
					$purchase_id = $key->purchase_id; 
					$warehouse_id = $key->warehouse_id; 
					$page_data['items'] = $this->purchase_model->getPurchaseItems($purchase_id,$warehouse_id);	 
				} 
 
				$page_data['purchase_id'] = $purchase_id = $id; 
				 
				if($_POST) 
				{ 
					$data1['invoice_add_date'] = $this->input->post('date'); 
					 
					$invoice_add_date = strtotime($data1['invoice_add_date']); 
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date)); 
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020 
					 
					$warehouse_id = $this->input->post('warehouse'); 
 
					$purchase_request_type = $this->input->post('purchase_request_type'); 
					 
					if( $status == "re_request" ) 
					{ 
						$po_status = 1; #Draft 
					} 
					else 
					{ 
						$po_status = 1; 
					} 
					 
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0; 
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0; 
					 
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0) 
					{ 
					    $total_tax = $_POST['total_tax']; 
					} 
					else 
					{ 
					    $total_tax = 0; 
					} 
					 
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0) 
					{ 
					    $total_discount = $_POST['total_discount']; 
					} 
					else 
					{ 
					    $total_discount = 0; 
					} 
					 
					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0; 
 
					 
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type'])) 
					{ 
						$additionalChargeType = $_POST['additional_charge_type']; 
					} 
					else 
					{ 
						$additionalChargeType = 0; 
					} 
 
					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge'])) 
					{ 
						$additionalCharge = $_POST['additional_charge']; 
					} 
					else 
					{ 
						$additionalCharge = 0; 
					} 
 
					$data = array( 
						"date" 				      =>  date('Y-m-d',$invoice_add_date), 
						"invoice_add_date" 	      =>  $this->input->post('date'), 
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)), 
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date), 
						"warehouse_id" 		      =>  $warehouse_id, 
						 
						"supplier_id" 		      =>  isset($_POST["supplier"]) ? $_POST["supplier"] : 0, 
						 
						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0, 
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0, 
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0, 
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0, 
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0, 
 
						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0, 
 
						"supplier_site" 		  =>  $supplier_site, 
						"total" 			      =>  $grand_total, 
						"discount_value"	      =>  $total_discount, 
						"tax_value" 		      =>  $total_tax, 
 
						"note" 				      =>  $this->input->post('note'), 
						"tax_type" 				  =>  $tax_type, 
						"po_status" 		      =>  $po_status, 
						"additional_charge_type"     =>  $additionalChargeType, 
						"additional_charge" 	     =>  $additionalCharge, 
					); 
					#print_r($data);exit; 
					$this->db->where('purchase_id', $id); 
					$result = $this->db->update('purchases', $data); 
					 
					if($result) 
					{ 
						$js_data = json_decode($this->input->post('table_data1'));			 
						$php_data = json_decode($this->input->post('table_data')); 
						 
						if(!empty($js_data)) 
						{ 
							foreach (array_filter($js_data) as $key => $value)  
							{ 
								if($value=='delete') 
								{ 
									 
									$product_id =  $php_data[$key]; 
									if($this->purchase_model->deletePurchaseItems($id,$product_id,$warehouse_id)) 
									{ 
										 
									} 
								} 
								else if($value==null) 
								{ 
									 
								} 
								else 
								{ 
									$product_id = $value->product_id; 
									$quantity = $value->quantity; 
 
									if(isset($value->expiry_date) && $value->expiry_date !="") 
									{ 
										$expiry_date1 = date("d")."-".$value->expiry_date; 
 
										$expiry_date =  date("Y-m-d",strtotime($expiry_date1)) ; 
									} 
									else 
									{ 
										$expiry_date = null; 
									} 
 
	 
									/*  
									#Lot No start here 
									if(isset($value->batch_no) && $value->batch_no !=""){ 
										$batch_no = $value->batch_no; 
									}else{ 
										$batch_no = null; 
									} 
 
									if(LOT_CONTROL_LEVEL == 1) #Product 
									{ 
										$increment_id = 0; 
									} 
									else if(LOT_CONTROL_LEVEL == 2) #Org 
									{ 
										$increment_id = isset($value->increment_id) ? $value->increment_id : 0; 
									}  
									#Lot No end here 
									*/ 
									 
									$data = array( 
										#"increment_id"     => $increment_id, 
										"product_id"       => $value->product_id, 
										"quantity"         => $value->quantity, 
										"gross_total"      => $value->total, 
										"discount_id"      => $value->discount_id, 
										"discount_value"   => $value->discount_value, 
										"discount"         => $value->discount, 
										"tax_id"           => $value->tax_id, 
										"tax_value"        => $value->tax_value, 
										"tax"              => $value->tax, 
										"cost"             => $value->cost, 
										#"expiry_date"      => $expiry_date, 
										#"batch_no"         => $batch_no, #Lot No 
										"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"", 
										"purchase_id"      => $id 
									); 
 
									$warehouse_data = array( 
										"product_id"     => $value->product_id, 
										"warehouse_id"   => $warehouse_id, 
										"quantity"       => $value->quantity 
									); 
 
									if($this->purchase_model->addUpdatePurchaseItem($id,$product_id,$warehouse_id,$quantity,$data,$warehouse_data)) 
									{ 
										 
									} 
									else 
									{ 
 
									} 
								} 
							} 
						} 
 
						#getPR Amount start here 
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$id."'"; 
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array(); 
 
						$totalAmount = 0; 
						foreach($getPurchaseItems as $purchaseItems) 
						{ 
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"]; 
						} 
						#getPR Amount end here 
						 
						if ( $status == "re_request" ) #PR Re Request 
						{ 
							$reRequestData = array( 
								"request_id"     => $id, 
								"request_status" => $po_status, 
								"request_type"   => 1, 
								"request_date"   => time(), 
								"total_amount"   => $totalAmount, 
								"created_by"     => $this->user_id, 
							); 
 
							$this->db->insert('pr_po_rerequest', $reRequestData); 
							$rerequest_id = $this->db->insert_id(); 
 
							$submit_levelData["submit_level"] =1; //all levels Completed 
							$this->db->where('submit_level', 0); 
							//$this->db->where('submit_level !=', 1); 
							$this->db->where('request_id', $id); 
							$this->db->where('approval_type', 1); 
							$result = $this->db->update('org_approval_status', $submit_levelData); 
						} 
						#re_request end here 
						 
						$this->session->set_flashdata('flash_message' , "Purchase order updated successfully!"); 
						redirect(base_url() . 'purchase/ManagePurchaseReturn/'.$id, 'refresh'); 
					} 
				} 
			break; 
			 
			case "delete": #Delete 
				$this->db->where('sales_id', $id); 
				$this->db->delete('sales'); 
				 
				$this->db->where('sales_id', $id); 
				$this->db->delete('sales_items'); 
				 
				/* $this->db->where('invoice_id', $id); 
				$this->db->delete('invoice_payment'); */ 
				 
				$this->session->set_flashdata('flash_message' , "Sale deleted successfully!"); 
				redirect(base_url() . 'sales/ManageSales', 'refresh'); 
			break; 
 
			case "approval_status": #approval_status 
				if($status == 5) #Close 
				{ 
					$successMsg = "Purchase order closed successfully!"; 
				} 
				else if($status == 4) #Cancel 
				{ 
					$successMsg = "Purchase order cancelled successfully!"; 
				} 
  
				$updateData["po_status"] = $status; 
 
				$this->db->where('purchase_id', $id); 
				 
				$result = $this->db->update('purchases', $updateData); 
 
				$this->session->set_flashdata('flash_message' , $successMsg); 
				redirect(base_url() . 'purchase/ManagePurchase', 'refresh'); 
			break; 
 
			default : #Manage 
				$page_data["totalRows"] = $totalRows = $this->purchase_model->getManagePurchaseCount(); 
	 
				if(!empty($_SESSION['PAGE'])) 
				{$limit = $_SESSION['PAGE']; 
				}else{$limit = 10;} 
				 
				if (!empty($_GET['keywords'])) { 
					$base_url = base_url('purchase/ManagePurchase?keywords='.$_GET['keywords']); 
				} else { 
					$base_url = base_url('purchase/ManagePurchase?keywords='); 
				} 
				 
				$config = PaginationConfig($base_url,$totalRows,$limit); 
				$this->pagination->initialize($config); 
				$str_links = $this->pagination->create_links(); 
				$page_data['pagination'] = explode('', $str_links); 
				$offset = 0; 
				if (!empty($_GET['per_page'])) { 
					$pageNo = $_GET['per_page']; 
					$offset = ($pageNo - 1) * $limit; 
				} 
				 
				if($offset == 1 || $offset== "" || $offset== 0){ 
					$page_data["first_item"] = 1; 
				}else{ 
					$page_data["first_item"] = $offset + 1; 
				} 
				 
				$page_data['resultData']  = $result= $this->purchase_model->getManagePurchase($limit, $offset); 
				 
				#show start and ending Count 
				$total_counts = $total_count= 0; 
				$pages=$page_data["starting"] = $page_data["ending"]=""; 
				$pageno = isset($pageNo) ? $pageNo :""; 
				 
				if( $totalRows == 0 ){ 
					$page_data["starting"] = 0; 
				}else if( $pageno==1 || $pageno=="" ){ 
					$page_data["starting"] = 1; 
				}else{ 
					$pages = $pageno-1; 
					$total_count = $pages * $config["per_page"]; 
					$page_data["starting"] = ( $config["per_page"] * $pages )+1; 
				} 
				 
				$total_counts = $total_count + count($result); 
				$page_data["ending"]  = $total_counts; 
				#show start and ending Count end 
			break; 
		}	 
		$this->load->view($this->adminTemplate, $page_data); 
	} 
 
	public function purchaseReturnDetails($invoice_id="") 
	{ 
		if (empty($this->user_id)) 
        { 
			redirect(base_url() . 'admin/adminLogin', 'refresh'); 
		} 
	 
		$page_data['id'] = $id=$invoice_id; 
		 
		$page_data['ManagePurchaseReturn'] = 1; 
		 
		$page_data['page_name']  = 'purchase/purchaseReturnDetails'; 
		$page_data['page_title'] = 'Purchase Return Details'; 
 
		$this->load->view($this->adminTemplate, $page_data); 
	} 
	 
} 
?> 

Did this file decode correctly?

Original Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include_once('vendor/autoload.php');
class Purchase extends CI_Controller 
{
	function __construct()
	{
		parent::__construct();
		$this->load->database();
        $this->load->library('session');
      
        #Cache Control
		$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
		$this->output->set_header('Pragma: no-cache');
	}
	
	function ManagePurchase($type = '', $id = '', $status = '')
    {
   	    //echo phpinfo();exit;
    
		if (empty($this->user_id))
        {
			redirect(base_url() . 'admin/adminLogin', 'refresh');
		}
	
		$page_data['type'] = $type;
		$page_data['id'] = $id;
		
		$page_data['ManagePurchase'] = 1;
		$page_data['page_name']  = 'purchase/ManagePurchase';
		$page_data['page_title'] = 'Purchase Orders';
		
		if(isset($_POST['delete']) && isset($_POST['checkbox']))
		{
			$cnt=array();
			$cnt=count($_POST['checkbox']);
			
			for($i=0;$i<$cnt;$i++)
			{
				$del_id=$_POST['checkbox'][$i];
				 
				$this->db->where('purchase_id', $del_id);
				$this->db->delete('purchase_items');
				
				$this->db->where('purchase_id', $del_id);
				$this->db->delete('purchases');
			}
			$this->session->set_flashdata('flash_message' , "Purchase deleted successfully!");
			redirect($_SERVER['HTTP_REFERER'], 'refresh');
		}
		
		switch($type)
		{
			case "add": #View
				$page_data['warehouse'] = $this->purchase_model->getWarehouse();
				
				if($_POST)
				{
					$data1['invoice_add_date'] = $this->input->post('date');
					
					$invoice_add_date = strtotime($data1['invoice_add_date']);
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date));
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020
					
					$warehouse_id = $this->input->post('warehouse');

					$po_status = 1;
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0;
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0;
					
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0)
					{
					    $total_tax = $_POST['total_tax'];
					}
					else
					{
					    $total_tax = 0;
					}
					
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0)
					{
					    $total_discount = $_POST['total_discount'];
					}
					else
					{
					    $total_discount = 0;
					}
					
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type']))
					{
						$additionalChargeType = $_POST['additional_charge_type'];
					}
					else
					{
						$additionalChargeType = 0;
					}

					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge']))
					{
						$additionalCharge = $_POST['additional_charge'];
					}
					else
					{
						$additionalCharge = 0;
					}

					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0;
					
					$data = array(
						"date" 				      =>  date('Y-m-d',$invoice_add_date),
						"invoice_add_date" 	      =>  $this->input->post('date'),
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)),
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date),
						"warehouse_id" 		      =>  $warehouse_id,
						"supplier_id" 		      => isset($_POST["supplier"]) ? $_POST["supplier"] : 0,
						
						
						"supplier_site" 		  =>  $supplier_site,
						"total" 			      =>  $grand_total,
						"discount_value"	      =>  $total_discount,
						"tax_value" 		      =>  $total_tax,

						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0,
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0,
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0,
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0,
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0,
						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0,
						"note" 				      =>  $this->input->post('note'),
						"tax_type" 				  =>  $tax_type,
						"po_status" 			  =>  $po_status, #Pending
						"created_date" 			  =>  time(),
						"additional_charge_type"     =>  $additionalChargeType,
						"additional_charge" 	     =>  $additionalCharge,
					);
					#print_r($data);exit;
					$this->db->insert('purchases', $data);
					$purchase_id = $this->db->insert_id();
					
					if($purchase_id)
					{
						#purchase ID Start here
						$sequenceQry = "select purchase_id,increment_id from purchases 
								where fin_year_status = 0 order by increment_id desc";

						$results = $this->db->query($sequenceQry)->result_array();
						
						if( count($results) == 1 )
						{
							$incrementID = 0;
						}
						else if( count($results) == 2 )
						{
							$incrementID = 1;
						}
						else
						{
							$incID = isset($results[0]['increment_id']) ? $results[0]['increment_id'] : 1;
							$incrementID = $incID + 1;
						}

						/* $random_user_id =  $incrementID;
						$UpdateData['reference_no'] = 'RE-'.$random_user_id;
						$UpdateData['increment_id'] = $incrementID; */

						/* 	$UpdateData['reference_no'] = PURCHASE_NUMBER_PREFIX."".str_pad($incrementID, PURCHASE_NUMBER_LENGTH, "0", STR_PAD_LEFT);
						$UpdateData['increment_id'] = $incrementID;
						*/

						$getPrefix = $this->db->query("select prefix_name, prefix_length, from_year, prefix_starting_number from org_prefix_length where prefix_type = 2")->result_array();
						$startingNumber = $getPrefix[0]['prefix_starting_number'];
						$incNumber = $startingNumber + $incrementID;
						$randomUserId = $getPrefix[0]['prefix_name']."".$incNumber;


						$UpdateData['reference_no'] = $randomUserId;
						$UpdateData['increment_id'] = $incrementID;

						$this->db->where('purchase_id', $purchase_id);
						$resultUpdateData = $this->db->update('purchases', $UpdateData);
						#Purchase ID end here
						
						$PurchaseItems = $this->input->post('table_data');
						$js_data = json_decode($PurchaseItems);
                    
                   		if(!empty($js_data))
                        {
						foreach ($js_data as $key => $value) 
						{
							if($value==null)
							{
								
							}
							else
							{
								$product_id = $value->product_id;
								$quantity = $value->quantity;
								
								if(isset($value->expiry_date) && $value->expiry_date !="")
								{
									$expiry_date1 = date("d")."-".$value->expiry_date;

									$expiry_date =  date("Y-m-d",strtotime($expiry_date1));
								}
								else
								{
									$expiry_date = null;
								}

								/* 
								#Lot No start here
								if(isset($value->batch_no) && $value->batch_no !=""){
									$batch_no = $value->batch_no;
								}else{
									$batch_no = null;
								}

								if(LOT_CONTROL_LEVEL == 1) #Product
								{
									$increment_id = 0;
								}
								else if(LOT_CONTROL_LEVEL == 2) #Org
								{
									$increment_id = isset($value->increment_id) ? $value->increment_id : 0;
								} #Lot No end here
								*/

								$data1 = array(
									#"increment_id"      => $increment_id,
									"product_id"         => $value->product_id,
									"quantity"           => $value->quantity,
									"gross_total"        => $value->total,
									"discount_id"        => $value->discount_id,
									"discount_value"     => $value->discount_value,
									"discount"           => $value->discount,
									"tax_id"             => $value->tax_id,
									"tax_value"          => $value->tax_value,
									"tax"                => $value->tax,
									"cost"               => $value->cost,
									#"batch_no"          => $batch_no,
									#"expiry_date"       => $expiry_date,
									"purchase_id"        => $purchase_id,
									"purchase_item_date" => time(),

									"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"",
								);
								

								#add Product in warehouse start here
								/* $warehouse_data = array(
									"product_id"   => $value->product_id,
									"warehouse_id" => $warehouse_id,
									"quantity"     => $value->quantity
								);
								
								$this->purchase_model->addProductInWarehouse($product_id,$quantity,$warehouse_id,$warehouse_data);
						 		*/
								#add Product in warehouse end here
								
								$this->db->insert('purchase_items', $data1);
								$purchase_items  = $this->db->insert_id();
							}
						}
                        }
						
						#getPR Amount start here
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$purchase_id."'";
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array();

						$totalAmount = 0;
						foreach($getPurchaseItems as $purchaseItems)
						{
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"];
						}

						$reRequestData = array(
							"request_id"     => $purchase_id,
							"request_status" => $po_status,
							"request_type"   => 1, //Purchase Order
							"request_date"   => time(),
							"total_amount"   => $totalAmount,
							"created_by"     => $this->user_id,
						);

						$this->db->insert('pr_po_rerequest', $reRequestData);
						$rerequest_id = $this->db->insert_id();
						#getPR Amount end here

						#Audit Trails Start here
						/* $tableName = purchase_tbl;
						$createdMessage = $UpdateData['reference_no']." created successfully!";
						auditTrails($createdMessage,$tableName,$type); */
						#Audit Trails end here

						$this->session->set_flashdata('flash_message' , "Purchase order created successfully!");
						redirect(base_url() . 'purchase/ManagePurchase', 'refresh');
					}
				}
			break;
			
			case "edit": #edit
				$page_data['warehouse'] = $this->purchase_model->getWarehouse(); 
				$page_data['data'] = $this->purchase_model->getRecord($id);
				
				$page_data['discount'] = $this->purchase_model->getDiscount();
				$page_data['tax'] = $this->purchase_model->getTax();
				
				foreach ($page_data['data'] as $key) 
				{
					$purchase_id = $key->purchase_id;
					$warehouse_id = $key->warehouse_id;
					$page_data['items'] = $this->purchase_model->getPurchaseItems($purchase_id,$warehouse_id);	
				}

				$page_data['purchase_id'] = $purchase_id = $id;
				
                if($_POST)
				{

				   // print_r($_POST);exit;

					$data1['invoice_add_date'] = $this->input->post('date');
					
					$invoice_add_date = strtotime($data1['invoice_add_date']);
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date));
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020
					
					$warehouse_id = $this->input->post('warehouse');

					$purchase_request_type = $this->input->post('purchase_request_type');
					
					if( $status == "re_request" )
					{
						$po_status = 1; #Draft
					}
					else
					{
						$po_status = 1;
					}
					
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0;
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0;
					
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0)
					{
					    $total_tax = $_POST['total_tax'];
					}
					else
					{
					    $total_tax = 0;
					}
					
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0)
					{
					    $total_discount = $_POST['total_discount'];
					}
					else
					{
					    $total_discount = 0;
					}
					
					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0;

					
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type']))
					{
						$additionalChargeType = $_POST['additional_charge_type'];
					}
					else
					{
						$additionalChargeType = 0;
					}

					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge']))
					{
						$additionalCharge = $_POST['additional_charge'];
					}
					else
					{
						$additionalCharge = 0;
					}
					
					
					$data = array(
						"date" 				      =>  date('Y-m-d',$invoice_add_date),
						"invoice_add_date" 	      =>  $this->input->post('date'),
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)),
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date),
						"warehouse_id" 		      =>  $warehouse_id,
						
						"supplier_id" 		      =>  isset($_POST["supplier"]) ? $_POST["supplier"] : 0,
						
						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0,
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0,
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0,
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0,
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0,

						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0,

						"supplier_site" 		  =>  $supplier_site,
						"total" 			      =>  $grand_total,
						"discount_value"	      =>  $total_discount,
						"tax_value" 		      =>  $total_tax,

						"note" 				      =>  $this->input->post('note'),
						"tax_type" 				  =>  $tax_type,
						"po_status" 		      =>  $po_status,
						"additional_charge_type"     =>  $additionalChargeType,
						"additional_charge" 	     =>  $additionalCharge,
					);
					#print_r($data);exit;
					$this->db->where('purchase_id', $id);
					$result = $this->db->update('purchases', $data);
					
					if($result)
					{
						$js_data = json_decode($this->input->post('table_data1'));			
						$php_data = json_decode($this->input->post('table_data'));
                    
                    	#print_r($_POST["table_data"]);exit;
						
						if(!empty($js_data))
						{
							foreach (array_filter($js_data) as $key => $value) 
							{
								if($value=='delete')
								{
									
									$product_id =  $php_data[$key];
									if($this->purchase_model->deletePurchaseItems($id,$product_id,$warehouse_id))
									{
										
									}
								}
								else if($value==null)
								{
									
								}
								else
								{
									$product_id = $value->product_id;
									$quantity = $value->quantity;

									if(isset($value->expiry_date) && $value->expiry_date !="")
									{
										$expiry_date1 = date("d")."-".$value->expiry_date;

										$expiry_date =  date("Y-m-d",strtotime($expiry_date1)) ;
									}
									else
									{
										$expiry_date = null;
									}

	
									/* 
									#Lot No start here
									if(isset($value->batch_no) && $value->batch_no !=""){
										$batch_no = $value->batch_no;
									}else{
										$batch_no = null;
									}

									if(LOT_CONTROL_LEVEL == 1) #Product
									{
										$increment_id = 0;
									}
									else if(LOT_CONTROL_LEVEL == 2) #Org
									{
										$increment_id = isset($value->increment_id) ? $value->increment_id : 0;
									} 
									#Lot No end here
									*/
									
									$data = array(
										#"increment_id"     => $increment_id,
										"product_id"       => $value->product_id,
										"quantity"         => $value->quantity,
										"gross_total"      => $value->total,
										"discount_id"      => $value->discount_id,
										"discount_value"   => $value->discount_value,
										"discount"         => $value->discount,
										"tax_id"           => $value->tax_id,
										"tax_value"        => $value->tax_value,
										"tax"              => $value->tax,
										"cost"             => $value->cost,
										#"expiry_date"      => $expiry_date,
										#"batch_no"         => $batch_no, #Lot No
										"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"",
										"purchase_id"      => $id
									);

									$warehouse_data = array(
										"product_id"     => $value->product_id,
										"warehouse_id"   => $warehouse_id,
										"quantity"       => $value->quantity
									);

									if($this->purchase_model->addUpdatePurchaseItem($id,$product_id,$warehouse_id,$quantity,$data,$warehouse_data))
									{
										
									}
									else
									{

									}
								}
							}
						}

						#getPR Amount start here
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$id."'";
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array();

						$totalAmount = 0;
						foreach($getPurchaseItems as $purchaseItems)
						{
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"];
						}
						#getPR Amount end here
						
						if ( $status == "re_request" ) #PR Re Request
						{
							$reRequestData = array(
								"request_id"     => $id,
								"request_status" => $po_status,
								"request_type"   => 1,
								"request_date"   => time(),
								"total_amount"   => $totalAmount,
								"created_by"     => $this->user_id,
							);

							$this->db->insert('pr_po_rerequest', $reRequestData);
							$rerequest_id = $this->db->insert_id();

							$submit_levelData["submit_level"] =1; //all levels Completed
							$this->db->where('submit_level', 0);
							//$this->db->where('submit_level !=', 1);
							$this->db->where('request_id', $id);
							$this->db->where('approval_type', 1);
							$result = $this->db->update('org_approval_status', $submit_levelData);
						}
						#re_request end here
						
						$this->session->set_flashdata('flash_message' , "Purchase order updated successfully!");
						redirect(base_url() . 'purchase/ManagePurchase/'.$id, 'refresh');
					}
				}
			break;
			
			case "delete": #Delete
				$this->db->where('sales_id', $id);
				$this->db->delete('sales');
				
				$this->db->where('sales_id', $id);
				$this->db->delete('sales_items');
				
				/* $this->db->where('invoice_id', $id);
				$this->db->delete('invoice_payment'); */
				
				$this->session->set_flashdata('flash_message' , "Sale deleted successfully!");
				redirect(base_url() . 'sales/ManageSales', 'refresh');
			break;

			case "approval_status": #approval_status
				if($status == 5) #Close
				{
					$successMsg = "Purchase order closed successfully!";
				}
				else if($status == 4) #Cancel
				{
					$successMsg = "Purchase order cancelled successfully!";
				}
 
				$updateData["po_status"] = $status;

				$this->db->where('purchase_id', $id);
				
				$result = $this->db->update('purchases', $updateData);

				$this->session->set_flashdata('flash_message' , $successMsg);
				redirect(base_url() . 'purchase/ManagePurchase', 'refresh');
			break;

			default : #Manage
				$page_data["totalRows"] = $totalRows = $this->purchase_model->getManagePurchaseCount();
	
				if(!empty($_SESSION['PAGE']))
				{$limit = $_SESSION['PAGE'];
				}else{$limit = 10;}
				
				if (!empty($_GET['keywords'])) {
					$base_url = base_url('purchase/ManagePurchase?keywords='.$_GET['keywords']);
				} else {
					$base_url = base_url('purchase/ManagePurchase?keywords=');
				}
				
				$config = PaginationConfig($base_url,$totalRows,$limit);
				$this->pagination->initialize($config);
				$str_links = $this->pagination->create_links();
				$page_data['pagination'] = explode('', $str_links);
				$offset = 0;
				if (!empty($_GET['per_page'])) {
					$pageNo = $_GET['per_page'];
					$offset = ($pageNo - 1) * $limit;
				}
				
				if($offset == 1 || $offset== "" || $offset== 0){
					$page_data["first_item"] = 1;
				}else{
					$page_data["first_item"] = $offset + 1;
				}
				
				$page_data['resultData']  = $result= $this->purchase_model->getManagePurchase($limit, $offset);
				
				#show start and ending Count
				$total_counts = $total_count= 0;
				$pages=$page_data["starting"] = $page_data["ending"]="";
				$pageno = isset($pageNo) ? $pageNo :"";
				
				if( $totalRows == 0 ){
					$page_data["starting"] = 0;
				}else if( $pageno==1 || $pageno=="" ){
					$page_data["starting"] = 1;
				}else{
					$pages = $pageno-1;
					$total_count = $pages * $config["per_page"];
					$page_data["starting"] = ( $config["per_page"] * $pages )+1;
				}
				
				$total_counts = $total_count + count($result);
				$page_data["ending"]  = $total_counts;
				#show start and ending Count end
			break;
		}	
		$this->load->view($this->adminTemplate, $page_data);
	}
	
	function generatePDF($purchase_id="")
    {
		 $page_data['id'] = $id = $purchase_id;
		
		 
		/* $userQuery = "select 
			users.first_name,
			users.last_name,
			users.random_user_id,
			emp_periods.month,
			emp_periods.year
			from emp_payslip_header 
		
		left join users on 
			users.user_id = emp_payslip_header.user_id

		left join org_financial_years on 
			org_financial_years.financial_year_id = emp_payslip_header.financial_year_id
		
		left join emp_periods on 
			emp_periods.period_id = emp_payslip_header.period_id

		where emp_payslip_header.header_id='".$payslip_id."' ";
		$userDetails = $this->db->query($userQuery)->result_array();

		$random_user_id = $userDetails[0]["random_user_id"];
		$employee_name = ucfirst($userDetails[0]["first_name"])." ".ucfirst($userDetails[0]["last_name"]);
		
		$period_month = $userDetails[0]["month"];
		$year = $userDetails[0]["year"]; */
		$date = date('d-M-Y');

		ob_start();
		$html = ob_get_clean();
		$html = utf8_encode($html);
		
		$html = $this->load->view('backend/purchase/generatePurchasePDF',$page_data,true);
		$pdf_name = $date;
		$mpdf = new \Mpdf\Mpdf([
			'setAutoTopMargin' => 'stretch',
            'curlAllowUnsafeSslRequests' => true
		]);

		//$mpdf->SetHTMLHeader($this->load->view('backend/purchase/generatePurchaseHeaderPDF',$page_data,true));
		
        $mpdf->AddPage('L','','','','',7,7,7,7,7,7);
		$mpdf->WriteHTML($html);
		$mpdf->Output($pdf_name.'.pdf','I');
	}

	/* public function getProduct($product_id="")
	{
		$data = $this->db->select('p.product_id,cat.category_name,p.product_code,hsn_code.hsn_code as hsn_sac_code,p.unit,p.product_name,p.size,p.cost,p.price,p.alert_quantity,p.product_image,p.category_id,p.subcategory_id,p.tax_id,p.quantity,t.tax_value')
				->from('products p')
				->join('category cat','p.category_id = cat.category_id','left')
				->join('tax t','p.tax_id = t.tax_id','left')
				->join('inv_hsn_codes hsn_code','p.hsn_sac_code = hsn_code.hsn_code_id','left')
				->where('p.product_id',$product_id)
				->get()
				->result();
		$data['discount'] = $this->db->get_where('discount',array('discount_status'=>1))->result();
		$data['tax'] = $this->db->get_where('tax',array('tax_status'=>1))->result();
	    echo json_encode($data);
	} */

	public function getProduct($product_id="",$warehouse_id="")
	{
		$data = $this->db->select('
				p.product_id,
				hsn_code.hsn_code as hsn_sac_code,
				p.product_code,
				p.product_lot_prefix,
				p.product_lot_last_number,
				p.product_code,
				p.unit,
				p.product_name,
				p.size,
				pp.cost,
				pp.price,
				p.alert_quantity,
				p.product_image,
				p.category_id,
				p.subcategory_id,
				p.tax_id,
				p.quantity,
				t.tax_value,
				
				cat.category_name,
				sec_cat.category_name as sec_category_name,
				third_cat.category_name as third_category_name')
				
				->from('products p')
				->join('product_price pp','p.product_id = pp.product_id','left')
				
				->join('category cat','p.category_id = cat.category_id','left')
				->join('category sec_cat','p.subcategory_id = sec_cat.category_id','left')
				->join('category third_cat','p.second_subcategory_id = third_cat.category_id','left')


				->join('tax t','p.tax_id = t.tax_id','left')
				->join('inv_hsn_codes hsn_code','p.hsn_sac_code = hsn_code.hsn_code_id','left')
				->where('p.product_id',$product_id)
				->get()
				->result();

		$data['discount'] = $this->db->get_where('discount',array('discount_status'=>1))->result();
		$data['discount_type'] = $this->db->get_where('inv_discount_type',array('dicount_type_status'=>1))->result();
		
		$data['tax'] = $this->db->get_where('tax',array('tax_status'=>1))->result();

		#Lot No Start here
		$results = $this->db->query("select increment_id from purchase_items order by increment_id desc limit 1")->result_array();
		if( isset($results[0]['increment_id']) && $results[0]['increment_id'] == 0 )
		{
			$incrementID = 1;
		}
		else
		{
			$incID = isset($results[0]['increment_id']) ? $results[0]['increment_id'] : 0;
			$incrementID = $incID + 1;
		}

		$random_user_id =  $incrementID;

		$data['lot_prefix_length'] = LOT_PREFIX_LENGTH;
		$data['lot_number_prefix'] = LOT_NUMBER_PREFIX;
		$data['lot_starting_number'] = LOT_STARTING_NUMBER;
		$data['lot_no'] = $random_user_id;
		#Lot No end here
		
	    echo json_encode($data);
	}
	
	public function getDiscountValue($id="")
	{
		$data = $this->db->get_where('discount',array('discount_id'=>$id,'discount_status'=>1))->result();
		echo json_encode($data);
	}
	
	public function getTaxValue($id="")
	{
		$data = $this->db->get_where('tax',array('tax_id'=>$id,'tax_status'=>1))->result();
		echo json_encode($data);
	}
	
	
	public function purchaseDetails($invoice_id="")
	{
		if (empty($this->user_id))
        {
			redirect(base_url() . 'admin/adminLogin', 'refresh');
		}
	
		$page_data['id'] = $id=$invoice_id;
		
		$page_data['ManagePurchase'] = 1;
		
		$page_data['page_name']  = 'purchase/purchaseDetails';
		$page_data['page_title'] = 'Purchase Details';

		$this->load->view($this->adminTemplate, $page_data);
	}


	#Ajax Select Supplir Site
	public function ajaxSelectSupplirSite() 
	{
		
		if (isset($this->user_id) && $this->user_id == '')
            redirect(base_url() . 'admin/login', 'refresh');
			
        $id = $_POST["id"];		
		if($id)
		{			
			$data = $this->db->query("select supplier_site_id,site_name from supplier_sites 
			where supplier_id='".$id."' ")->result_array();

			$data1 = $this->db->query("select users.state_id,supplier_state.state_number from users 

			left join state as supplier_state on supplier_state.state_id = users.state_id

			where user_id='".$id."' ")->result_array();
			
			#print_r(ucfirst($data1[0]["state_number"]));

			if( count($data) > 0)
			{
				echo '<option value="">- Select Supplier Site -</option>';
				foreach($data as $val)
				{
					echo '<option value="'.$val['supplier_site_id'].'">'.ucfirst($val['site_name']).'</option>';
				}
			}else
			{
				echo '<option value="">No supplier site under this supplier!</option>';
			}
		}
		die;
    }

	#Ajax Select Supplir Site
	public function ajaxSelectSupplirState() 
	{
		
		if (isset($this->user_id) && $this->user_id == '')
            redirect(base_url() . 'admin/login', 'refresh');
			
        $id = $_POST["id"];		
		if($id)
		{			
			$data1 = $this->db->query("select users.state_id,supplier_state.state_number from users 

			left join state as supplier_state on supplier_state.state_id = users.state_id

			where user_id='".$id."' ")->result_array();
			
			echo $data1[0]["state_number"];
		}
		die;
    }

	# Ajax  Change
	public function ajaxSelectProducts() 
	{
        $id = $_POST["id"];		
		if($id)
		{		
			$productQuery = "select products.product_id,products.product_code,products.product_name from inv_assign_product_locator_line 
			
				left join inv_assign_product_locator_header on 
				inv_assign_product_locator_header.header_id = inv_assign_product_locator_line.header_id 
			
				left join products on 
					products.product_id = inv_assign_product_locator_line.product_id 
				
				where 
					inv_assign_product_locator_header.warehouse_id='".$id."' and 
					inv_assign_product_locator_header.assign_status=1 and 
					inv_assign_product_locator_line.assign_line_status=1 and 
					products.product_status=1 
					group by inv_assign_product_locator_line.product_id;";
							
			$data =  $this->db->query($productQuery)->result_array();
		
			if( count($data) > 0)
			{
				echo '<option value="">- Select Product -</option>';
				foreach($data as $val)
				{
					echo '<option value="'.$val['product_id'].'">'.ucfirst($val['product_code']).' - '.ucfirst($val['product_name']).'</option>';
				}
			}
			else
			{
				echo '<option value="">No products under this warehouse!</option>';
			}
		}
		die;
    }

	public function viewApprovals($id="")
	{
		if (empty($this->user_id))
        {
			redirect(base_url() . 'admin/adminLogin', 'refresh');
		}
		$page_data['ManageProject'] = 1;
		$page_data['id'] = $id;

		$page_data['page_name']  = 'purchase/viewApprovals';
		$page_data['page_title'] = 'Purchase Order Approval';

		if(isset($_POST["approval_status_btn"]))
		{
			#"Approver not Found for this Request Amount start here
			$approvalsQry = "select org_approval_line.level_id,org_approval_line.amount from org_approval_line 
				left join org_approval_header on
					org_approval_header.header_id = org_approval_line.header_id
				where 
					org_approval_line.approver_type = 1
					
					order by level_id desc limit 0,1";
			$getApprovals = $this->db->query($approvalsQry)->result_array();

			$finalApproverAmount = isset($getApprovals[0]["amount"]) ? $getApprovals[0]["amount"] : 0;
			$finalApproverLevelID = isset($getApprovals[0]["level_id"]) ? $getApprovals[0]["level_id"] : 0;

			$levelID = isset($_POST['level_id']) ? $_POST['level_id'] : 0;
			$approvalAmount = isset($_POST['approval_amount']) ? $_POST['approval_amount'] : 0;

			/* $prAmount = "select gross_total from purchase_items where purchase_id='".$id."' ";
			$getprAmount = $this->db->query($prAmount)->result_array(); */
		
			$prAmount = "select total from purchases where purchase_id='".$id."' ";
			$getprAmount = $this->db->query($prAmount)->result_array();

			$prTotalAmount = 0;

			foreach($getprAmount as $prAmount)
			{
				#$prTotalAmount += $prAmount["gross_total"];
				$prTotalAmount += $prAmount["total"];
			}

			if( $finalApproverLevelID == $levelID && $finalApproverAmount < $prTotalAmount )
			{
				$this->session->set_flashdata('error_message' , "Approver not found for this Request Amount!");
				redirect($_SERVER['HTTP_REFERER'], 'refresh');
			}
			#"Approver not Found for this Request Amount end here


			$re_request_id = isset($_POST["re_request_id"]) ? $_POST["re_request_id"] : 0;

			$chkExistQry = "select approval_status_id from org_approval_status where 
				request_id='".$id."' and 
					user_id='".$this->user_id."' and 
						level_id='".$levelID."' and 
							approval_type = 1 and 
								submit_level = 0
				 ";
			$chkExist = $this->db->query($chkExistQry)->result_array();
			
            if ( count($chkExist) == 0 )  #Insert
			{
				$data = array(
                    "request_id"         => $id,
                    "user_id"            => $this->user_id,
                    "level_id"           => $levelID,
                    "approval_status"    => $_POST["approval_status"],
                    "approval_remarks"   => $_POST["approval_remarks"],
                    "approval_type"      => 1,
                    "re_request_id"      => $re_request_id,
                    "approval_date"      => time()
                );

                $this->db->insert('org_approval_status', $data);
                $purchase_id = $this->db->insert_id();

                if ($purchase_id) 
				{
					if($_POST["approval_status"] == 2 || $_POST["approval_status"] == 3) #2=>Rejected, 3=>Need More Information
					{
						$purchaseData["po_status"] = 7; #Rejected
                        $this->db->where('purchase_id', $id);
                        $result = $this->db->update('purchases', $purchaseData);
					}

                    if ($levelID == 1 && $_POST["approval_status"] == 1) 
					{  
						#1st Level
                        $purchaseData["po_status"] = 2; #InProcess
                        $this->db->where('purchase_id', $id);
                        $result = $this->db->update('purchases', $purchaseData);
                    }

					
				}
            }
			else #Update
			{
				$data = array(
                    #"request_id"         => $id,
                    #"user_id"            => $this->user_id,
                    #"level_id"           => $levelID,
                    "approval_status"    => $_POST["approval_status"],
                    "approval_remarks"   => $_POST["approval_remarks"],
                    #"approval_type"      => 1,
                    #"approval_date"      => time()
                );

				$this->db->where('request_id', $id);
				$this->db->where('user_id', $this->user_id);
				$this->db->where('level_id', $levelID);
				$result = $this->db->update('org_approval_status', $data);
			}

			#Update Approval Datas start here
			$approvalLevelQry = "select line_id from org_approval_line 
				where approver_type = 1";
			$getApprovalLevel = $this->db->query($approvalLevelQry)->result_array();
			$levelCount  = count($getApprovalLevel);
			
			$approvalStatusQry = "select approval_status_id from org_approval_status 
			where 
				request_id = '".$id."' and
					approval_type = 1 and 
						submit_level = 0";
			$getApprovalStatus = $this->db->query($approvalStatusQry)->result_array();
			$approvalLevelCount  = count($getApprovalStatus);

			$checkaRejectionReqQry = "select approval_status_id from org_approval_status 
			where 
				request_id = '".$id."' and
					approval_type = 1 and
						approval_status = 2 and
							submit_level = 0
				";
			$checkaRejectionReq = $this->db->query($checkaRejectionReqQry)->result_array();

			$rejectionCount = count($checkaRejectionReq);

			if ($levelCount == $approvalLevelCount) 
			{
				if($rejectionCount == 0)
				{
					if($_POST["approval_status"] == 2 || $_POST["approval_status"] == 3) #2=>Rejected, 3=>Need More Information
					{
						$purchaseData["po_status"] = 7;
					}else{
						$purchaseData["po_status"] = 3;
					}

					$this->db->where('purchase_id', $id);
					$result = $this->db->update('purchases', $purchaseData);

					#Update Rerquest Data
					$ReRequestData["request_status"] = $_POST["approval_status"];
					$this->db->where('re_request_id', $re_request_id);
					$this->db->where('request_id', $id);
					$this->db->where('request_type', 1);
					$result = $this->db->update('pr_po_rerequest', $ReRequestData);

					/*$submit_levelData["submit_level"] =1; //all levels Completed
					$this->db->where('submit_level !=', 1);
					$this->db->where('request_id', $id);
					$result = $this->db->update('org_approval_status', $submit_levelData);*/
				}
			}
			#Update Approval Datas start here

			if( $prTotalAmount <= $approvalAmount && $_POST["approval_status"] == 1 ) #5015==20000
			{
				#$purchaseData1["po_status"] = 3; #Approved

				if($_POST["approval_status"] == 2 || $_POST["approval_status"] == 3) #2=>Rejected, 3=>Need More Information
				{
					$purchaseData1["po_status"] = 7;
				}
				else
				{
					$purchaseData1["po_status"] = 3;
				}

				$this->db->where('purchase_id', $id);
				$result = $this->db->update('purchases', $purchaseData1);
			}

			$this->session->set_flashdata('flash_message' , "Approval status updated successfully!");
			redirect(base_url() . 'purchase/viewApprovals/'.$id, 'refresh');
		}
		
		$this->load->view($this->adminTemplate, $page_data);
	}

	public function detailedViewApprovals($id="")
	{
		if (empty($this->user_id))
        {
			redirect(base_url() . 'admin/adminLogin', 'refresh');
		}
		$page_data['manageApproval'] = 1;
		$page_data['id'] = $id;

		$page_data['page_name']  = 'purchase/detailedViewApprovals';
		$page_data['page_title'] = 'Purchase Order Approvals';

		$this->load->view($this->adminTemplate, $page_data);
	}
	
	function ManagePurchaseReturn($type = '', $id = '', $status = '')
    {
		if (empty($this->user_id))
        {
			redirect(base_url() . 'admin/adminLogin', 'refresh');
		}
	
		$page_data['type'] = $type;
		$page_data['id'] = $id;
		
		$page_data['ManagePurchaseReturn'] = 1;
		$page_data['page_name']  = 'purchase/ManagePurchaseReturn';
		$page_data['page_title'] = 'Purchase Return';
		
		if(isset($_POST['delete']) && isset($_POST['checkbox']))
		{
			$cnt=array();
			$cnt=count($_POST['checkbox']);
			
			for($i=0;$i<$cnt;$i++)
			{
				$del_id=$_POST['checkbox'][$i];
				 
				$this->db->where('purchase_id', $del_id);
				$this->db->delete('purchase_items');
				
				$this->db->where('purchase_id', $del_id);
				$this->db->delete('purchases');
			}
			$this->session->set_flashdata('flash_message' , "Purchase deleted successfully!");
			redirect($_SERVER['HTTP_REFERER'], 'refresh');
		}
		
		switch($type)
		{
			case "add": #View
				$page_data['warehouse'] = $this->purchase_model->getWarehouse();
				
				if($_POST)
				{
					$data1['invoice_add_date'] = $this->input->post('date');
					
					$invoice_add_date = strtotime($data1['invoice_add_date']);
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date));
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020
					
					$warehouse_id = $this->input->post('warehouse');

					$po_status = 1;
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0;
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0;
					
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0)
					{
					    $total_tax = $_POST['total_tax'];
					}
					else
					{
					    $total_tax = 0;
					}
					
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0)
					{
					    $total_discount = $_POST['total_discount'];
					}
					else
					{
					    $total_discount = 0;
					}
					
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type']))
					{
						$additionalChargeType = $_POST['additional_charge_type'];
					}
					else
					{
						$additionalChargeType = 0;
					}

					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge']))
					{
						$additionalCharge = $_POST['additional_charge'];
					}
					else
					{
						$additionalCharge = 0;
					}

					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0;
					
					$data = array(
						"date" 				      =>  date('Y-m-d',$invoice_add_date),
						"invoice_add_date" 	      =>  $this->input->post('date'),
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)),
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date),
						"warehouse_id" 		      =>  $warehouse_id,
						"supplier_id" 		      => isset($_POST["supplier"]) ? $_POST["supplier"] : 0,
						
						
						"supplier_site" 		  =>  $supplier_site,
						"total" 			      =>  $grand_total,
						"discount_value"	      =>  $total_discount,
						"tax_value" 		      =>  $total_tax,

						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0,
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0,
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0,
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0,
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0,
						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0,
						"note" 				      =>  $this->input->post('note'),
						"tax_type" 				  =>  $tax_type,
						"po_status" 			  =>  $po_status, #Pending
						"created_date" 			  =>  time(),
						"additional_charge_type"     =>  $additionalChargeType,
						"additional_charge" 	     =>  $additionalCharge,
					);
					#print_r($data);exit;
					$this->db->insert('purchases', $data);
					$purchase_id = $this->db->insert_id();
					
					if($purchase_id)
					{
						#purchase ID Start here
						$results = $this->db->query("select purchase_id,increment_id from purchases order by increment_id desc")->result_array();
						
						if( count($results) == 1 )
						{
							$incrementID = 0;
						}
						else if( count($results) == 2 )
						{
							$incrementID = 1;
						}
						else
						{
							$incID = isset($results[0]['increment_id']) ? $results[0]['increment_id'] : 1;
							$incrementID = $incID + 1;
						}

						/* $random_user_id =  $incrementID;
						$UpdateData['reference_no'] = 'RE-'.$random_user_id;
						$UpdateData['increment_id'] = $incrementID; */

						/* 	$UpdateData['reference_no'] = PURCHASE_NUMBER_PREFIX."".str_pad($incrementID, PURCHASE_NUMBER_LENGTH, "0", STR_PAD_LEFT);
						$UpdateData['increment_id'] = $incrementID;
						*/

						$getPrefix = $this->db->query("select prefix_name, prefix_length, from_year, prefix_starting_number from org_prefix_length where prefix_type = 2")->result_array();
						$startingNumber = $getPrefix[0]['prefix_starting_number'];
						$incNumber = $startingNumber + $incrementID;
						$randomUserId = $getPrefix[0]['prefix_name']."".$incNumber;


						$UpdateData['reference_no'] = $randomUserId;
						$UpdateData['increment_id'] = $incrementID;

						$this->db->where('purchase_id', $purchase_id);
						$resultUpdateData = $this->db->update('purchases', $UpdateData);
						#Purchase ID end here
						
						$PurchaseItems = $this->input->post('table_data');
						$js_data = json_decode($PurchaseItems);
						
						foreach ($js_data as $key => $value) 
						{
							if($value==null)
							{
								
							}
							else
							{
								$product_id = $value->product_id;
								$quantity = $value->quantity;
								
								if(isset($value->expiry_date) && $value->expiry_date !="")
								{
									$expiry_date1 = date("d")."-".$value->expiry_date;

									$expiry_date =  date("Y-m-d",strtotime($expiry_date1));
								}
								else
								{
									$expiry_date = null;
								}

								/* 
								#Lot No start here
								if(isset($value->batch_no) && $value->batch_no !=""){
									$batch_no = $value->batch_no;
								}else{
									$batch_no = null;
								}

								if(LOT_CONTROL_LEVEL == 1) #Product
								{
									$increment_id = 0;
								}
								else if(LOT_CONTROL_LEVEL == 2) #Org
								{
									$increment_id = isset($value->increment_id) ? $value->increment_id : 0;
								} #Lot No end here
								*/

								$data1 = array(
									#"increment_id"      => $increment_id,
									"product_id"         => $value->product_id,
									"quantity"           => $value->quantity,
									"gross_total"        => $value->total,
									"discount_id"        => $value->discount_id,
									"discount_value"     => $value->discount_value,
									"discount"           => $value->discount,
									"tax_id"             => $value->tax_id,
									"tax_value"          => $value->tax_value,
									"tax"                => $value->tax,
									"cost"               => $value->cost,
									#"batch_no"          => $batch_no,
									#"expiry_date"       => $expiry_date,
									"purchase_id"        => $purchase_id,
									"purchase_item_date" => time(),

									"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"",
								);
								

								#add Product in warehouse start here
								/* $warehouse_data = array(
									"product_id"   => $value->product_id,
									"warehouse_id" => $warehouse_id,
									"quantity"     => $value->quantity
								);
								
								$this->purchase_model->addProductInWarehouse($product_id,$quantity,$warehouse_id,$warehouse_data);
						 		*/
								#add Product in warehouse end here
								
								$this->db->insert('purchase_items', $data1);
								$purchase_items  = $this->db->insert_id();
							}
						}
						
						#getPR Amount start here
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$purchase_id."'";
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array();

						$totalAmount = 0;
						foreach($getPurchaseItems as $purchaseItems)
						{
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"];
						}

						$reRequestData = array(
							"request_id"     => $purchase_id,
							"request_status" => $po_status,
							"request_type"   => 1, //Purchase Order
							"request_date"   => time(),
							"total_amount"   => $totalAmount,
							"created_by"     => $this->user_id,
						);

						$this->db->insert('pr_po_rerequest', $reRequestData);
						$rerequest_id = $this->db->insert_id();
						#getPR Amount end here

						$this->session->set_flashdata('flash_message' , "Purchase order created successfully!");
						redirect(base_url() . 'purchase/ManagePurchaseReturn', 'refresh');
					}
				}
			break;
			
			case "edit": #edit
				$page_data['warehouse'] = $this->purchase_model->getWarehouse(); 
				$page_data['data'] = $this->purchase_model->getRecord($id);
				
				$page_data['discount'] = $this->purchase_model->getDiscount();
				$page_data['tax'] = $this->purchase_model->getTax();
				
				foreach ($page_data['data'] as $key) 
				{
					$purchase_id = $key->purchase_id;
					$warehouse_id = $key->warehouse_id;
					$page_data['items'] = $this->purchase_model->getPurchaseItems($purchase_id,$warehouse_id);	
				}

				$page_data['purchase_id'] = $purchase_id = $id;
				
				if($_POST)
				{
					$data1['invoice_add_date'] = $this->input->post('date');
					
					$invoice_add_date = strtotime($data1['invoice_add_date']);
					#$data['invoice_billing_date'] = strtotime(date('d-m-Y h:i:s a',$invoice_add_date));
					#$data['added_date'] = date('Y-m-d',$invoice_add_date); #time(); 11-05-2020
					
					$warehouse_id = $this->input->post('warehouse');

					$purchase_request_type = $this->input->post('purchase_request_type');
					
					if( $status == "re_request" )
					{
						$po_status = 1; #Draft
					}
					else
					{
						$po_status = 1;
					}
					
					$supplier_site = isset($_POST['supplier_site']) ? $_POST['supplier_site'] : 0;
					$grand_total = isset($_POST['grand_total']) ? $_POST['grand_total'] : 0;
					
					if(isset($_POST['total_tax']) && !empty($_POST['total_tax']) && $_POST['total_tax'] > 0)
					{
					    $total_tax = $_POST['total_tax'];
					}
					else
					{
					    $total_tax = 0;
					}
					
					if(isset($_POST['total_discount']) && !empty($_POST['total_discount']) && $_POST['total_discount'] > 0)
					{
					    $total_discount = $_POST['total_discount'];
					}
					else
					{
					    $total_discount = 0;
					}
					
					$tax_type = isset($_POST['tax_type']) ? $_POST['tax_type'] : 0;

					
					if( isset($_POST['additional_charge_type']) && !empty($_POST['additional_charge_type']))
					{
						$additionalChargeType = $_POST['additional_charge_type'];
					}
					else
					{
						$additionalChargeType = 0;
					}

					if( isset($_POST['additional_charge']) && !empty($_POST['additional_charge']))
					{
						$additionalCharge = $_POST['additional_charge'];
					}
					else
					{
						$additionalCharge = 0;
					}

					$data = array(
						"date" 				      =>  date('Y-m-d',$invoice_add_date),
						"invoice_add_date" 	      =>  $this->input->post('date'),
						"invoice_billing_date" 	  =>  strtotime(date('d-m-Y h:i:s a',$invoice_add_date)),
						"added_date" 	          =>  date('Y-m-d',$invoice_add_date),
						"warehouse_id" 		      =>  $warehouse_id,
						
						"supplier_id" 		      =>  isset($_POST["supplier"]) ? $_POST["supplier"] : 0,
						
						"round_off"  				 =>  isset($_POST['round_off']) ? $_POST['round_off'] : 0,
						"s_gst"  				 =>  isset($_POST['s_gst']) ? $_POST['s_gst'] : 0,
						"c_gst"  				 =>  isset($_POST['c_gst']) ? $_POST['c_gst'] : 0,
						"i_gst"  				 =>  isset($_POST['i_gst']) ? $_POST['i_gst'] : 0,
						"state_number"  		 =>  isset($_POST['state_number']) ? $_POST['state_number'] : 0,

						"additional_charges"  		 =>  isset($_POST['additional_charges']) ? $_POST['additional_charges'] : 0,

						"supplier_site" 		  =>  $supplier_site,
						"total" 			      =>  $grand_total,
						"discount_value"	      =>  $total_discount,
						"tax_value" 		      =>  $total_tax,

						"note" 				      =>  $this->input->post('note'),
						"tax_type" 				  =>  $tax_type,
						"po_status" 		      =>  $po_status,
						"additional_charge_type"     =>  $additionalChargeType,
						"additional_charge" 	     =>  $additionalCharge,
					);
					#print_r($data);exit;
					$this->db->where('purchase_id', $id);
					$result = $this->db->update('purchases', $data);
					
					if($result)
					{
						$js_data = json_decode($this->input->post('table_data1'));			
						$php_data = json_decode($this->input->post('table_data'));
						
						if(!empty($js_data))
						{
							foreach (array_filter($js_data) as $key => $value) 
							{
								if($value=='delete')
								{
									
									$product_id =  $php_data[$key];
									if($this->purchase_model->deletePurchaseItems($id,$product_id,$warehouse_id))
									{
										
									}
								}
								else if($value==null)
								{
									
								}
								else
								{
									$product_id = $value->product_id;
									$quantity = $value->quantity;

									if(isset($value->expiry_date) && $value->expiry_date !="")
									{
										$expiry_date1 = date("d")."-".$value->expiry_date;

										$expiry_date =  date("Y-m-d",strtotime($expiry_date1)) ;
									}
									else
									{
										$expiry_date = null;
									}

	
									/* 
									#Lot No start here
									if(isset($value->batch_no) && $value->batch_no !=""){
										$batch_no = $value->batch_no;
									}else{
										$batch_no = null;
									}

									if(LOT_CONTROL_LEVEL == 1) #Product
									{
										$increment_id = 0;
									}
									else if(LOT_CONTROL_LEVEL == 2) #Org
									{
										$increment_id = isset($value->increment_id) ? $value->increment_id : 0;
									} 
									#Lot No end here
									*/
									
									$data = array(
										#"increment_id"     => $increment_id,
										"product_id"       => $value->product_id,
										"quantity"         => $value->quantity,
										"gross_total"      => $value->total,
										"discount_id"      => $value->discount_id,
										"discount_value"   => $value->discount_value,
										"discount"         => $value->discount,
										"tax_id"           => $value->tax_id,
										"tax_value"        => $value->tax_value,
										"tax"              => $value->tax,
										"cost"             => $value->cost,
										#"expiry_date"      => $expiry_date,
										#"batch_no"         => $batch_no, #Lot No
										"discount_type_id" => isset($value->discount_type_id) ? $value->discount_type_id :"",
										"purchase_id"      => $id
									);

									$warehouse_data = array(
										"product_id"     => $value->product_id,
										"warehouse_id"   => $warehouse_id,
										"quantity"       => $value->quantity
									);

									if($this->purchase_model->addUpdatePurchaseItem($id,$product_id,$warehouse_id,$quantity,$data,$warehouse_data))
									{
										
									}
									else
									{

									}
								}
							}
						}

						#getPR Amount start here
						$purchaseItemsQry = "select gross_total,tax,discount_value from purchase_items where purchase_id='".$id."'";
						$getPurchaseItems = $this->db->query($purchaseItemsQry)->result_array();

						$totalAmount = 0;
						foreach($getPurchaseItems as $purchaseItems)
						{
							$totalAmount += $purchaseItems["gross_total"] + $purchaseItems["tax"] - $purchaseItems["discount_value"];
						}
						#getPR Amount end here
						
						if ( $status == "re_request" ) #PR Re Request
						{
							$reRequestData = array(
								"request_id"     => $id,
								"request_status" => $po_status,
								"request_type"   => 1,
								"request_date"   => time(),
								"total_amount"   => $totalAmount,
								"created_by"     => $this->user_id,
							);

							$this->db->insert('pr_po_rerequest', $reRequestData);
							$rerequest_id = $this->db->insert_id();

							$submit_levelData["submit_level"] =1; //all levels Completed
							$this->db->where('submit_level', 0);
							//$this->db->where('submit_level !=', 1);
							$this->db->where('request_id', $id);
							$this->db->where('approval_type', 1);
							$result = $this->db->update('org_approval_status', $submit_levelData);
						}
						#re_request end here
						
						$this->session->set_flashdata('flash_message' , "Purchase order updated successfully!");
						redirect(base_url() . 'purchase/ManagePurchaseReturn/'.$id, 'refresh');
					}
				}
			break;
			
			case "delete": #Delete
				$this->db->where('sales_id', $id);
				$this->db->delete('sales');
				
				$this->db->where('sales_id', $id);
				$this->db->delete('sales_items');
				
				/* $this->db->where('invoice_id', $id);
				$this->db->delete('invoice_payment'); */
				
				$this->session->set_flashdata('flash_message' , "Sale deleted successfully!");
				redirect(base_url() . 'sales/ManageSales', 'refresh');
			break;

			case "approval_status": #approval_status
				if($status == 5) #Close
				{
					$successMsg = "Purchase order closed successfully!";
				}
				else if($status == 4) #Cancel
				{
					$successMsg = "Purchase order cancelled successfully!";
				}
 
				$updateData["po_status"] = $status;

				$this->db->where('purchase_id', $id);
				
				$result = $this->db->update('purchases', $updateData);

				$this->session->set_flashdata('flash_message' , $successMsg);
				redirect(base_url() . 'purchase/ManagePurchase', 'refresh');
			break;

			default : #Manage
				$page_data["totalRows"] = $totalRows = $this->purchase_model->getManagePurchaseCount();
	
				if(!empty($_SESSION['PAGE']))
				{$limit = $_SESSION['PAGE'];
				}else{$limit = 10;}
				
				if (!empty($_GET['keywords'])) {
					$base_url = base_url('purchase/ManagePurchase?keywords='.$_GET['keywords']);
				} else {
					$base_url = base_url('purchase/ManagePurchase?keywords=');
				}
				
				$config = PaginationConfig($base_url,$totalRows,$limit);
				$this->pagination->initialize($config);
				$str_links = $this->pagination->create_links();
				$page_data['pagination'] = explode('', $str_links);
				$offset = 0;
				if (!empty($_GET['per_page'])) {
					$pageNo = $_GET['per_page'];
					$offset = ($pageNo - 1) * $limit;
				}
				
				if($offset == 1 || $offset== "" || $offset== 0){
					$page_data["first_item"] = 1;
				}else{
					$page_data["first_item"] = $offset + 1;
				}
				
				$page_data['resultData']  = $result= $this->purchase_model->getManagePurchase($limit, $offset);
				
				#show start and ending Count
				$total_counts = $total_count= 0;
				$pages=$page_data["starting"] = $page_data["ending"]="";
				$pageno = isset($pageNo) ? $pageNo :"";
				
				if( $totalRows == 0 ){
					$page_data["starting"] = 0;
				}else if( $pageno==1 || $pageno=="" ){
					$page_data["starting"] = 1;
				}else{
					$pages = $pageno-1;
					$total_count = $pages * $config["per_page"];
					$page_data["starting"] = ( $config["per_page"] * $pages )+1;
				}
				
				$total_counts = $total_count + count($result);
				$page_data["ending"]  = $total_counts;
				#show start and ending Count end
			break;
		}	
		$this->load->view($this->adminTemplate, $page_data);
	}

	public function purchaseReturnDetails($invoice_id="")
	{
		if (empty($this->user_id))
        {
			redirect(base_url() . 'admin/adminLogin', 'refresh');
		}
	
		$page_data['id'] = $id=$invoice_id;
		
		$page_data['ManagePurchaseReturn'] = 1;
		
		$page_data['page_name']  = 'purchase/purchaseReturnDetails';
		$page_data['page_title'] = 'Purchase Return Details';

		$this->load->view($this->adminTemplate, $page_data);
	}
	
}
?>

Function Calls

None

Variables

None

Stats

MD5 453851db3566eb4baf206f4e6c0b1cde
Eval Count 0
Decode Time 150 ms