<?php
class LoadingOrder {
	protected $info = array();
	private $db;

	public function __construct() {
		$this->db = DBConnectorFactory::loadDriver();
	}

	public function setData($data) {
		$this->info = $data;
		return $this;
	}


	public function assignSalesOrderToLoadOrder() {
		$query = $this->db->query('INSERT INTO
										tbl_garage_loading_order
										(
											Vehicle_ID,
											Driver_ID,
											Sales_Man_ID,
											Loading_Order_Date,
                                            Class_ID,
											Logged_ID
										)
										VALUES
										(
											"'.$this->info['Vehicle_ID'].'",
											"'.$this->info['Driver_ID'].'",
											"'.$this->info['Sales_Man_ID'].'",
											"'.$this->info['Loading_Order_Date'].'",
											"'.$this->info['Class_ID'].'",
											"'.$this->info[0].'"
										)
				');
		$j = 0;
		for ($i = 0; $i < count($this->info['orders']); $i++) {
			$query = $this->db->query('UPDATE
											tbl_garage_sales_order
										SET 
											Assign_To 	   = "'.$this->info['orders'][$i]['Assign_To'].'",
											Load_Order_ID  = "'.$this->info['Load_Order_ID'].'",
                                            Sales_Status   = 2
										WHERE 
											Sales_Order_ID = "'.$this->info['orders'][$i]['Sales_Order_ID'].'"
					');
			if ($query)
				$j++;
		}
		if ($j==$i)
			return true;
		return false;
	}

	public function submitLoadOrder($load_id,$depot_id=null) {
		if (is_null($depot_id))
			$depot_id = 1;
		$query = $this->db->query('UPDATE 
										tbl_garage_loading_order
									SET 
										Is_Load = 2
									WHERE 
										Loading_Order_ID = "'.$load_id.'"
				');
		if ($query) {
			$j = 0;
			for ($i=0; $i<count($this->info['Products']); $i++) {
				$qy = $this->db->query('UPDATE 
											tbl_stock_products 
										SET 
											Product_Quantity = Product_Quantity - "'.$this->info['Products'][$i]['Quantity'].'"
										WHERE 
											Product_ID = "'.$this->info['Products'][$i]['Product_ID'].'"
					');
				$this->db->query('UPDATE 
									tbl_stock_product_location 
								SET 
									Product_Depot_Quantity = Product_Depot_Quantity - "'.$this->info['Products'][$i]['Quantity'].'"
								WHERE 
									Location_Product_ID = "'.$this->info['Products'][$i]['Product_ID'].'" 
								AND 
									Product_Depot_ID = "'.$depot_id.'"
				');


				if ($qy) {
					$IsSales = self::CheckIfSales($load_id);
					if($IsSales['Exist']){
						$add = $this->db->query('INSERT INTO
													tbl_garage_loading_order_details (
														Loading_ID,
														Product_ID,
														Initial_Quantity,
														Product_Load_Quantity,
                                                        Product_Added_Quantity,
                                                        Logged_ID
													)
													VALUES (
														"'.$load_id.'",
														"'.$this->info['Products'][$i]['Product_ID'].'",
														"'.$this->info['Products'][$i]['Initial_Quantity'].'",
														"'.$this->info['Products'][$i]['Quantity'].'",
														"'.$this->info['Products'][$i]['Product_Added_Quantity'].'",
                                                        "'.$this->info[0].'"
													)
							');
						if ($add)
							$j++;
					}else{
						if (self::IfLoadingOrderExists($load_id,$this->info['Products'][$i]['Product_ID'])) {
							$query = $this->db->query('UPDATE 
                                                                tbl_garage_loading_order_details
                                                            SET 
                                                                Product_Added_Quantity = "'.$this->info['Products'][$i]['Product_Added_Quantity'].'",
                                                                Product_Load_Quantity = "'.$this->info['Products'][$i]['Quantity'].'"
                                                            WHERE 
                                                                Product_ID = "'.$this->info['Products'][$i]['Product_ID'].'" 
                                                            AND 
                                                                Loading_ID = "'.$load_id.'"
                                        ');

						}
						else{

							$query = $this->db->query('INSERT INTO
													tbl_garage_loading_order_details (
														Loading_ID,
														Product_ID,
														Initial_Quantity,
														Product_Load_Quantity,
                                                        Product_Added_Quantity,
                                                        Logged_ID
													)
													VALUES (
														"'.$load_id.'",
														"'.$this->info['Products'][$i]['Product_ID'].'",
														"'.$this->info['Products'][$i]['Initial_Quantity'].'",
														"'.$this->info['Products'][$i]['Quantity'].'",
														"'.$this->info['Products'][$i]['Product_Added_Quantity'].'",
                                                        "'.$this->info[0].'"
													)
                                          ');


						}
						if($query)
							$j++;
					}
				}
			}
			if ($j==$i)
				return true;
		}
		return false;
	}



	public function getSalesOrderInfo($zone) {
		$data = array();
		$query = $this->db->query('SELECT 

                                        s.*,
                                        c.*

                                    FROM 
                                        tbl_garage_sales_order s
                                    LEFT JOIN 
                                        tbl_customers c
                                    ON
                                        s.Customer_ID = c.Customer_ID
                                   WHERE 
                                        Zone_ID = "'.$zone.'" AND Assign_To = 0
                                    AND 
                                        s.Sales_Status <> 3
                    ');
		while ($row = $this->db->assoc($query)) {
			$data[] = $row;
		} 
		return $data;
	}


	public function viewLoadingOrder($date=null,$type = null) {
		$data = array();
		$condition = '';
		if(!is_null($type))
			$condition .=' AND o.Is_Load = "'.$type.'"';
		if(!is_null($date))
			$condition .= ' AND o.Loading_Order_Date = "'.$date.'"';
		$query = $this->db->query('SELECT 
										o.*,
										v.*,
										CONCAT(d.Employee_FirstName, " ", d.Employee_MiddleName, " ", d.Employee_LastName) AS Driver_Name,
										CONCAT(sm.Employee_FirstName, " ", sm.Employee_MiddleName, " ", sm.Employee_LastName) AS Sales_Man_Name,
										CONCAT(l.Employee_FirstName, " ", l.Employee_MiddleName, " ", l.Employee_LastName) AS Logged_Name
									FROM 
										tbl_garage_loading_order o
									LEFT JOIN
										tbl_garage_vehicle v
									ON 
										v.Vehicle_ID = o.Vehicle_ID 
									LEFT JOIN 
										tbl_hrm_employee d
									ON 
										o.Driver_ID = d.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee sm
									ON 
										o.Sales_Man_ID = sm.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee l
									ON 
										o.Logged_ID = l.Employee_ID
                                    WHERE
                                       1=1

				'.$condition);
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;
	}
	public function viewSalesOrder($date=null) {
		$data = array();
		$query = $this->db->query('SELECT 
										o.*,
										c.*,
									CONCAT(e.Employee_FirstName, " ", e.Employee_MiddleName, " ", e.Employee_LastName) AS Employee_Name



									FROM 
										tbl_garage_sales_order o


                                    LEFT JOIN 
										tbl_customers c
									ON 
										c.Customer_ID = o.Customer_ID
									LEFT JOIN
										tbl_common_users u
									ON 
										u.User_ID = o.Logged_ID
									LEFT JOIN 
										tbl_hrm_employee  e
									ON 
										e.Employee_ID = u.Employee_ID

                                    WHERE 
										o.Sales_Order_Date = "'.$date.'"
				');
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;
	}
	public function viewSalesOrderInfo($id) {
		$data = array();
		$query = $this->db->query('SELECT 
										o.*,
										c.*,
                                        cu.*       
									FROM 
										tbl_garage_sales_order o
									LEFT JOIN 
										tbl_customers c
									ON 
										c.Customer_ID = o.Customer_ID
                                    LEFT JOIN 
										tbl_common_currency cu
									ON 
										c.Currency_ID = cu.Currency_ID
                                    WHERE
                                        o.Sales_Order_ID="'.$id.'"



				');
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;
	}
	public function getMaxOrder() {
		$query = $this->db->query('SELECT * FROM tbl_garage_sales_order ORDER BY Sales_Order_ID DESC limit 1');
		$Order = '';
		$row = $this->db->assoc($query);
		$Order = $row['Sales_Order_ID'];

		return $Order;
	}
	public function getMaxLoadingOrder() {
		$query = $this->db->query('SELECT * FROM tbl_garage_loading_order ORDER BY Loading_Order_ID DESC limit 1');
		$Order = '';
		$row = $this->db->assoc($query);
		$Order = $row['Loading_Order_ID'];

		return $Order;
	}
	public function viewLoadingInfoByID($id) {
		$data = array();

		$ordersquery = $this->db->query('SELECT Sales_Order_ID
                                        FROM
                                            tbl_garage_sales_order s
                                        WHERE
                                            s.Load_Order_ID = "'.$id.'"');  

		$orders = $this->db->assoc($ordersquery);
		$i = 0;
		$count = 0;
		$temp = array();
		if(!is_null($orders)){

			$query = $this->db->query('SELECT 
										c.Customer_Name,
										c.Customer_Company,
										c.Customer_Address,
										v.Vehicle_Registration_Number,
										o.*,
                                        s.Sales_Order_ID,
										ct.Country_Name,
										cy.Name AS City_Name,
										z.Zone_Name,
									   CONCAT(dk.Employee_FirstName, " ", dk.Employee_MiddleName, " ", dk.Employee_LastName) AS Driver_Name,
										CONCAT(sm.Employee_FirstName, " ", sm.Employee_MiddleName, " ", sm.Employee_LastName) AS Sales_Man_Name,
										CONCAT(l.Employee_FirstName, " ", l.Employee_MiddleName, " ", l.Employee_LastName) AS Logged_Name
									FROM 
										tbl_garage_loading_order o
									LEFT JOIN
										tbl_garage_vehicle v
									ON 
										v.Vehicle_ID = o.Vehicle_ID 
									LEFT JOIN 
										tbl_hrm_employee dk
									ON 
										o.Driver_ID = dk.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee sm
									ON 
										o.Sales_Man_ID = sm.Employee_ID
									LEFT JOIN
										tbl_common_users u
									ON 
										u.User_ID = o.Logged_ID
									LEFT JOIN 
										tbl_hrm_employee l
									ON 
										l.Employee_ID = u.Employee_ID
									LEFT JOIN 
										tbl_garage_sales_order s
									ON 
										o.Loading_Order_ID = s.Load_Order_ID
									LEFT JOIN 
										tbl_garage_vehicle_zone z
									ON 
										z.Zone_ID = s.Zone_ID
									LEFT JOIN 
										tbl_customers c
									ON 
										c.Customer_ID = s.Customer_ID
									LEFT JOIN 
										tbl_all_countries ct
									ON 
										c.Customer_Country_ID = ct.Country_ID
									LEFT JOIN 
										tbl_all_cities cy
									ON 
										c.Customer_City_ID = cy.ID
									WHERE 
										s.Load_Order_ID = "'.$id.'"

									AND 
										s.Assign_To > 0
				');
			while($row = $this->db->assoc($query)) {
				$count = count($row);
				$query2 = $this->db->query('
                                            SELECT
                                                s.*,
                                                p.*
                                            FROM 
                                                tbl_garage_sales_order_details s
                                            LEFT JOIN 
                                                tbl_stock_products p
                                            ON
                                                s.Product_ID = p.Product_ID
                                            WHERE
                                                s.Sales_Order_ID = "'.$row['Sales_Order_ID'].'"
                        ');
				$data[$i] = $row;
				while($row2=$this->db->fetch($query2)) {
					$data[$i][] = $row2;
					if (!array_key_exists($row2['Product_ID'].'-/'.$row2['Product_Code'].'-/'.$row2['Product_Name'],$temp))
						$temp[$row2['Product_ID'].'-/'.$row2['Product_Code'].'-/'.$row2['Product_Name']] = $row2['Quantity'];
					else
						$temp[$row2['Product_ID'].'-/'.$row2['Product_Code'].'-/'.$row2['Product_Name']]+= $row2['Quantity'];
				}

				$i++;
			}
		}
		else{
			$query = $this->db->query('SELECT 
										v.Vehicle_Registration_Number,
										o.*,
										z.Zone_Name,
										CONCAT(dk.Employee_FirstName, " ", dk.Employee_MiddleName, " ", dk.Employee_LastName) AS Driver_Name,
										CONCAT(sm.Employee_FirstName, " ", sm.Employee_MiddleName, " ", sm.Employee_LastName) AS Sales_Man_Name,
										CONCAT(l.Employee_FirstName, " ", l.Employee_MiddleName, " ", l.Employee_LastName) AS Logged_Name
									FROM 
										tbl_garage_loading_order o
									LEFT JOIN
										tbl_garage_vehicle v
									ON 
										v.Vehicle_ID = o.Vehicle_ID 
                                    LEFT JOIN
										tbl_garage_vehicle_driver vd
									ON 
										v.Vehicle_ID = vd.Vehicle_ID
									LEFT JOIN 
										tbl_hrm_employee dk
									ON 
										o.Driver_ID = dk.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee sm
									ON 
										o.Sales_Man_ID = sm.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee l
									ON 
										o.Logged_ID = l.Employee_ID
									LEFT JOIN 
										tbl_garage_vehicle_zone z
									ON 
										z.Zone_ID = vd.Vehicle_Zone_ID
									WHERE 
										o.Loading_Order_ID = "'.$id.'"
                                    GROUP BY
                                        o.Loading_Order_ID
				');
			while($row = $this->db->assoc($query)) {
				$count = count($row);
				$query2 = $this->db->query('
                                            SELECT
                                                s.*,
                                                s.Initial_Quantity AS Quantity,
                                                p.*
                                            FROM 
                                                tbl_garage_loading_order_details s
                                            LEFT JOIN 
                                                tbl_stock_products p
                                            ON
                                                s.Product_ID = p.Product_ID
                                            WHERE
                                                s.Loading_ID = "'.$id.'"

                        ');
				$row['Customer_Name'] = 'Road Customer';
				$row['Sales_Order_ID'] = 0;
				$row['Customer_Company'] = '-';
				$row['Customer_Address'] = $row['Zone_Name'];
				$row['Country_Name'] = '-';
				$row['City_Name'] = '-';
				$data[$i] = $row;
				while($row2=$this->db->fetch($query2)) {
					$data[$i][] = $row2;
					if (!array_key_exists($row2['Product_ID'].'-/'.$row2['Product_Code'].'-/'.$row2['Product_Name'],$temp))
						$temp[$row2['Product_ID'].'-/'.$row2['Product_Code'].'-/'.$row2['Product_Name']] = $row2['Quantity'];
					else
						$temp[$row2['Product_ID'].'-/'.$row2['Product_Code'].'-/'.$row2['Product_Name']]+= $row2['Quantity'];
				}

				$i++;
			}


		}
		$data['Total'] = $temp;
		$data['Count_Columns'] = $count;
		return $data;
	}

	
	public function viewTotalLoadByDate($date = null,$load_id=null,$flag = null) {        
		$condition = '';
		if (!is_null($date))
			$condition .= ' AND l.Loading_Order_Date = "'.$date.'"';
		if (!is_null($load_id))
			$condition .= ' AND l.Loading_Order_ID = "'.$load_id.'"';
		$data = array();
		$query = $this->db->query(' SELECT 
										ld.Product_ID,
										p.Product_Code,
										p.Product_Name,
                                        p.Product_Price,
										(ld.Initial_Quantity + ld.Product_Added_Quantity) AS Total_Loaded_Quantity,
										(p.Product_Price*(ld.Initial_Quantity + ld.Product_Added_Quantity)) AS Total_Loaded_Price,
										v.Zone_ID,
										CONCAT(ld.Product_ID, so.Zone_ID) AS Product_Load,
										c.Currency_Symbol
									FROM  
										tbl_garage_loading_order_details ld

									LEFT JOIN 
										tbl_garage_loading_order l
									ON 
										ld.Loading_ID = l.Loading_Order_ID
									LEFT JOIN 
										tbl_garage_sales_order so
									ON 
										so.Load_Order_ID = l.Loading_Order_ID
									LEFT JOIN 
										tbl_stock_products p
									ON 
										ld.Product_ID = p.Product_ID
									LEFT JOIN 
    									tbl_common_currency c
									ON 
										c.Currency_ID = p.Currency_ID
									LEFT JOIN 
										tbl_garage_vehicle_zone v
									ON 
										v.Zone_ID = so.Zone_ID
									WHERE 
										l.Is_Load = 2

										'.$condition.'
									GROUP BY 
										Product_Load
				');
		$i = 0;

		while ($row = $this->db->assoc($query)) {
			if($row['Zone_ID'] == 8) {
				$row['Total_Loaded_Price'] = $row['Total_Loaded_Price'] * 2;
			}
			$data[] = $row;
			$return = $this->db->query('SELECT 
                                                            CONCAT(r.Loading_Order_ID, r.Product_ID) AS Product_Load,
                                                            r.Return_Quantity AS Return_Quantity,
                                                            r.Damaged_Quantity AS Damaged_Quantity
                                                    FROM  
                                                            tbl_garage_load_returns r
                                                    LEFT JOIN 
                                                            tbl_garage_loading_order_details ld 
                                                    ON 
                                                            ld.Product_ID = r.Product_ID
                                                    LEFT JOIN 
                                                            tbl_garage_loading_order_details ldr 
                                                    ON 
                                                            r.Loading_Order_ID = ldr.Loading_ID
                                                    LEFT JOIN 
                                                            tbl_garage_loading_order l
                                                    ON 
                                                            ld.Loading_ID = l.Loading_Order_ID
                                                    WHERE 
                                                            r.Product_ID = "'.$row['Product_ID'].'"
                                                    AND
                                                            l.Is_Load = 2
                                                            '.$condition.'
                                                    GROUP BY 
                                                    Product_Load
					');
			$row_return = $this->db->assoc($return);
			$sold = $this->db->query('SELECT
                                                    id.Product_Quantity AS Total_Sold_Quantity,
                                                    id.Product_Net_Price AS Total_Sold_Price,
                                                    l.Loading_Order_Date
                                                FROM 
                                                        tbl_invoice_products_details id
                                                LEFT JOIN 
                                                        tbl_invoices i
                                                ON 
                                                        i.Invoice_ID = id.Invoice_ID
                                                LEFT JOIN     
                                                    tbl_garage_loading_order l
                                                ON 
                                                        i.Load_ID = l.Loading_Order_ID
                                                WHERE 
                                                        id.Product_ID = "'.$row['Product_ID'].'"
                                                AND 
                                                        i.Load_ID > 0 
                                                        '.$condition.'
                                                GROUP BY 
                                                id.Product_ID
					');
			$row_sold = $this->db->assoc($sold);
			if (count($row_sold)>0) {
				if(is_null($row_sold['Total_Sold_Quantity']))
					$row_sold['Total_Sold_Quantity'] = 0;
				if(is_null($row_sold['Total_Sold_Price']))
					$row_sold['Total_Sold_Price'] = 0;
			}
			if (count($row_return)>0) {
				if(is_null($row_return['Return_Quantity']))
					$row_return['Return_Quantity'] = 0;
				if(is_null($row_return['Damaged_Quantity']))
					$row_return['Damaged_Quantity'] = 0;
				
			}

			$data[$i]['Total_Sold_Quantity'] = $row_sold['Total_Sold_Quantity'];
			$data[$i]['Damaged_Quantity'] = $row_return['Damaged_Quantity'];
			$data[$i]['Return_Quantity'] = $row_return['Return_Quantity'];
			$data[$i]['Total_Sold_Price'] = $row_sold['Total_Sold_Price'];
			$data[$i]['Product_Final_Quantity'] = $data[$i]['Total_Loaded_Quantity'] - $data[$i]['Return_Quantity']  - $data[$i]['Damaged_Quantity'] - $data[$i]['Total_Sold_Quantity'];

			$i++;
		}
		$final_product = array();
		$count = count($data);
		for ($z = 0; $z < $count; $z++) {
			$load_quantity = 0.0;
			$load_price = 0.0;
			$sold_quantity = 0.0;
			$sold_price = 0.0;
			$final_quantity = 0.0;
			$return_quantity = 0.0;
			$damages_quantity = 0.0;
			if (array_key_exists($z, $data)) {
				$symbol = $data[$z]['Currency_Symbol'];
				$id = $data[$z]['Product_ID'];
				$code = $data[$z]['Product_Code'];
				$name = $data[$z]['Product_Name'];
				$load_quantity = $data[$z]['Total_Loaded_Quantity'];
				$load_price = $data[$z]['Total_Loaded_Price'];
				$sold_quantity = $data[$z]['Total_Sold_Quantity'];
				$sold_price = $data[$z]['Total_Sold_Price'];
				$final_quantity = $data[$z]['Product_Final_Quantity'];
				$return_quantity = $data[$z]['Return_Quantity'];
				$damages_quantity = $data[$z]['Damaged_Quantity'];
				for ($j = $z + 1; $j < $count; $j++)
					if (array_key_exists($j, $data))
						if ($data[$z]['Product_ID'] == $data[$j]['Product_ID']) {
							$load_quantity += $data[$j]['Total_Loaded_Quantity'];
							$load_price += $data[$j]['Total_Loaded_Price'];
							$sold_quantity += $data[$j]['Total_Sold_Quantity'];
							$sold_price += $data[$j]['Total_Sold_Price'];
							$final_quantity += $data[$j]['Product_Final_Quantity'];
							$return_quantity += $data[$j]['Return_Quantity'];
							$damages_quantity += $data[$j]['Damaged_Quantity'];
							unset($data[$j]);  
						}
				if(!is_null($flag)){
					$product_temp = array(
						'0' 	    	  => $id,
						'1' 			  => $code,
						'2'    		  => $name,
						'3'   => $load_quantity,
						'4'   	  => $load_price.' '.$symbol
					);
				}else{

					$product_temp = array(
						'Product_ID' 	    	  => $id,
						'Product_Code' 			  => $code,
						'Product_Name'    		  => $name,
						'Total_Loaded_Quantity'   => $load_quantity,
						'Product_Final_Quantity'  => $final_quantity,
						'Return_Quantity'   => $return_quantity,
						'Damaged_Quantity'   => $damages_quantity,
						'Total_Sold_Quantity'     => $sold_quantity,
						'Total_Loaded_Price'   	  => $load_price,
						'Total_Sold_Price'        => $sold_price,
						'Currency_Symbol'         => $symbol
					);
				}
				array_push($final_product,$product_temp);
				$product_temp = array();
				unset($data[$z]);
				$id = 0;
				$code = '';
				$name = '';
				$final_quantity = 0.0;
				$return_quantity = 0.0;
				$damages_quantity = 0.0;
				$load_quantity = 0.0;
				$load_price = 0.0;
				$sold_quantity = 0.0;
				$sold_price = 0.0;
			}
		}
		return $final_product;
	}



	public function addReturnDamagedQuantity($depot_id=null) {
		if (is_null($depot_id))
			$depot_id = 1;
		for($i=0;$i<count($this->info['Return']);$i++) { 
			$check = $this->db->query('SELECT 
											Load_Return_ID,
											Parent_ID,
											Return_Quantity
										FROM 
											tbl_garage_load_returns
										WHERE
											Status_ID = 1
										AND 
											Loading_Order_ID = "'.$this->info['Return'][$i]['Loading_Order_ID'].'"
										AND 
											Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'"
					');
			$row = $this->db->assoc($check);
			if (is_null($row['Parent_ID'])) {
				$query = $this->db->query('INSERT INTO
                                            tbl_garage_load_returns (Loading_Order_ID,
                                                                    Product_ID,
                                                                    Product_Qty,
                                                                    Return_Quantity,
                                                                    Damaged_Quantity,
                                                                    Total_Remaining_Qty,
                                                                    Logging_ID

                                            )
                                            VALUES ("'.$this->info['Return'][$i]['Loading_Order_ID'].'",
                                                    "'.$this->info['Return'][$i]['Product_ID'].'",
                                                    "'.$this->info['Return'][$i]['Product_Qty'].'",
                                                    "'.$this->info['Return'][$i]['Return_Quantity'].'",
                                                    "'.$this->info['Return'][$i]['Damaged_Quantity'].'",
                                                    "'.$this->info['Return'][$i]['Total_Remaining_Qty'].'",
                                                    "'.$this->info[0].'"
                                            )
                    ');
				if ($query) {
					$update = $this->db->query('UPDATE 
													tbl_stock_products 
												SET 
													Product_Quantity = Product_Quantity + "'.$this->info['Return'][$i]['Return_Quantity'].'"
												WHERE 
													Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'"
					');
					$this->db->query('UPDATE 
										tbl_stock_product_location 
									SET 
										Product_Depot_Quantity = Product_Depot_Quantity + "'.$this->info['Return'][$i]['Return_Quantity'].'"
									WHERE 
										Location_Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'" 
									AND 
										Product_Depot_ID = "'.$depot_id.'"
					');

					if ($update)
						$j++;
				}
			}

			else {
				$query = $this->db->query('INSERT INTO
                                            tbl_garage_load_returns (Loading_Order_ID,
                                                                    Product_ID,
                                                                    Product_Qty,
                                                                    Return_Quantity,
                                                                    Damaged_Quantity,
                                                                    Total_Remaining_Qty,
                                                                    Logging_ID,
																	Parent_ID

                                            )
                                            VALUES ("'.$this->info['Return'][$i]['Loading_Order_ID'].'",
                                                    "'.$this->info['Return'][$i]['Product_ID'].'",
                                                    "'.$this->info['Return'][$i]['Product_Qty'].'",
                                                    "'.$this->info['Return'][$i]['Return_Quantity'].'",
                                                    "'.$this->info['Return'][$i]['Damaged_Quantity'].'",
                                                    "'.$this->info['Return'][$i]['Total_Remaining_Qty'].'",
                                                    "'.$this->info[0].'",
													"'.$row['Load_Return_ID'].'"
                                            )
                    ');
				$update_status = $this->db->query('UPDATE
														tbl_garage_load_returns
													SET 
														Status_ID = 0
													WHERE
														Load_Return_ID = "'.$row['Load_Return_ID'].'"
								');
				if ($row['Return_Quantity'] > $this->info['Return'][$i]['Return_Quantity']){
					$diff = $row['Return_Quantity'] - $this->info['Return'][$i]['Return_Quantity'];
					$update = $this->db->query('UPDATE 
													tbl_stock_products 
												SET 
													Product_Quantity = Product_Quantity - "'.$diff.'"
												WHERE 
													Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'"
					');
					$this->db->query('UPDATE 
										tbl_stock_product_location 
									SET 
										Product_Depot_Quantity = Product_Depot_Quantity - "'.$diff.'"
									WHERE 
										Location_Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'" 
									AND 
										Product_Depot_ID = "'.$depot_id.'"
					');
					if ($update)
						$j++;

				}
				else {
					$diff = $this->info['Return'][$i]['Return_Quantity'] - $row['Return_Quantity'];
					$update = $this->db->query('UPDATE 
													tbl_stock_products 
												SET 
													Product_Quantity = Product_Quantity + "'.$diff.'"
												WHERE 
													Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'"
					');
					$this->db->query('UPDATE 
										tbl_stock_product_location 
									SET 
										Product_Depot_Quantity = Product_Depot_Quantity + "'.$diff.'"
									WHERE 
										Location_Product_ID = "'.$this->info['Return'][$i]['Product_ID'].'" 
									AND 
										Product_Depot_ID = "'.$depot_id.'"
					');
					if ($update)
						$j++;
				}

			}
		}
		if ($i==$j)
			return	true;
		return false;
	}

	public function getSalesOrder($id,$load = null){
		$condition = '';
		$data = array();
		if(!is_null($load)){$condition = ' AND o.Load_Order_ID = "'.$load.'"';}
		$query = $this->db->query('SELECT
                                    p.Product_ID,
                                    p.Product_Code,
                                    p.Product_Name,
                                    p.Product_VAT,
                                    d.Quantity,
                                    pcl.Product_Price
                                FROM
                                    tbl_garage_sales_order_details d
                                LEFT JOIN
                                    tbl_garage_sales_order o
                                ON  
                                    d.Sales_Order_ID = o.Sales_Order_ID
                                 LEFT JOIN
                                    tbl_customers c
                                ON
                                    c.Customer_ID = o.Customer_ID
                                LEFT JOIN
                                    tbl_item_price_by_classes pcl
                                ON 
                                    c.Class_ID = pcl.Class_ID
                                LEFT JOIN 
                                    tbl_stock_products p
                                ON
                                    (d.Product_ID = p.Product_ID
                                 AND
                                    pcl.Product_ID = p.Product_ID)
                                WHERE
                                    o.Sales_Order_ID = "'.$id.'"
                                AND pcl.Status_ID = 1
                                AND p.Status_ID = 1
                                AND c.Status_ID = 1


                                '.$condition);
		while($row = $this->db->assoc($query)){
			$data[] = $row;
		}
		return $data;



	}

	public function viewSalesOrderProductByID($id,$load_id=null) {
		$data = array();
		$condition = '';
		if (!is_null($load_id))
			$condition .= ' AND ps.Loading_Order_ID = "'.$load_id.'" AND s.Sales_Order_ID NOT IN (
																									SELECT 
																										Sales_ID 
																									FROM 
																										tbl_invoices
																									WHERE 
																										Sales_ID = "'.$id.'"
																									)';
		$query = $this->db->query('SELECT
											s.*,
											p.Product_Code,
                                            p.Product_Name,
                                            pcl.Product_Price,
                                            pcl.Class_ID,
                                            s.Sales_Order_ID
										FROM 
											tbl_garage_sales_order_details s
										LEFT JOIN 
											tbl_garage_sales_order so
										ON
											so.Sales_Order_ID = s.Sales_Order_ID
                                        LEFT JOIN
                                            tbl_customers c
                                        ON
                                            c.Customer_ID = so.Customer_ID
                                        LEFT JOIN
                                            tbl_item_price_by_classes pcl
                                        ON 
                                            c.Class_ID = pcl.Class_ID
										INNER JOIN 
											tbl_stock_products p
										ON
											(s.Product_ID = p.Product_ID
                                         AND
                                            pcl.Product_ID = p.Product_ID)
                                        LEFT JOIN 
                                            tbl_garage_loading_order ps
                                        ON 
                                         so.Load_Order_ID = ps.Loading_Order_ID 
										WHERE
											s.Sales_Order_ID = "'.$id.'"
                                       
                                        AND 
                                            c.Status_ID = 1
                                        AND 
                                            pcl.Status_ID = 1




				'.$condition.'GROUP BY ps.Loading_Order_ID');
		while ($row=$this->db->assoc($query)) {
			$row['Product_Discount'] = 0;
			$data[] = $row;
		}

		return $data;

	}

	public function viewSalesOrderForInvoices($load_id) {
		$data = array();
		$query = $this->db->query('SELECT
										s.Sales_Order_ID,
										s.Zone_ID
									FROM 
										tbl_garage_sales_order s
									WHERE 
										s.Load_Order_ID = "'.$load_id.'"
				');
		while ($row=$this->db->assoc($query)) {
			$query2 = $this->db->query('SELECT 
											Sales_ID 
										FROM 
											tbl_invoices
										WHERE 
											Sales_ID = "'.$row['Sales_Order_ID'].'"');
			$row2 = $this->db->assoc($query2);
			if (!is_null($row2['Sales_ID']))
				$val = 'True';
			else
				$val = 'False';
			$row['Exists'] = $val;
			$data[] = $row;
			$val = '';
		}

		return $data;

	}

	public function viewSumPaymentInLoadingOrder($load_id) {
		$data = array();
		$total_paid = 0;
		$total = 0;
		$query = $this->db->query('SELECT
											i.Invoice_Paid_Amount,
											i.Invoice_Net_Total,
											i.Invoice_Currency,
											i.Sales_ID,
											i.Invoice_Net_Total - i.Invoice_Paid_Amount AS Invoice_Credit,
											c.Currency_Symbol,
                                            i.Customer_ID,
                                            ct.Customer_Name
										FROM 
											tbl_invoices i
										LEFT JOIN 
											tbl_common_currency c
										ON
											c.Currency_ID = i.Invoice_Currency 
										LEFT JOIN 
											tbl_garage_sales_order d
										ON
											d.Sales_Order_ID = i.Sales_ID 
                                        LEFT JOIN
                                            tbl_customers ct
                                        ON
                                            ct.Customer_ID = i.Customer_ID
										WHERE
											d.Load_Order_ID = "'.$load_id.'"
										OR 
											i.Load_ID = "'.$load_id.'"
				');
		while ($row=$this->db->assoc($query)) {
			$total_paid += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Invoice_Currency'],$row['Invoice_Paid_Amount']);
			$total      += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Invoice_Currency'],$row['Invoice_Net_Total']);
			$data[] = $row;
		}

		$data['Total_Paid']   = $total_paid;
		$data['Total_Credit'] = $total - $total_paid;
		$data['Total']        = $total;

		return $data;

	}

	public function calculateLoadingOrderAfterReturn($LID){
		$data = array();
		$salesID = array();
		$checkSales = $this->db->query('SELECT
                                          DISTINCT c.Class_ID AS Class_ID
                                        FROM
                                            tbl_garage_sales_order s
                                        LEFT JOIN
                                            tbl_garage_loading_order l
                                        ON
                                            s.Load_Order_ID = l.Loading_Order_ID
                                        LEFT JOIN
                                            tbl_customers c
                                        ON
                                            c.Customer_ID = s.Customer_ID
                                        WHERE
                                            l.Loading_Order_ID = "'.$LID.'"

                                        ');
		while($sales = $this->db->assoc($checkSales)){
			$salesID[] = $sales;
		}
		$additional = $this->db->query('SELECT
                                            Product_Added_Quantity
                                        FROM
                                            tbl_garage_loading_order_details
                                        WHERE
                                            Loading_ID = "'.$LID.'"
                                    ');
		$additioalQty = $this->db->assoc($additional);

		if(count($salesID) != 1 or($salesID[0]['Class_ID'] != 1 and count($salesID) == 1 and $additioalQty['Product_Added_Quantity'] > 0)){

			$query = $this->db->query('SELECT 
										g.*,
										p.*,
                                        cu.*
									FROM 
										tbl_garage_load_returns g 
									LEFT JOIN 
										tbl_stock_products p
									ON
										p.Product_ID = g.Product_ID
                                    LEFT JOIN 
                                       tbl_common_currency cu
                                    ON 
                                       cu.Currency_ID = p.Currency_ID

									WHERE 
                                        Loading_Order_ID = "'.$LID.'"
                                    AND 
                                        g.Status_ID = 1
									');
			while($row = $this->db->fetch($query)){
				$row['Total_price'] = 0;
				$data[] = $row;
			}
		}else{
			$query = $this->db->query('SELECT 
										g.*,
										p.Product_Code,
										p.Product_Name,
                                        pcl.Product_Price,
                                        cu.*,
                                        (g.Total_Remaining_Qty * pcl.Product_Price) AS Total_Price
									FROM 
										tbl_garage_load_returns g 
									LEFT JOIN 
										tbl_stock_products p
									ON
										p.Product_ID = g.Product_ID
                                    LEFT JOIN 
                                        tbl_garage_loading_order ps
                                    ON 
                                     g.Loading_Order_ID = ps.Loading_Order_ID 
                                    LEFT JOIN 
                                        tbl_garage_sales_order so
                                    ON
                                        so.Load_Order_ID = ps.Loading_Order_ID 

                                    LEFT JOIN
                                        tbl_item_price_by_classes pcl
                                    ON 
                                        p.Product_ID = pcl.Product_ID
                                    LEFT JOIN 
                                       tbl_common_currency cu
                                    ON 
                                       cu.Currency_ID = pcl.Currency_ID

									WHERE 
                                        g.Loading_Order_ID = "'.$LID.'"
                                    AND 
                                        pcl.Status_ID = 1
                                    AND 
                                        pcl.Class_ID = "'.$salesID[0]['Class_ID'].'"
                                    AND 
                                        g.Status_ID = 1
                                    GROUP BY
                                        p.Product_ID
									');
			while($row = $this->db->fetch($query)){
				$data[] = $row;
			}


		}
		$data['count'] = count($salesID);
		return $data;
	}

	public function viewLoadReturn($load_id){
		$data = array();
		$query = $this->db->query('SELECT 
                                        *
									FROM 
										tbl_garage_load_returns

                                    WHERE
                                        Loading_Order_ID="'.$load_id.'"



				');
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;
	}


	public function EditSalesOrder($sales_id){


		$data = array();
		$query = $this->db->query('SELECT 
                                        go.*,
                                        gsd.*,
                                        p.Product_Code,
                                        p.Product_Name,
                                        z.Zone_Name,
                                        c.Customer_Name,
                                        c.Customer_Company,
                                        c.Customer_Email,
                                        c.Customer_Phone,
                                        c.Customer_Address,
                                        cy.Country_Name,
										CONCAT(e.Employee_FirstName, " ", e.Employee_MiddleName, " ", e.Employee_LastName) AS Employee_Name

									FROM 
										tbl_garage_sales_order go
                                    INNER JOIN
                                        tbl_garage_sales_order_details gsd
                                    ON
                                        gsd.Sales_Order_ID = go.Sales_Order_ID
                                    LEFT JOIN
                                        tbl_stock_products p
                                    ON
                                        p.Product_ID = gsd.Product_ID
                                    LEFT JOIN
                                        tbl_garage_vehicle_zone z
                                    ON
                                        z.Zone_ID = go.Zone_ID 
                                    LEFT JOIN
                                        tbl_customers c
                                    ON
                                        c.Customer_ID = go.Customer_ID
				                    LEFT JOIN 
								        tbl_all_countries cy
								    ON 
								        c.Customer_Country_ID = cy.Country_ID
									LEFT JOIN
										tbl_common_users u
									ON 
										u.User_ID = go.Logged_ID
									LEFT JOIN 
										tbl_hrm_employee  e
									ON 
										e.Employee_ID = u.Employee_ID	

                                    WHERE
                                        gsd.Sales_Order_ID="'.$sales_id.'"



				');
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;

	}


	public function updateSalesOrder($sales_id) {
		$query = $this->db->query('UPDATE
										tbl_garage_sales_order 
									SET 
										Customer_ID 	 = "'.$this->info['Customer_ID'].'",
										Logged_ID 		 = "'.$this->info[0].'",
										Sales_Order_Date = "'.$this->info['Sales_Order_Date'].'",
										Zone_ID 		 = "'.$this->info['Zone_ID'].'"
									WHERE 
										Sales_Order_ID 	 = "'.$sales_id.'"
				');
		if ($query) {
			$j = 0;
			$update = $this->db->query('UPDATE
													tbl_garage_sales_order_details 
												SET 
													Sales_Order_ID 	 = "'.$this->info['Sales_Order_ID'].'",
													Product_ID 		 = "'.$this->info['Products'][0]['Product_ID'].'",
													Quantity 		 = "'.$this->info['Products'][0]['Product_Quantity'].'"
												WHERE 
													Item_ID 	 	 = "'.$this->info['Products'][0]['Item_ID'].'"
						');
			if ($update) 
				$j++;
			for ($i=1; $i<count($this->info['Products']); $i++) {
				if ($this->info['Products'][$i]['Item_ID'] == $this->info['Products'][0]['Item_ID'] ) {
					$add = $this->db->query('INSERT INTO
													tbl_garage_sales_order_details ( 
															Sales_Order_ID,
															Product_ID,
															Quantity
													)
													VALUES (
															"'.$sales_id.'",	
															"'.$this->info['Products'][$i]['Product_ID'].'",
															"'.$this->info['Products'][$i]['Product_Quantity'].'"	
													)
						');
					if ($add)
						$j++;
				}
				else {
					$update = $this->db->query('UPDATE
													tbl_garage_sales_order_details 
												SET 
													Sales_Order_ID 	 = "'.$this->info['Sales_Order_ID'].'",
													Product_ID 		 = "'.$this->info['Products'][$i]['Product_ID'].'",
													Quantity 		 = "'.$this->info['Products'][$i]['Product_Quantity'].'"
												WHERE 
													Item_ID 	 	 = "'.$this->info['Products'][$i]['Item_ID'].'"
								');
					if ($update) 
						$j++;
				}

			}

		}
		return false;
	}
	public function addAdditionalLoad(){
		if (self::LoadingOrderExists()) {
			$query = $this->db->query('UPDATE 
											tbl_garage_loading_order_details
										SET 
											Product_Added_Quantity = "'.$this->info['Added_Quantity'].'"
										WHERE 
                                            Product_ID = "'.$this->info['Product_ID'].'" 
                                        AND 
                                            Loading_ID = "'.$this->info['Loading_ID'].'"
					');
		}
		else{

			$query = $this->db->query('INSERT INTO tbl_garage_loading_order_details
                                            (
                                                Loading_ID,
                                                Product_ID,
                                                Added_Quantity
                                            )
                                                VALUES
                                            (
                                               	"'.$this->info['Loading_ID'].'",
												"'.$this->info['Product_ID'].'",
												"'.$this->info['Added_Quantity'].'"
                                            )
                      ');


		}
		if($query)
			return true;
		return false;




	}
	private function LoadingOrderExists() {
		$query = $this->db->query('SELECT 
										* 
									FROM 
										tbl_garage_loading_order_details 
									WHERE 
										Product_ID = "'.$this->info['Product_ID'].'" 
									AND 
										Loading_ID = "'.$this->info['Loading_ID'].'"
				');
		$result = $this->db->rowsno($query);
		if ($result != 0)
			return true;
		return false;
	}

	public function viewLoadedQuantityToReturn($load_id){

		$data = array();
		$query = $this->db->query('SELECT 
                                        glod.Loading_ID,
                                        glod.Product_ID,
                                        glod.Initial_Quantity + glod.Product_Added_Quantity AS Total_Quantity,
                                        sp.Product_ID,
                                        sp.Product_Code,
                                        sp.Product_Name

                                   FROM
                                        tbl_garage_loading_order_details glod
                                   LEFT JOIN
                                        tbl_stock_products sp
                                   ON
                                         sp.Product_ID = glod.Product_ID
                                   WHERE    
                                        glod.Loading_ID = "'.$load_id.'"
                                    GROUP BY 
                                        glod.Product_ID
                                ');    
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;


	}
	public function viewLoadedDetailsToReturn($id){

		$data = array();
		$ordersquery = $this->db->query('SELECT Sales_Order_ID
                                        FROM
                                            tbl_garage_sales_order s
                                        WHERE
                                            s.Load_Order_ID = "'.$id.'"');  

		$orders = $this->db->assoc($ordersquery);
		if(!is_null($orders)){
			$query = $this->db->query('SELECT 

										c.Customer_Name,
										s.*,
										v.Vehicle_Registration_Number,
										o.*,
										z.Zone_Name,
										CONCAT(dk.Employee_FirstName, " ", dk.Employee_MiddleName, " ", dk.Employee_LastName) AS Driver_Name,
										CONCAT(sm.Employee_FirstName, " ", sm.Employee_MiddleName, " ", sm.Employee_LastName) AS Sales_Man_Name,
										CONCAT(l.Employee_FirstName, " ", l.Employee_MiddleName, " ", l.Employee_LastName) AS Logged_Name
									FROM 
										tbl_garage_loading_order o
									LEFT JOIN
										tbl_garage_vehicle v
									ON 
										v.Vehicle_ID = o.Vehicle_ID 
									LEFT JOIN 
										tbl_hrm_employee dk
									ON 
										o.Driver_ID = dk.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee sm
									ON 
										o.Sales_Man_ID = sm.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee l
									ON 
										o.Logged_ID = l.Employee_ID
									LEFT JOIN 
										tbl_garage_sales_order s
									ON 
										o.Loading_Order_ID = s.Load_Order_ID
									LEFT JOIN 
										tbl_garage_vehicle_zone z
									ON 
										z.Zone_ID = s.Zone_ID
									LEFT JOIN 
										tbl_customers c
									ON 
										c.Customer_ID = s.Customer_ID

									WHERE 
										s.Load_Order_ID = "'.$id.'"

									AND 
										s.Assign_To > 0
                                ');    
			while($row=$this->db->assoc($query))
				$data[] = $row;
		}else{
			$query = $this->db->query('SELECT 
										v.Vehicle_Registration_Number,
										o.*,
										z.Zone_Name,
                                        z.Zone_ID,
										CONCAT(dk.Employee_FirstName, " ", dk.Employee_MiddleName, " ", dk.Employee_LastName) AS Driver_Name,
										CONCAT(sm.Employee_FirstName, " ", sm.Employee_MiddleName, " ", sm.Employee_LastName) AS Sales_Man_Name,
										CONCAT(l.Employee_FirstName, " ", l.Employee_MiddleName, " ", l.Employee_LastName) AS Logged_Name
									FROM 
										tbl_garage_loading_order o
									LEFT JOIN
										tbl_garage_vehicle v
									ON 
										v.Vehicle_ID = o.Vehicle_ID 
                                    LEFT JOIN
										tbl_garage_vehicle_driver vd
									ON 
										v.Vehicle_ID = vd.Vehicle_ID
									LEFT JOIN 
										tbl_hrm_employee dk
									ON 
										o.Driver_ID = dk.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee sm
									ON 
										o.Sales_Man_ID = sm.Employee_ID
									LEFT JOIN 
										tbl_hrm_employee l
									ON 
										o.Logged_ID = l.Employee_ID
									LEFT JOIN 
										tbl_garage_vehicle_zone z
									ON 
										z.Zone_ID = vd.Vehicle_Zone_ID
									WHERE 
										o.Loading_Order_ID = "'.$id.'"
				');
			while($row = $this->db->assoc($query)){
				$data[] = $row;
			}

		}
		return $data;
	}

	public function addEmployeeAdvance() {
		if (!in_array(4,$this->info['Types']))
			self::addAutometicInvoice();
		$j = 0;
		for ($i=0;$i<count($this->info['Details']);$i++) {
			$detail = $this->info['Details'][$i];
			$query = $this->db->query('INSERT INTO 
                                            tbl_inventory_loading_order_payments (
                                                Loading_Order_ID,
                                                Type_ID,
                                                Payment_Amount,
                                                Currency_ID
                                            )
                                            Values (
                                                "'.$this->info['Load_ID'].'",
                                                "'.$detail['Type_ID'].'",
                                                "'.$detail['Payment_Amount'].'",
                                                "'.$detail['Currency_ID'].'"
                                            )
                    ');
			if ($query)
				$j++;
		}
		if ($i==$j) {

			$desc = "Advance Payment to ".$this->info['Driver_Name']." taken from loading order number ".$this->info['Load_ID'];
			$query = $this->db->query('INSERT INTO tbl_hrm_advance_payments( Advance_Payment_Date,
                                                                            Advance_Payment_Amount,
                                                                            Advance_Payment_Description,
                                                                            Currency_ID,
                                                                            Employee_ID
                                                                            )
                                                                    VALUES( "'.$this->info['Date'].'",
                                                                            "'.$this->info['Amount'].'",
                                                                            "'.$desc.'",
                                                                            "'.$this->info['Currency_ID'].'",
                                                                            "'.$this->info['Driver_ID'].'"
                                                                            )

                    ');
			//perssonal
			$jv = JV::returnJV();

			$advance = $this->db->query('SELECT MAX(Advance_Payment_ID) AS max_payment FROM tbl_hrm_advance_payments');
			$advance_row = $this->db->assoc($advance);
			$advance_ID = $advance_row['max_payment'];

			$data_1 = array(
				"JV_ID" => $jv,
				"Transaction_Reference" => $advance_ID,
				"Transaction_Account" => '421',
				"Transaction_Type" => "Debit",
				"Transaction_Amount" => $this->info['Amount'],
				"Transaction_Date" => $this->info['Date'],
				"Currency_ID" => $this->info['Currency_ID'],
				"Logged_ID" => $this->info[0],
				"Transaction_Description" => $desc,
				"Current_Ex_Rate" => "0"
			);
			JV::addTransaction($data_1);
			//payment

			$data_2 = array(
				"JV_ID" => $jv,
				"Transaction_Reference" => $advance_ID,
				"Transaction_Account" => '53',
				"Transaction_Type" => "Credit",
				"Transaction_Amount" => $this->info['Amount'],
				"Transaction_Date" => $this->info['Date'],
				"Currency_ID" => $this->info['Currency_ID'],
				"Logged_ID" => $this->info[0],
				"Transaction_Description" => $desc,
				"Current_Ex_Rate" => "0"
			);
			JV::addTransaction($data_2);
			//after done update load to be 3
			if($query)

				return true;
			return false;

		}
		return false;


	}





	public function updateLoadStatus($load_id) {
		$query = $this->db->query('UPDATE 
										tbl_garage_loading_order 
									SET 
										Is_Load = 3
									WHERE 
										Loading_Order_ID = "'.$load_id.'"
				');
		if ($query)
			return true;
		return false;
	}
	public function viewSalesDetailsByID($id){
		$data = array();
		$query = $this->db->query('SELECT
											s.*,
											p.Product_Code,
                                            p.Product_Name,
                                            pcl.Product_Price,
                                            pcl.Class_ID,
                                            s.Sales_Order_ID
										FROM 
											tbl_garage_sales_order_details s
										LEFT JOIN 
											tbl_garage_sales_order so
										ON
											so.Sales_Order_ID = s.Sales_Order_ID
                                        LEFT JOIN
                                            tbl_customers c
                                        ON
                                            c.Customer_ID = so.Customer_ID
                                        LEFT JOIN
                                            tbl_item_price_by_classes pcl
                                        ON 
                                            c.Class_ID = pcl.Class_ID
										INNER JOIN 
											tbl_stock_products p
										ON
											(s.Product_ID = p.Product_ID
                                         AND
                                            pcl.Product_ID = p.Product_ID) 
										WHERE
											s.Sales_Order_ID = "'.$id.'"
                                        
                                        AND 
                                            c.Status_ID = 1
                                        AND 
                                            pcl.Status_ID = 1
                            ');
		while($row = $this->db->assoc($query)){
			$data[] = $row;
		}
		return $data;


	}

	public function addLoadingOrderWithoutSalesOrder() {
		$query = $this->db->query('INSERT INTO
                                        tbl_garage_loading_order (
                                            Vehicle_ID,
                                            Shift_ID,
                                            Driver_ID,
                                            Sales_Man_ID,
                                            Loading_Order_Date,
                                            Class_ID,
                                            Logged_ID
                                        )
                                        VALUES(
                                            "'.$this->info['Vehicle_ID'].'",
                                            "'.$this->info['Shift_ID'].'",
                                            "'.$this->info['Driver_ID'].'",
                                            "'.$this->info['Sales_Man_ID'].'",
                                            "'.$this->info['Loading_Order_Date'].'",
                                            "'.$this->info['Class_ID'].'",
                                            "'.$this->info[0].'"
                                        )
                ');
		if ($query) {
			$j = 0;
			$load_id_query = $this->db->query('SELECT MAX(Loading_Order_ID) AS Loading_ID FROM tbl_garage_loading_order');
			$load_assoc = $this->db->assoc($load_id_query);
			$load_id = $load_assoc['Loading_ID'];
			for ($i=0; $i<count($this->info['products']); $i++) {
				$cur_product = $this->info['products'][$i];

				$product = $this->db->query('INSERT INTO
                                                tbl_garage_loading_order_details (
                                                    Loading_ID,
                                                    Product_ID,
                                                    Initial_Quantity
                                                )
                                                VALUES(
                                                    "'.$load_id.'",
                                                    "'.$cur_product['Product_ID'].'",
                                                    "'.$cur_product['Product_Quantity'].'"
                                                )
                        ');
				if ($product)
					$j++;
			}
			if ($j == $i)
				return true;
		}
		return false;
	}

	public function returnProductIDByCodeAndName($code,$name) {
		$query = $this->db->query('SELECT Product_ID FROM tbl_stock_products WHERE Product_Name = "'.$name.'" AND Product_Code = "'.$code.'"');
		$product = $this->db->assoc($query);
		return $product['Product_ID'];
	}
	public function CheckIfSales($id){
		$data = array();
		$query = $this->db->query('SELECT
                                    Sales_Order_ID
                                    FROM
                                        tbl_garage_sales_order
                                    WHERE
                                        Load_Order_ID = "'.$id.'"');
		$row = $this->db->assoc($query);
		if(!is_null($row))
			$data['Exist'] = 1;
		else
			$data['Exist'] = 0;

		return $data;


	}
	private function IfLoadingOrderExists($id,$pid) {
		$query = $this->db->query('SELECT 
										* 
									FROM 
										tbl_garage_loading_order_details 
									WHERE 
										Product_ID = "'.$pid.'" 
									AND 
										Loading_ID = "'.$id.'"
				');
		$result = $this->db->rowsno($query);
		if ($result != 0)
			return true;
		return false;
	}
	public function getSalesOrderNumber(){
		$data = array();
		$today = Date::getToday();
		$count = 0;
		$totalPrice = 0;
		$query = $this->db->query('SELECT
                                        COUNT(Sales_Order_ID) AS count
                                    FROM
                                        tbl_garage_sales_order
                                    WHERE
                                        Sales_Order_Date = "'.$today.'"

        ');
		$row = $this->db->assoc($query);
		$count = $row['count'];

		$query1 = $this->db->query('SELECT
                                        (d.Quantity * c.Product_Price) AS Total,
                                        c.Currency_ID
                                    FROM
                                        tbl_garage_sales_order_details d
                                    LEFT JOIN
                                        tbl_garage_sales_order s
                                    ON
                                        d.Sales_Order_ID = s.Sales_Order_ID
                                    LEFT JOIN
                                        tbl_customers cr
                                    ON
                                        cr.Customer_ID = s.Customer_ID
                                    LEFT JOIN
                                        tbl_item_price_by_classes c
                                    ON
                                        (c.Class_ID = cr.Class_ID
                                    AND 
                                        d.Product_ID = c.Product_ID)

                                    WHERE
                                        Sales_Order_Date = "'.$today.'" 



                                ');
		while($row = $this->db->assoc($query1)){
			$totalPrice+=CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'],$row['Total']);
		}
		$data['total'] = $totalPrice;
		$data['count'] = $count;

		return $data;


	}

	public function deleteLoadingOrder($id){
		$cancelLoad = false;
		$query = $this->db->query('SELECT 
                                        Is_Load
                                    FROM
                                        tbl_garage_loading_order
                                    WHERE
                                        Loading_Order_ID = "'.$id.'"


                                    ');
		$Load = $this->db->assoc($query);
		$LoadStatus = $Load['Is_Load'];

		if($LoadStatus == 1){
			$cancelLoad = $this->db->query('UPDATE
                                                tbl_garage_loading_order
                                            SET 
                                                Is_Load = 4
                                            WHERE
                                                Loading_Order_ID = "'.$id.'"

                                        ');


			if($cancelLoad)
				return true;
		}else
			if($LoadStatus == 2){
				$loadProducts = $this->db->query('SELECT
                                                Product_ID,
                                                Product_Load_Quantity AS Qty
                                            FROM
                                                tbl_garage_loading_order_details 
                                            WHERE
                                                Loading_ID = "'.$id.'"

                                        ');
				$i = 0;
				$j = 0;
				while($row = $this->db->assoc($loadProducts)){
					$i++;
					$returnQty = $this->db->query('UPDATE
                                                    tbl_stock_product_location
                                                SET 
                                                    Product_Depot_Quantity =Product_Depot_Quantity + "'.$row['Qty'].'"
                                                WHERE
                                                    Location_Product_ID = "'.$row['Product_ID'].'"
                                                AND 
                                                    Status_ID = 1
                                                AND 
                                                    Product_Depot_ID = 1


                                            ');
					if($returnQty)
						$returnStockQty = $this->db->query('UPDATE
                                                    tbl_stock_products
                                                SET 
                                                    Product_Quantity =Product_Quantity + "'.$row['Qty'].'"
                                                WHERE
                                                    Product_ID = "'.$row['Product_ID'].'"
                                                AND 
                                                    Status_ID = 1



                                            ');
					if($returnStockQty)
						$j++;

				}
				if($i == $j){
					$cancelLoad = $this->db->query('UPDATE
                                                tbl_garage_loading_order
                                            SET 
                                                Is_Load = 4
                                            WHERE
                                                Loading_Order_ID = "'.$id.'"
                                                 ');




					if($cancelLoad){

						$updateSales = $this->db->query('UPDATE
                                                tbl_garage_sales_order
                                            SET 
                                                Assign_To = 0,
                                                Load_Order_ID = 0
                                            WHERE
                                                Load_Order_ID = "'.$id.'"

                                            ');
						if($updateSales)
							return true;
					}
				}
			}
		return false;

	}
	public function deleteSalesOrder($id){
		$update = $this->db->query('UPDATE
                                        tbl_garage_sales_order
                                    SET 
                                        Sales_Status = 3,
                                        Assign_To = 0,
                                        Load_Order_ID = 0
                                    WHERE
                                        Sales_Order_ID = "'.$id.'"


                                ');
		if($update)
			return true;
		return false;



	}

	public function viewLoadOrderValue($load_id) {
		$sales_ids = $this->db->query('SELECT 
                                            COUNT(Sales_Order_ID) AS Count_Sales
                                        FROM 
                                            tbl_garage_sales_order 
                                        WHERE 
                                            Load_Order_ID = "'.$load_id.'"
                    ');
		$row_sales = $this->db->assoc($sales_ids);
		$sales_count = $row_sales['Count_Sales'];
		$total_price = 0.0;
		$load_class_query = $this->db->query('SELECT 
                                                    Class_ID 
                                                FROM 
                                                    tbl_garage_loading_order 
                                                WHERE
                                                    Loading_Order_ID = "'.$load_id.'"
                            ');
		$row_class_id = $this->db->assoc($load_class_query);
		$class_id = $row_class_id['Class_ID'];
		if ($sales_count == 0) {
			$load_class_query = $this->db->query('SELECT 
                                                        lr.Total_Remaining_Qty * p.Product_Price AS Rem_Price,
                                                        p.Currency_ID
                                                    FROM 
                                                        tbl_garage_load_returns lr
                                                    LEFT JOIN 
                                                        tbl_item_price_by_classes p
                                                    ON 
                                                        p.Product_ID = lr.Product_ID
                                                    WHERE    
                                                        p.Class_ID = "'.$class_id.'"
                                                    AND 
                                                        lr.Status_ID = 1
                                                    AND 
                                                        p.Status_ID = 1
                                                    AND 
                                                        lr.Loading_Order_ID = "'.$load_id.'"
                                ');
			while ($row_price = $this->db->assoc($load_class_query))
				$total_price += CurrencyFactory::returnPriceInDefaultCurrencyValue($row_price['Currency_ID'],$row_price['Rem_Price']); 
		}
		else {
			$sales_price = 0.0;
			$return_damaged_price = 0.0;
			$added_price = 0.0;
			$load_class_query = $this->db->query('SELECT 
                                                        sd.Quantity * p.Product_Price AS Sales_Price,
                                                        p.Currency_ID
                                                    FROM 
                                                        tbl_garage_sales_order_details sd
                                                    LEFT JOIN 
                                                        tbl_garage_sales_order s
                                                    ON 
                                                        s.Sales_Order_ID = sd.Sales_Order_ID
                                                    LEFT JOIN 
                                                        tbl_customers c
                                                    ON 
                                                        s.Customer_ID = c.Customer_ID
                                                    LEFT JOIN 
                                                        tbl_item_price_by_classes p
                                                    ON 
                                                        p.Product_ID = sd.Product_ID
                                                    AND 
                                                        p.Class_ID = c.Class_ID
                                                    WHERE   
                                                        p.Status_ID = 1
                                                    AND 
                                                        s.Load_Order_ID = "'.$load_id.'"
                                                    AND 
                                                        c.Status_ID = 1
                                ');
			while ($row_price = $this->db->assoc($load_class_query))
				$sales_price += CurrencyFactory::returnPriceInDefaultCurrencyValue($row_price['Currency_ID'],$row_price['Sales_Price']); 
			$return_query = $this->db->query('SELECT 
                                                    (lr.Return_Quantity + lr.Damaged_Quantity ) * p.Product_Price AS Return_Damaged_Price,
                                                    p.Currency_ID
                                                FROM 
                                                    tbl_garage_load_returns lr
                                                LEFT JOIN 
                                                    tbl_item_price_by_classes p
                                                ON 
                                                    p.Product_ID = lr.Product_ID
                                                WHERE    
                                                    p.Class_ID = "'.$class_id.'"
                                                AND 
                                                    lr.Status_ID = 1
                                                AND 
                                                    p.Status_ID = 1
                                                AND 
                                                    lr.Loading_Order_ID = "'.$load_id.'"
                            ');
			while ($row_r_d = $this->db->assoc($return_query))
				$return_damaged_price += CurrencyFactory::returnPriceInDefaultCurrencyValue($row_r_d['Currency_ID'],$row_r_d['Return_Damaged_Price']);
			$added_query = $this->db->query('SELECT 
                                                    lr.Product_Added_Quantity * p.Product_Price AS Added_Price,
                                                    p.Currency_ID
                                                FROM 
                                                    tbl_garage_loading_order_details lr
                                                LEFT JOIN 
                                                    tbl_item_price_by_classes p
                                                ON 
                                                    p.Product_ID = lr.Product_ID
                                                WHERE    
                                                    p.Class_ID = "'.$class_id.'"
                                                AND 
                                                    p.Status_ID = 1
                                                AND 
                                                    lr.Loading_ID = "'.$load_id.'"
                            ');
			while ($row_added = $this->db->assoc($added_query))
				$added_price += CurrencyFactory::returnPriceInDefaultCurrencyValue($row_added['Currency_ID'],$row_added['Added_Price']);
			$total_price = $sales_price + $added_price - $return_damaged_price;

		}

		return round($total_price,2);
	}

	private function addAutometicInvoice() {
		$load_class_query = $this->db->query('SELECT 
                                                    Class_ID 
                                                FROM 
                                                    tbl_garage_loading_order 
                                                WHERE
                                                    Loading_Order_ID = "'.$this->info['Load_ID'].'"
                            ');
		$row_class_id = $this->db->assoc($load_class_query);
		$class_id = $row_class_id['Class_ID'];
		$invoice = $this->db->query('INSERT INTO   
                                        tbl_invoices (
                                            Invoice_Date,
                                            Invoice_Currency,
                                            Invoice_Sub_Total,
                                            Invoice_Net_Total,
                                            Invoice_Due_Date,
                                            Invoice_Paid_Amount,
                                            Invoice_Status,
                                            Logged_ID,
                                            Load_ID
                                        )
                                        VALUES (
                                            "'.$this->info['Date'].'",
                                            "'.$this->info['Currency_ID'].'",
                                            "'.$this->info['Amount'].'",
                                            "'.$this->info['Amount'].'",
                                            "'.$this->info['Date'].'",
                                            "'.$this->info['Amount'].'",
                                            "2",
                                            "'.$this->info[0].'",
                                            "'.$this->info['Load_ID'].'"
                                        )
                    ');
		$invoice_id = $this->db->query('SELECT MAX(Invoice_ID) AS Max_Invoice FROM tbl_invoices');
		$row_invoice = $this->db->assoc($invoice_id);
		$inv_id = $row_invoice['Max_Invoice'];
		$load_details = $this->db->query('SELECT 
                                                r.Product_ID,
                                                r.Total_Remaining_Qty AS Product_Quantity,
                                                r.Total_Remaining_Qty * p.Product_Price AS Product_Net_Price,
                                                p.Currency_ID
                                            FROM 
                                                tbl_garage_load_returns r
                                             LEFT JOIN 
                                                tbl_item_price_by_classes p
                                            ON 
                                                p.Product_ID = r.Product_ID
                                            WHERE    
                                                p.Class_ID = "'.$class_id.'"
                                            AND 
                                                p.Status_ID = 1
                                            AND 
                                                r.Status_ID = 1
                                            AND 
                                                r.Loading_Order_ID = "'.$this->info['Load_ID'].'"

                        ');
		while ($row = $this->db->assoc($load_details)) {
			$price = CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'],$row['Product_Net_Price']);
			$insert = $this->db->query('INSERT INTO
                                            tbl_invoice_products_details (
                                                Invoice_ID,
                                                Product_ID,
                                                Product_Net_Price,
                                                Product_Quantity,
                                                Product_Total_Price
                                            )
                                            VALUES (
                                                "'.$inv_id.'",
                                                "'.$row['Product_ID'].'",
                                                "'.$price.'",
                                                "'.$row['Product_Quantity'].'",
                                                "'.$price.'"
                                            )
                    ');
		}
		$jv = JV::returnJV();

		$desc = 'Road customer invoice for tje loading order number: '.$this->info['Load_ID'];

		$data_3 = array(
			"JV_ID" => $jv,
			"Transaction_Reference" => $inv_id,
			"Transaction_Account" => '70',
			"Transaction_Type" => "Credit",
			"Transaction_Amount" => $this->info['Amount'],
			"Transaction_Date" => $this->info['Date'],
			"Currency_ID" => $this->info['Currency_ID'],
			"Logged_ID" => $this->info[0],
			"Transaction_Description" => $desc,
			"Current_Ex_Rate" => "0"
		);
		JV::addTransaction($data_3);
		for ($i=0;$i<count($this->info['Details']);$i++) {
			$tem = $this->info['Details'];
			$data_4 = array(
				"JV_ID" => $jv,
				"Transaction_Reference" => $inv_id,
				"Transaction_Account" => $tem['Payment_Code'],
				"Transaction_Type" => "Debit",
				"Transaction_Amount" => $tem['Payment_Amount'],
				"Transaction_Date" => $this->info['Date'],
				"Currency_ID" => $tem['Currency_ID'],
				"Logged_ID" => $this->info[0],
				"Transaction_Description" => $desc,
				"Current_Ex_Rate" => "0"
			);
			JV::addTransaction($data_4);

		}


	}

	public function submitLoadPayment() {
		$j = 0;
		for ($i=0;$i<count($this->info['Details']);$i++) {
			$detail = $this->info['Details'][$i];
			$query = $this->db->query('INSERT INTO 
                                            tbl_inventory_loading_order_payments (
                                                Loading_Order_ID,
                                                Type_ID,
                                                Payment_Amount,
                                                Currency_ID,
                                                Account_Code
                                            )
                                            Values (
                                                "'.$this->info['Load_ID'].'",
                                                "'.$detail['Type_ID'].'",
                                                "'.$detail['Payment_Amount'].'",
                                                "'.$detail['Currency_ID'].'",
                                                "'.$detail['Payment_Code'].'"
                                            )
                    ');
			$changeStatus = $this->db->query('UPDATE tbl_garage_loading_order SET Is_Load = 3 WHERE Loading_Order_ID = "'.$this->info['Load_ID'].'"');

			if ($query)
				$j++;
		}
		if ($i==$j) {
			if (!in_array(4,$this->info['Types'])) {

				$load_class_query = $this->db->query('SELECT 
                                                            Class_ID 
                                                        FROM 
                                                            tbl_garage_loading_order 
                                                        WHERE
                                                            Loading_Order_ID = "'.$this->info['Load_ID'].'"
                                    ');
				$row_class_id = $this->db->assoc($load_class_query);
				$class_id = $row_class_id['Class_ID'];
				$invoice = $this->db->query('INSERT INTO   
                                                tbl_invoices (
                                                    Invoice_Date,
                                                    Invoice_Currency,
                                                    Invoice_Sub_Total,
                                                    Invoice_Net_Total,
                                                    Invoice_Due_Date,
                                                    Invoice_Paid_Amount,
                                                    Invoice_Status,
                                                    Logged_ID,
                                                    Load_ID
                                                )
                                                VALUES (
                                                    "'.$this->info['Date'].'",
                                                    "'.$this->info['Currency_ID'].'",
                                                    "'.$this->info['Amount'].'",
                                                    "'.$this->info['Amount'].'",
                                                    "'.$this->info['Date'].'",
                                                    "'.$this->info['Amount'].'",
                                                    "2",
                                                    "'.$this->info[0].'",
                                                    "'.$this->info['Load_ID'].'"
                                                )
                            ');
				$invoice_id = $this->db->query('SELECT MAX(Invoice_ID) AS Max_Invoice FROM tbl_invoices');
				$row_invoice = $this->db->assoc($invoice_id);
				$inv_id = $row_invoice['Max_Invoice'];
				$load_details = $this->db->query('SELECT 
                                                        r.Product_ID,
                                                        r.Total_Remaining_Qty AS Product_Quantity,
                                                        r.Total_Remaining_Qty * p.Product_Price AS Product_Net_Price,
                                                        p.Currency_ID
                                                    FROM 
                                                        tbl_garage_load_returns r
                                                     LEFT JOIN 
                                                        tbl_item_price_by_classes p
                                                    ON 
                                                        p.Product_ID = r.Product_ID
                                                    WHERE    
                                                        p.Class_ID = "'.$class_id.'"
                                                    AND 
                                                        p.Status_ID = 1
                                                    AND 
                                                        r.Status_ID = 1
                                                    AND 
                                                        r.Loading_Order_ID = "'.$this->info['Load_ID'].'"

                                ');
				while ($row = $this->db->assoc($load_details)) {
					$price = CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'],$row['Product_Net_Price']);
					$insert = $this->db->query('INSERT INTO
                                                    tbl_invoice_products_details (
                                                        Invoice_ID,
                                                        Product_ID,
                                                        Product_Net_Price,
                                                        Product_Quantity,
                                                        Product_Total_Price
                                                    )
                                                    VALUES (
                                                        "'.$inv_id.'",
                                                        "'.$row['Product_ID'].'",
                                                        "'.$price.'",
                                                        "'.$row['Product_Quantity'].'",
                                                        "'.$price.'"
                                                    )
                            ');
				}
				$jv = JV::returnJV();

				if ($this->info['Amount'] > $this->info['Total_Paid_Amount']) {
					$diff = $this->info['Amount'] - $this->info['Total_Paid_Amount'];
					$query = $this->db->query('INSERT INTO tbl_hrm_advance_payments( Advance_Payment_Date,
                                                                            Advance_Payment_Amount,
                                                                            Advance_Payment_Description,
                                                                            Currency_ID,
                                                                            Employee_ID
                                                                            )
                                                                    VALUES( "'.$this->info['Date'].'",
                                                                            "'.$diff.'",
                                                                            "'.$desc.'",
                                                                            "'.$this->info['Currency_ID'].'",
                                                                            "'.$this->info['Driver_ID'].'"
                                                                            )

                    ');
					if (count ($this->info['Expenses']) > 0) {
						$desc = "Payment of load order, part of payment became advance on the driver and the other divided between cash, cheque and expenses";
						for ($i=0; $i<count($this->info['Expenses']);$i++) {
							$query = $this->db->query('INSERT INTO
                                                            tbl_garage_truck_expenses (
                                                                Truck_ID,
                                                                Truck_Expense_Description,
                                                                Truck_Expense_Amount,
                                                                Currency_ID,
                                                                Truck_Expense_Date,
                                                                Truck_Expense_Account,
                                                                Logged_ID
                                                            )
                                                            VALUES (
                                                                "'.$this->info['Expenses'][$i]['Truck_Code'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Description'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Amount'].'",
                                                                "'.$this->info['Expenses'][$i]['ExpenseCurrency_ID'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Date'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Account'].'",
                                                                "'.$this->info[0].'"
                                                            )
                                    ');

						}
					}
					else
						$desc = "Payment of load order, part of payment became advance on the driver and the other divided between cash and cheque";

					$data_5 = array(
						"JV_ID" => $jv,
						"Transaction_Reference" => $inv_id,
						"Transaction_Account" => '70',
						"Transaction_Type" => "Credit",
						"Transaction_Amount" => $this->info['Amount'],
						"Transaction_Date" => $this->info['Date'],
						"Currency_ID" => $this->info['Currency_ID'],
						"Logged_ID" => $this->info[0],
						"Transaction_Description" => $desc,
						"Current_Ex_Rate" => "0"
					);
					JV::addTransaction($data_5);

					$data_6 = array(
						"JV_ID" => $jv,
						"Transaction_Reference" => $inv_id,
						"Transaction_Account" => '421',
						"Transaction_Type" => "Debit",
						"Transaction_Amount" => $diff,
						"Transaction_Date" => $this->info['Date'],
						"Currency_ID" => $this->info['Currency_ID'],
						"Logged_ID" => $this->info[0],
						"Transaction_Description" => $desc,
						"Current_Ex_Rate" => "0"
					);
					JV::addTransaction($data_6);

				}
				else {
					$desc = "Payment of load order divided between cash and cheque";

					$data_7 = array(
						"JV_ID" => $jv,
						"Transaction_Reference" => $inv_id,
						"Transaction_Account" => '70',
						"Transaction_Type" => "Credit",
						"Transaction_Amount" => $this->info['Amount'],
						"Transaction_Date" => $this->info['Date'],
						"Currency_ID" => $this->info['Currency_ID'],
						"Logged_ID" => $this->info[0],
						"Transaction_Description" => $desc,
						"Current_Ex_Rate" => "0"
					);
					JV::addTransaction($data_7);
				}
				for ($i=0;$i<count($this->info['Details']);$i++) {
					$tem = $this->info['Details'][$i];
					$data_8 = array(
						"JV_ID" => $jv,
						"Transaction_Reference" => $inv_id,
						"Transaction_Account" => $tem['Payment_Code'],
						"Transaction_Type" => "Debit",
						"Transaction_Amount" => $tem['Payment_Amount'],
						"Transaction_Date" => $this->info['Date'],
						"Currency_ID" => $tem['Currency_ID'],
						"Logged_ID" => $this->info[0],
						"Transaction_Description" => $desc,
						"Current_Ex_Rate" => "0"
					);
					JV::addTransaction($data_8);

				}
			}
			else {
				if ($this->info['Amount'] > $this->info['Total_Paid_Amount']) {
					$diff = $this->info['Amount'] - $this->info['Total_Paid_Amount'];
					$desc = "Advance payment on ".$this->info['Driver_Name']." from loading order number ".$this->info['Load_ID'];
					$query = $this->db->query('INSERT INTO tbl_hrm_advance_payments( Advance_Payment_Date,
                                                                            Advance_Payment_Amount,
                                                                            Advance_Payment_Description,
                                                                            Currency_ID,
                                                                            Employee_ID
                                                                            )
                                                                    VALUES( "'.$this->info['Date'].'",
                                                                            "'.$diff.'",
                                                                            "'.$desc.'",
                                                                            "'.$this->info['Currency_ID'].'",
                                                                            "'.$this->info['Driver_ID'].'"
                                                                            )

                    ');
					$advance = $this->db->query('SELECT MAX(Advance_Payment_ID) AS max_payment FROM tbl_hrm_advance_payments');
					$advance_row = $this->db->assoc($advance);
					$advance_ID = $advance_row['max_payment'];
					$jv = JV::returnJV();
					$data_9 = array(
						"JV_ID" => $jv,
						"Transaction_Reference" => $inv_id,
						"Transaction_Account" => '53',
						"Transaction_Type" => "Credit",
						"Transaction_Amount" => $diff,
						"Transaction_Date" => $this->info['Date'],
						"Currency_ID" => $this->info['Currency_ID'],
						"Logged_ID" => $this->info[0],
						"Transaction_Description" => $desc,
						"Current_Ex_Rate" => "0"
					);
					JV::addTransaction($data_9);

					$data_9 = array(
						"JV_ID" => $jv,
						"Transaction_Reference" => $inv_id,
						"Transaction_Account" => '53',
						"Transaction_Type" => "Credit",
						"Transaction_Amount" => $diff,
						"Transaction_Date" => $this->info['Date'],
						"Currency_ID" => $this->info['Currency_ID'],
						"Logged_ID" => $this->info[0],
						"Transaction_Description" => $desc,
						"Current_Ex_Rate" => "0"
					);
					JV::addTransaction($data_9);

				}
				if (count ($this->info['Expenses']) > 0) {
					$desc = "Expense on truck number ".$this->info['Expenses'][0]['Truck_Code']. " with load number ".$this->info['Load_ID'];
					for ($i=0; $i<count($this->info['Expenses']);$i++) {
						$query = $this->db->query('INSERT INTO
                                                            tbl_garage_truck_expenses (
                                                                Truck_ID,
                                                                Truck_Expense_Description,
                                                                Truck_Expense_Amount,
                                                                Currency_ID,
                                                                Truck_Expense_Date,
                                                                Truck_Expense_Account,
                                                                Logged_ID
                                                            )
                                                            VALUES (
                                                                "'.$this->info['Expenses'][$i]['Truck_Code'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Description'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Amount'].'",
                                                                "'.$this->info['Expenses'][$i]['ExpenseCurrency_ID'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Date'].'",
                                                                "'.$this->info['Expenses'][$i]['Truck_Expense_Account'].'",
                                                                "'.$this->info[0].'"
                                                            )
                                    ');
						$expense = $this->db->query('SELECT MAX(Truck_Expense_ID) AS max_id FROM tbl_garage_truck_expenses');
						$expense_row = $this->db->assoc($expense);
						$expense_ID = $expense_row['max_id'];
						$jv = JV::returnJV();
						$data_10 = array(
							"JV_ID" => $jv,
							"Transaction_Reference" => $expense_ID,
							"Transaction_Account" =>$this->info['Expenses'][$i]['Truck_Expense_Account'],
							"Transaction_Type" => "Debit",
							"Transaction_Amount" =>  $this->info['Expenses'][$i]['Truck_Expense_Amount'],
							"Transaction_Date" =>  $this->info['Expenses'][$i]['Truck_Expense_Date'],
							"Currency_ID" =>  $this->info['Expenses'][$i]['ExpenseCurrency_ID'],
							"Logged_ID" => $this->info[0],
							"Transaction_Description" =>  $this->info['Expenses'][$i]['Truck_Expense_Description'],
							"Current_Ex_Rate" => "0"
						);
						JV::addTransaction($data_10);

						$data_11 = array(
							"JV_ID" => $jv,
							"Transaction_Reference" => $expense_ID,
							"Transaction_Account" => '53',
							"Transaction_Type" => "Credit",
							"Transaction_Amount" => $this->info['Expenses'][$i]['Truck_Expense_Amount'],
							"Transaction_Date" => $this->info['Expenses'][$i]['Truck_Expense_Date'],
							"Currency_ID" => $this->info['Expenses'][$i]['ExpenseCurrency_ID'],
							"Logged_ID" => $this->info[0],
							"Transaction_Description" => $this->info['Expenses'][$i]['Truck_Expense_Description'],
							"Current_Ex_Rate" => "0"
						);
						JV::addTransaction($data_11);


					}
				}
			}
			return true;
		}
		return false;
	}
	public function getSalesOrderProduct($id) {
		$data = array();
		$query = $this->db->query('SELECT 
										d.*,
                                        o.*,
                                        p.Product_Code,
                                        p.Product_Name,
                                        p.Product_VAT,
                                        pc.Product_Price,
                                        c.Customer_Name

									FROM 
                                        tbl_garage_sales_order_details d
                                    LEFT JOIN
                                        tbl_stock_products p
                                    ON
                                        p.Product_ID = d.Product_ID
                                    LEFT JOIN
										tbl_garage_sales_order o
                                    ON
                                        d.Sales_Order_ID = o.Sales_Order_ID
                                    LEFT JOIN
                                        tbl_customers c
                                    ON
                                        c.Customer_ID = o.Customer_ID
                                    LEFT JOIN
                                        tbl_item_price_by_classes pc
                                    ON  
                                        (c.Class_ID = pc.Class_ID
                                    AND 
                                        pc.Product_ID = d.Product_ID)
                                    WHERE 
										o.Sales_Order_ID = "'.$id.'"
                                    AND 
                                        p.Status_ID = 1
                                    AND 
                                        pc.Status_ID = 1

				');
		while($row=$this->db->assoc($query))
			$data[] = $row;
		return $data;
	}
	public function viewLoadingOrderPayments($id){
		$data = array();
		$query = $this->db->query('SELECT   
                                        l.*,
                                        c.Currency_Symbol,
                                        o.Account_Name
                                    FROM
                                        tbl_inventory_loading_order_payments  l
                                    LEFT JOIN
                                        tbl_common_currency c
                                    ON
                                        c.Currency_ID = l.Currency_ID
                                    LEFT JOIN
                                        tbl_chart_of_accounts o
                                    ON
                                        l.Account_Code = o.Account_Code
                                    WHERE
                                        Loading_Order_ID = "'.$id.'"


        ');
		while($row = $this->db->assoc($query)){
			$row['Payment_Amount'] = number_format($row['Payment_Amount'], 2, '.', ','); 
			if($row['Type_ID'] == 1)
				$data['Cash'][] = $row;
			else if($row['Type_ID'] == 2)
				$data['Cheque'][] = $row;
			else if($row['Type_ID'] == 3)
				$data['Expense'][] = $row;
			else if($row['Type_ID'] == 4)
				$data['Customers'][] = $row;


		}
		return $data;

	}

	public function addExpenseAccount($expense_name) {
		$Account = array();
		$parent_id_query = $this->db->query('SELECT Account_ID FROM tbl_chart_of_accounts WHERE Account_Code = 6118');
		$parent_assoc = $this->db->assoc($parent_id_query);
		$parent_id = $parent_assoc['Account_ID'];
		$query = $this->db->query('SELECT MAX(Account_Code) AS Max_Code FROM tbl_chart_of_accounts WHERE Parent_ID = "'.$parent_id.'"');
		$max_code_assoc = $this->db->assoc($query);
		if (count($max_code_assoc) == 0) {
			$code = '6118001';
		}
		else {
			$max_code = $max_code_assoc['Max_Code'];
			$code = $max_code + 1;
		}
		$insert = $this->db->query('INSERT INTO tbl_chart_of_accounts (Account_Name,
                                                                        Parent_ID,
                                                                        Account_Code,
                                                                        Account_Status,
                                                                        IsAdded
                                                                        )
                                                                VALUES ( "'.$expense_name.'",
                                                                          "'.$parent_id.'",
                                                                          "'.$code.'",
                                                                          "1",
                                                                          "1"
                                                                        )
                ');
		if ($insert) 
		{
			$query = $this->db->query('SELECT * FROM tbl_chart_of_accounts WHERE Account_Code = "'.$code.'"');
			$Account = $this->db->assoc($query);

		}

		return $Account;
	}





}