<?php
//user_action.php
include('db_con.php');
include('function.php');
$rate = 0;
$cost = 0;
$stock = 0;
 		stock_update($connect);
		$query = "
		SELECT * FROM items WHERE item_id = :item_no";
		
		$statement = $connect->prepare($query);
		$statement->execute(
			array(
				':item_no'	=>	$_POST["item_no"]
			)
		);
		$result = $statement->fetchAll();
		foreach($result as $row)
		{
			
			
			
           $cost          =  $row['item_cost'];
           $stock          =  $row['stock'];
          
          
		}
		
 			$item_detail = '';
 			$item_detail .='
 			<div class="row">
 			<div class="col-md-4">
 			</div>';
			
				
				
				
 			
	
				
$query = "
				SELECT  IFNULL(d.rate,0) rate FROM purchase_detail d,purchase m 
				WHERE m.p_id=d.p_id and
				d.item_no = :item_no";
				
				$statement = $connect->prepare($query);
				$statement->execute(
					array(
						':item_no'	=>	$_POST["item_no"]
						
					)
				);
				$rate = $statement->fetchColumn();
				if($rate > 0)
				{
				 $item_detail .='
			 			
			 			<div class="col-md-8">
			 			<table width ="100%">
			 			<tr>
			 			<th width="20%">Date</th>
			 			<th width="5%">PID</th>
			 			<th width="60%">From</th>
			 			<th width="15%">Rate</th>
			 			</tr>
			 			';
			 			
					$sql = "select m.dated, m.p_id,v.name,ifnull(d.rate,0) rate from purchase_detail d, purchase m,vendors v 
					where m.p_id = d.p_id  and m.v_id=v.v_id and 
					d.item_no = '".$_POST['item_no']."' order by dated desc LIMIT 5";
					 $statement = $connect->prepare($sql);
					 $statement->execute();
					  
					 
					 $result = $statement->fetchAll();
					
						foreach($result as $row)
							{
						  
						  $rate = $row["rate"];
						
							$item_detail .= '
						  
						  
						  
							<tr>
							  <td width="20%">'.$row["dated"].'</td>
							  <td width="10%">'.$row["p_id"].'</td>
							  <td width="50%">'.$row["name"].'</td>
							   <td width="15%" class="rightside"><b>'.number_format($rate, 2).'</b></td>
							  
							   
							    
						    </tr>
						  ';
						}
					}else {$item_detail .= '
						  
						  
						  
							<tr>
							  <td width="20%"></td>
							  <td width="10%"></td>
							  <td width="50%">History : Not found</td>
							   <td width="15%" class="rightside"><b></b></td>
							  
							   
							    
						    </tr>
						  ';}
			  
				$item_detail .='</table><br /></div>';
				$output['item_detail']  =  $item_detail;
				if($rate == 0)
				{
					$sql = " select retail_price from items where item_id = '".$_POST['item_no']."'";
					 $statement = $connect->prepare($sql);
					 $statement->execute();
					 $rate = $statement->fetchColumn();
				}
				$output['rate']  =  $rate;
	
		echo json_encode($output);
?>