<?php
include('../config/config.php');
include('../classes/classSaleInvoice.php');
include('../classes/classProduct.php');
include('../classes/classPatient.php');
include('../classes/classReceiveInvoice.php');
include('../classes/classProductClosingReconcilation.php');

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



if(isset($_POST['search_by_date'])&&isset($_POST['product_id']))
{
	try
	{
		$product_id = $_POST['product_id'];
		
		$lastClosingQtyOb = new classProductClosingReconcilation;
		$lastClosingQtyOb->setProductID($product_id);
		$last_closing_array = $lastClosingQtyOb->retrieveLastClosingQtyOfProduct();
		
		if(isset($last_closing_array[0]['closing_date'])&&$last_closing_array[0]['closing_date']!='')
		{
			$from = date('Y-m-d',$last_closing_array[0]['closing_date']);
			$to =  date('Y-m-d',time());
			$lastClosingQty = $last_closing_array[0]['unit_phy_qtyinstock'];
		}
		
		$saleOb = new classSaleInvoice;
		$recOb = new classReceiveInvoice;
		
		$sale_array = $saleOb->singleProductSalesDetailReport($from,$to,$_SESSION['security']['location_id'],$product_id);	
		
		$rec_array = $recOb->singleProductsReceivesDetailReport($from,$to,$_SESSION['security']['location_id'],$product_id);
		
		$refund_array = $saleOb->refundDetails($from,$to,$product_id);
		
		
									
		
	}
	catch (MyException $e)
	{
		$error_message = $e->getUserMsg();
	}
	
	


}
else
{
	$to = '';
	$from = '';
	$product_id = 0;
	$lastClosingQty = 0;
	$sale_array = array();
$rec_array = array();
$refund_array = array();
	
}



############################ merge array and sort them by time ###################
$invoice_array = array_merge($sale_array,$rec_array,$refund_array);

foreach ($invoice_array as $key => $row) {
	if(isset($row['sale_date']))
	{
    	$orderByDate[$key]  = $row['sale_date'];
	}
	elseif(isset($row['received_date']))
	{
    	$orderByDate[$key]  = $row['received_date'];
	}
	else
	{
		$orderByDate[$key]  = $row['refund_time'];
	}
}
if(!empty($invoice_array))
{
	array_multisort($orderByDate,SORT_DESC,$invoice_array);
}

############################ retrieve products array ###################
try
{
	$retrieveProdOb = new classProduct;
	$retrieveProdOb->setOrganizationID($_SESSION['security']['org_id']);
	$product_array = $retrieveProdOb->retrieveActiveProducts();
	
}
catch (MyException $e)
{
	$error_message = $e->getUserMsg();
}	



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

?>
<!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 rel="stylesheet" href="../datepicker/jquery-ui.css">  
    <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" -->Product Wise Stock Ledger Report<!-- InstanceEndEditable --></h2>
            </header>

  <br />
  
<!-- InstanceBeginEditable name="main" -->
  <!-- page start-->
              <?php
			if(isset($error_message)&&$error_message!='')
			{
				?>
              <span class="message_red"><?php echo $error_message;?></span>
              <?php
			}
			?>

	<section class="wrapper">

	  <form action="" method="post">
        <table width="100%" border="0" cellpadding="1" cellspacing="0">
            <tr>
                <td width="1%" align="right"></td>
               
                <td width="20%">
                <select name="product_id" class="form-control">
                <option value="">Select Product</option>
                <?php
                for($p=0;$p<count($product_array);$p++)
                {
                  	 ?>
                    <option value="<?php echo $product_array[$p]['product_id'];?>" <?php if($product_id==$product_array[$p]['product_id']){echo 'selected';}?>><?php echo $product_array[$p]['product_name'];?></option>
                    <?php
                }
                ?>
                </select>
                </td>
                <td><input type="submit" class="btn btn-success btn-sm" name="search_by_date" value="Search"></td>
                
                 
                
            </tr>
            <tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
        </table>
        </form>
        
      <!-- page start-->
      <div class="row">
        <div class="col-sm-12">
          <section class="panel">
            <div class="panel-body">
              <div class="adv-table">
               
                <table  class="bottomBorder" width="100%">
                    
                    <thead>
                        <tr>
                            <th width="15%" align="left"> Date</th>
                            <th width="10%" align="left">Inv.No</th>
                            <th width="10%" align="left">Type</th>
                            <th width="10%" align="center">Supplier/Customer</th>
                            <th width="15%" align="right">Stock In</th>
                            <th width="15%" align="right">Stock Out</th>
                            <th width="15%" align="right">Balance</th>
                        </tr>
                    </thead>
                    
                    <tbody>
                    
                        <tr>
                            <td colspan="4" align="left"><strong>Last Closing Qty On <?php if($from!=''){echo $from;}?>:</strong></td>
                            <td align="left">&nbsp;</td>
                            <td align="left">&nbsp;</td>
                            <td align="right"><strong><?php echo $lastClosingQty;?></strong></td>
                        </tr>
                    
                    </tbody>
                  
                    <tbody>
                        <?php
                        $total_sales = 0;
                        $total_rec = 0;
                        $balance = $lastClosingQty;
                        
                        if(isset($invoice_array[0]['product_id']))
                        {
                            for($r=0;$r<count($invoice_array);$r++)
                            {
                                if(isset($invoice_array[$r]['received_date']))
                                {
                                    $date = $invoice_array[$r]['received_date'];
                                    $invoice_id = $invoice_array[$r]['recinvoice_id'];
                                    $unitqty_recieved = $invoice_array[$r]['unitqty_recieved'];
                                    $unitsaleqty = 0;
                                    $balance += $unitqty_recieved;
                                    
                                    $retrieveOb = new classProduct;
                                    $supplier_single_detail = $retrieveOb->retrieveSupplierBySupplierID($invoice_array[$r]['supplier_id']);
                                    $name = $supplier_single_detail[0]['company_name'];
									
									$type = 'Purchase';
									
								}
                                if(isset($invoice_array[$r]['sale_date']))
                                {
                                    $date = $invoice_array[$r]['sale_date'];
                                    $invoice_id = $invoice_array[$r]['saleinvoice_id'];
                                    $unitsaleqty = $invoice_array[$r]['unitsaleqty'];
                                    $unitqty_recieved = 0;
                                    $balance -= $unitsaleqty;
									
									
                                    
                                    if($invoice_array[$r]['patient_id']!=0)
                                    {
                                        $retrievePatientOb = new classPatient;
                                        $retrievePatientOb->setPatientAutoID($invoice_array[$r]['patient_id']);
                                        $patient_single_detail = $retrievePatientOb->retrievePatientByPatientID();
                                        $name = $patient_single_detail[0]['patient_fname'].' '.$patient_single_detail[0]['patient_lname'];
										
                                    }
                                    else
                                    {
                                        $name = 'Outdoor';
                                    }
                                    
									$type = 'Sale';
                                    
                                }
								if(isset($invoice_array[$r]['refund_time']))
                                {
									
                                    $date = $invoice_array[$r]['refund_time'];
									
									if($invoice_array[$r]['recinvoice_id']!=0)
									{
										$invoice_id = $invoice_array[$r]['recinvoice_id'];	
										$unitsaleqty = $invoice_array[$r]['qty'];
										$unitqty_recieved = 0;
										$balance -= $unitsaleqty;
										
										
										$retrieveOb = new classProduct;
                                    	$supplier_single_detail = $retrieveOb->retrieveSupplierBySupplierID($recOb->retrieveSupplierIDOfInvoice($invoice_id));
                                    	$name = 'Refund To '.$supplier_single_detail[0]['company_name'];
										
										$type = 'Suppliers Refund';
									}
									elseif($invoice_array[$r]['saleinvoice_id']!=0)
									{
										$invoice_id = $invoice_array[$r]['saleinvoice_id'];	
										$unitqty_recieved = $invoice_array[$r]['qty'];
										$unitsaleqty = 0;
										$balance += $unitqty_recieved;
										
										
										if($saleOb->retrievePatientIDOfInvoice($invoice_id)!=0)
										{
											$retrievePatientOb = new classPatient;
											$retrievePatientOb->setPatientAutoID($saleOb->retrievePatientIDOfInvoice($invoice_id));
											$patient_single_detail = $retrievePatientOb->retrievePatientByPatientID();
											$name = 'Refund By '.$patient_single_detail[0]['patient_fname'].' '.$patient_single_detail[0]['patient_lname'];
										}
										else
										{
											$name = 'Refund By Outdoor';
										}
										
										$type = 'Patients Refund';
									}
									
                                  
									
								}
                                
                                
                                ?>
                                <tr>
                                    <td align="left"><?php echo date('d-M-Y',$date);?></td>
                                    <td align="left"><?php echo $invoice_id;?></td>
                                    <td align="left"><?php echo $type;?></td>
                                    <td align="left"><?php echo $name;?></td>
                                    <td align="right"><?php echo $unitqty_recieved;?></td>
                                    <td align="right"><?php echo $unitsaleqty;?></td>
                                    <td align="right"><?php echo $balance;?></td>
                                </tr>
                                <?php
                                
                                $total_sales += $unitsaleqty;
                                $total_rec += $unitqty_recieved;
                                
                            }
                            
                            ?>
                            
                            <tr>
                                <td align="left"></td>
                                <td align="left"></td>
                                <td align="left">&nbsp;</td>
                                <td align="right"><strong>Total:</strong></td>
                                <td align="right"><strong><?php echo $total_rec?></strong></td>
                                <td align="right"><strong><?php echo $total_sales;?></strong></td>
                                <td align="right"><strong><?php echo $balance?></strong></td>
                            </tr>
                            <?php
                        }
                        else
                        {
                            ?>
                            <tr><table>
                                <tr><td>No Entry Found</td></tr>
                            </table></tr>
                                
                            <?php
                        }
                        ?>
                                
                      </tbody>
                  
                </table>
               
              </div>
            </div>
          </section>
        </div>
      </div>
      <!-- page end-->
    </section>
  <!-- page end-->
  
<!-- 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>-->


<style>


#block{
    display:block;
    margin:auto;
    position:absolute;
	float:right;
    }

#text {
    padding:0;
    margin:0;
    position:relative;
    font-size:9px;
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);
	left: 880px; top: 348px; 
}
</style> 
<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>
<script>
	$(function() {
		
		$("#datepicker").datepicker({
		showOn: "button",
		buttonImage: "../images/calendar.gif",
		buttonImageOnly: true,
		changeMonth: true,
		changeYear: true,
		dateFormat: "yy-mm-dd"
		});
		
		$("#datepicker1").datepicker({
		showOn: "button",
		buttonImage: "../images/calendar.gif",
		buttonImageOnly: true,
		changeMonth: true,
		changeYear: true,
		dateFormat: "yy-mm-dd"
		
		});
	
	});
</script>