<?php 
require('../db/db.php');
require('../classes/classInvoice.php');

if(isset($_GET['editrecinvoiceid'])&&$_GET['editrecinvoiceid']!='')
{
	$recinvoiceid=$_GET['editrecinvoiceid'];
	$_SESSION['invoiceid']=$recinvoiceid;
	
	$supplierid=$_GET['supplierid'];
	$_SESSION['supplierid']=$supplierid;
}
else
{
	$recinvoiceid=$_SESSION['invoiceid'];
	$supplierid=$_SESSION['supplierid'];
}

/*echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;*/

/////////////////////////////Refund Medicine////////////////////////

if(isset($_POST['refund'])&&$_POST['refund']=='Refund Products')
{
	if(isset($_POST['qty'][0])&&$_POST['qty'][0]!=""&&$_POST['qty'][0]!=0)
	{
		for($i=0;$i<count($_POST['recitemsid']);$i++)
		{
			$recitemsid=$_POST['recitemsid'][$i];
			//$packingtype=$_POST['packingtype'][$i];
			$qty=$_POST['qty'][$i];
			//$productid=$_POST['productid'][$i];
			$unitprice=$_POST['price'][$i];
			
			$refundamount = $unitprice*$qty;
			
			######################################### check quantity start ######################################################
			
			$checkQuantityResult = mysqli_query($con,"SELECT * FROM product_recitems WHERE recitems_id='$recitemsid'");
			$checkQuantityArray = mysqli_fetch_assoc($checkQuantityResult);
			$availabel_qty = $checkQuantityArray['qty_received']-$checkQuantityArray['refund_qty'];
			
			######################################### check quantity end ######################################################
			
			if($qty>0&&$qty<=$availabel_qty)
			{
				
				######################################### update in product sales items refund quantity & amount ###################
				
				$query= mysqli_query($con,"UPDATE product_recitems SET refund_status = 'refund' , refund_qty = refund_qty + '$qty' , refund_amount = refund_amount + '$refundamount' where recitems_id='$recitemsid'")or die(mysql_errno());
				
				######################################### update in product quantity ###############################################
				
				$resultdelproductdata = mysqli_query($con,"SELECT * FROM product_recitems WHERE recitems_id='$recitemsid'");
				$dataArray = mysqli_fetch_assoc($resultdelproductdata);
				
				$delProductid=$dataArray['product_id'];
				
				$DelproductData = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$delProductid'");
				$DelproductDataRow = mysqli_fetch_assoc($DelproductData);
				$packingtype = $dataArray['packing_type'];	
				
				if ($dataArray['packing_type']=='Unit/Tablets')
				{
					$afterDelQty = $DelproductDataRow['unit_qtyinstock']- $dataArray['refund_qty'];
				}
				
				if ($dataArray['packing_type']=='Leaf')
				{
					$leafunit=$dataArray['refund_qty']*($DelproductDataRow['unitperbox']/$DelproductDataRow['leafperbox']);
					$afterDelQty = $DelproductDataRow['unit_qtyinstock']- $leafunit;
				}
				
				if ($dataArray['packing_type']=='Box/Pack')
				{
					$boxunit=$dataArray['refund_qty']*$DelproductDataRow['unitperbox'];
					$afterDelQty = $DelproductDataRow['unit_qtyinstock'] - $boxunit;
				}
				
				$query= mysqli_query($con,"UPDATE products set unit_qtyinstock='$afterDelQty' WHERE product_id= '$delProductid'") or die(mysqli_errno());
				
				######################################### insert in product refund items ###############################################
				
				$query= mysqli_query($con,"INSERT INTO product_refunditems (recinvoice_id,product_id,packing_type,qty,refund_amount) VALUES ('$recinvoiceid','$delProductid','$packingtype','$qty','$refundamount')")or die(mysql_errno());
				
				######################################### insert in transactions #######################################################
				
				$accheadid=3;
				$accountid=6;
				$transacttype='Income';
				$amountpayable=$refundamount;
				$payment=$refundamount;
				$balance = $amountpayable-$payment;
				$date = date('Y-m-d',time());
				$username=$_SESSION['myusername'];
				
				$query= mysql_query("INSERT INTO transactions (transact_date, supplier_id, acchead_id,account_id, recinvoice_id, transact_type, transaction_purpose,amount_payable, payment, balance, username) VALUES('$date', '$supplierid', '$accheadid','$accountid', '$recinvoiceid', '$transacttype','refund', '$amountpayable', '$payment', '$balance', '$username')");
				
				
				
			}
			
			
		}
		
		
		header("Location:".$_SERVER['REQUEST_URI']);
		
	}
}



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/print.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="shortcut icon" href="../images/favicon.png">
    <title>Med2TEC Hospital Management Information System</title> 
    <link href="../css/print.css" rel="stylesheet">
    <link href="../datepicker/jquery-ui.css" rel="stylesheet" >  
    <script type="text/javascript" src="../datepicker/jquery-1.9.1.js"></script>
	<script type="text/javascript" src="../datepicker/jquery-ui.js"></script> 
</head>

<body> 
<div align="right"> 
 <SCRIPT LANGUAGE="JavaScript">  
if (window.print) {
document.write('<form class="no-print"><input type=button name=print value="Print" onClick="window.print()"></form>');
}
</script></div>

<section class="wrapper">
<div style="background:#FFF; padding:0px 0px 0; height:auto;">
  <table cellspacing="0" cellpadding="0" width="100%" border="0" style="font-size:11px;">
    <tbody>
      <tr>
        <td align="left" style="background:#fff;"><img alt="" src="../images/org_print_logos/<?php echo $_SESSION['security']['org_id']?>.png" style="width:100%;"></td>
      </tr>
    </tbody>
  </table>
  
</br>

</div>

<div class="row">
          <section class="panel">
            <header class="panel-heading">
              <h2><!-- InstanceBeginEditable name="title" -->SALE INVOICES<!-- InstanceEndEditable --></h2>
            </header>

  <br />
  
<!-- InstanceBeginEditable name="main" -->
<div class="content">
   <table width="100%" border="0" align="left" cellpadding="0" cellspacing="0">
  <tr>
    <td align="right"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="bottomBorder">
      <tr>
        <td valign="bottom"><h1>SUPPLIER REFUNDS</h1><table width="40%" align="left" border="0" cellspacing="0" cellpadding="0" class="rounded_corners">
          
            <tr>
              <td width="25%">Company:</td>
              <td width="75%">
				<?php 	
				$raw_results2 = mysqli_query($con,"SELECT * FROM suppliers WHERE supplier_id='$supplierid'");
				while($row2 = mysqli_fetch_array($raw_results2))
				{ 
					$suppliername=$row2['company_name'];
					echo $suppliername;
				}
				?>
                </td>
            </tr>
            <tr>
              <td>Address:</td>
              <td><?php echo $row2['company_address'];?><p></td>
            </tr>
            <tr>
              <td>Phone:</td>
              <td><?php echo $row2['company_phone'];?><p></td>
            </tr>
            <tr>
              <td>Invoice ID:</td>
              <td><?php  echo $recinvoiceid; ?></td>
            </tr>
          </table></td>
        </tr>
      </table></td>
  </tr>
  <tr>
    <td width="511"><table width="100%">
     <?php
	if(isset($errorMessage)&&$errorMessage!="")
	{
		?>
		<tr>
			<td style="color:red;"><?php echo $errorMessage;?></td>
		</tr>
		<?php
	}
	
	if(isset($_GET['error'])&&$_GET['error']!="")
	{
		?>
		<tr>
			<span style="float:left; color:red;"><?php echo $_GET['error'];?></span>
		</tr>
		<?php
	}
	?>
      
      
      <tr>
        <td>
        <div id="container-5">
            <table width="100%" class="bottomBorder">
              <tr>
                <th width="5%" align="center">ID</th>
                <th width="10%" align="left">Product</th>
                <th width="10%" align="center">Packing</th>
                <th width="20%" align="center">Trade Price per Unit</th>
                <th width="5%" align="center">Qty</th>
                <th width="10%" align="center">Refund Qty</th>
                <th width="15%" align="center">Total</th>
                <th width="10%" align="center">Discount</th>
                <th width="15%" align="center">Net Total</th>
                </tr>
                <?php
			    $result4 = mysqli_query($con,"SELECT * FROM product_recitems where recinvoice_id='$recinvoiceid'");
				while($row4 = mysqli_fetch_array($result4))
				{
					$recitemsid = $row4["recitems_id"]; 
					$productid = $row4["product_id"];
			
					$raw_results5 = mysqli_query($con,"SELECT * FROM products WHERE product_id='$productid'");
					while($row5 = mysqli_fetch_assoc($raw_results5))
					{ 
						if(($row4['qty_received']-$row4['refund_qty'])==0)
						{
							?>
                          	<tr style="text-decoration:line-through;">
                            
                                <td align="left" valign="middle"><?php  echo $row5['product_id'];?></p></td>
                                
                                <td align="left" valign="middle"><?php echo $row5['product_name']. " - " . $row5['medicine_type'];?></p></td>
                                
                                <td align="center" valign="middle">
                                 <?php
                              
                                    
                                    echo $row4['packing_type'];
                              
                                ?>
                                </td>
                                
                                <td align="right" valign="middle">Rs. 
                                    <?php
                                    if ($row4['packing_type']=='Unit/Tablets') {  echo number_format($row5['unit_tradeprice'],2);} 
                                    
                                    if ($row4['packing_type']=='Leaf') {  echo number_format($row5['leaf_tradeprice'],2);} 
                                    
                                    if ($row4['packing_type']=='Box/Pack') {  echo number_format($row5['box_tradeprice'],2);}
                                    
                                    ?>
                                </td>
                                
                                <td align="center" valign="middle"><?php echo $row4['qty_received']-$row4['refund_qty'];?></td>
                                
                                <td align="center" valign="middle"><?php echo $row4['refund_qty']; ?></td>
                                 
                                <td align="right" valign="middle">
                                <?php 
                                    if ($row4['packing_type']=='Unit/Tablets') 
                                    { 
                                        $total=$row5['unit_tradeprice']*$row4['qty_received'];
                                    } 
                                    elseif ($row4['packing_type']=='Leaf') 
                                    {  
                                        $total=$row5['leaf_tradeprice']*$row4['qty_received'];
                                    } 
                                    elseif ($row4['packing_type']=='Box/Pack') 
                                    { 
                                        $total=$row5['box_tradeprice']*$row4['qty_received'];
                                    }
                                    else
                                    {
                                        $total = 0;
                                    }
                                    
                                     echo "Rs. ".number_format($total,2); 
                                ?>
                                </td>
                                
                                <td align="right" valign="middle"><?php echo $row4['discount']; ?></td>
                                
                                <td align="right" valign="middle"><?php echo "Rs. ".number_format($row4['net_total'],2); ?></td>
                            
                            </tr>
                            <?php
						}
						else
						{
							?>
                            <input name="productid[]" value="<?php echo $row5['product_id'];?>" type="hidden" size="5"/>
                        	<input name="recitemsid[]" value="<?php echo $row4['recitems_id'];?>" type="hidden" size="5"/>
                            <input name="unitqty[]" type="hidden" id="qty" size="5" value="<?php if(isset($row4['unitqty_recieved'])&&$row4['unitqty_recieved']!='0'){ echo $row4['unitqty_recieved']; } ?>" />
                            <input name="unitqtyold[]" type="hidden" id="qty" size="5" value="<?php if(isset($row4['unitqty_recieved'])&&$row4['unitqty_recieved']!='0'){ echo $row4['unitqty_recieved']; } ?>" />   
                            <tr>
						
                            <td align="left" valign="middle"><?php  echo $row5['product_id'];?></p></td>
                            
                            <td align="left" valign="middle"><?php echo $row5['product_name']. " - " . $row5['medicine_type'];?></p></td>
                            
                            <td align="center" valign="middle">
                           
                               <?php echo $row4['packing_type']; ?>
                              
                            </td>
                            
                            <td align="right" valign="middle">Rs. 
                                <?php
                                if ($row4['packing_type']=='Unit/Tablets') {  echo number_format($row5['unit_tradeprice'],2);} 
                                
                                if ($row4['packing_type']=='Leaf') {  echo number_format($row5['leaf_tradeprice'],2);} 
                                
                                if ($row4['packing_type']=='Box/Pack') {  echo number_format($row5['box_tradeprice'],2);}
                                
                                ?><input name="price[]" value="<?php if ($row4['packing_type']=='Unit/Tablets') {  echo $row5['unit_tradeprice'];} 
                                
                                if ($row4['packing_type']=='Leaf') {  echo $row5['leaf_tradeprice'];} 
                                
                                if ($row4['packing_type']=='Box/Pack') {  echo $row5['box_tradeprice'];}?>" type="hidden" size="5"/>
                            </td>
                            
                            <td align="center" valign="middle"><?php echo $row4['qty_received']-$row4['refund_qty'];?></td>
                            
                            <td align="center" valign="middle"></td>
                            
                            <td align="right" valign="middle">
                            <?php 
                                if ($row4['packing_type']=='Unit/Tablets') 
                                { 
                                    $total=$row5['unit_tradeprice']*$row4['qty_received'];
                                } 
                                elseif ($row4['packing_type']=='Leaf') 
                                {  
                                    $total=$row5['leaf_tradeprice']*$row4['qty_received'];
                                } 
                                elseif ($row4['packing_type']=='Box/Pack') 
                                { 
                                    $total=$row5['box_tradeprice']*$row4['qty_received'];
                                }
                                else
                                {
                                    $total = 0;
                                }
                                
                                 echo "Rs. ".number_format($total,2); 
                            ?>
                            </td>
                            
                            <td align="right" valign="middle"><?php echo $row4['discount']; ?></td>
                            
                            <td align="right" valign="middle"><?php echo "Rs. ".number_format($row4['net_total'],2); ?></td>
                            
                            </tr>
                        	<?php
							
						}
					}
			  	}
				?>
              </table>
            <br />

            <table width="100%" border="0" cellspacing="0" cellpadding="0" style="font-family:'Arial Black', Gadget, sans-serif; font-size:12px;">
              <?php 
		  		$raw_result5 = mysql_query("SELECT sum(refund_amount) FROM product_recitems where recinvoice_id='$recinvoiceid'") or die(mysql_error()); 
	 			while($row5 = mysql_fetch_array($raw_result5))
				{
					$invoiceamount=$row5['sum(refund_amount)'];
					?>
              		<tr>
                    <td width="75%" align="right"><h4>Total Refund Amount:</h4></td>
                    <td width="25%" align="right"><h4><?php echo "Rs. ".number_format($invoiceamount,2); ?>
                      <input name="invoiceamount" type="hidden" value="<?php echo $invoiceamount; ?>" />
                    </h4></td>
                    </tr>
                  	
					<?php 
				}
				?>
              </table>
        </div>
        </td>
      </tr>
     
    </table></td>
  </tr> 
  </form>
  </table>
  </div>

  <!-- InstanceEndEditable -->
</section>
</div>

<!--<p align="center" style="font-size:12px; font-family:Arial, Helvetica, sans-serif; margin-top:260px;"><strong><!--317 A-1, Nursery Stop, Township, Lahore. 
Ph: 042-35151666</strong><br />
For Appointment call at 042-35151666 (bring your Patient ID Card) </p>-->

   <div class="sidepop" style="float:right;">
    <div class="sidepopbutton stemp"><div style="color: rgb(0, 0, 0); text-align: right; font-size: 10px; margin-top: 4px; position: absolute; right: 180px;">© Software by Softusion Inc. 0322 6155 219</div>   
    </div>
</div>

<!--<div class="sidepop" style="float:right;">
    <div class="sidepopbutton stemp"><div style="color:#000; text-align:right; font-size:9px;">© Software designed by Softusion Inc. Contact us at 0322 6155 219</div>   
    </div>
</div>-->


          
</body>
<!-- InstanceEnd --></html>
