<?php
 error_reporting(0); 

 $first_date=date('01/m/Y');
 $cur_date=date('d/m/Y');


 //For User Store
$sql_user_store="select hmis_storeid,StoreCode from www_users left join storetype on storetype.id=www_users.hmis_storeid where www_users.id='".$_SESSION['UserID']."'";
$result_user_store=DB_query($sql_user_store,$db);
$rs_user_store=DB_fetch_array($result_user_store);
$main_store=$rs_user_store[0];


$sql_other_store="select store_id,StoreCode from www_users_dtls left join storetype on storetype.id=www_users_dtls.store_id where user_id='".$_SESSION['UserID']."'";
$result_other_store=DB_query($sql_other_store,$db);
while($rs_other_store=DB_fetch_array($result_other_store))
{
  $store[]=$rs_other_store['store_id'];
}
if(!empty($store))
{
  $get_store_id=implode(",",$store);
}


if($main_store!=0 && $get_store_id!='')
{
  $all_store=$main_store.",".$get_store_id;
}
else
{
  $all_store=$main_store;
}


?> 
<script type="text/javascript"> 
function checkval(){
  var idsite = document.getElementById("site").value;
  var idstore = document.getElementById("store1").value;
  var fromdate = document.getElementById("from_date").value;
  var todate = document.getElementById("to_date").value;
  var maincat = document.getElementById("maincat").value;
  if(idsite=='0'){
    alert("Select Branch First.");
    return false;
  }
  
  else if(fromdate=='' && todate=='')
  {
    alert("Select From - To date.");
    return false;
  }
  else if(maincat=='0' && idstore=='0')
  {
  alert("Select Main category First.");
    return false;
  }
  return true;
}

function showItems(str)
{
  $.post("Get_itemcode.php",{"partName":str},function(data){
  document.getElementById("itemid").innerHTML=data;
  });
}
function showsitename160(str)
{

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
  var data=xmlhttp.responseText.split("__");  
  document.getElementById("storedata7").innerHTML=data[0];
    }
  }
  xmlhttp.open("GET","get_sitenamedata3.php?site="+str,true);
  xmlhttp.send();

//xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);  
}


function showsubcat(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
  var data=xmlhttp.responseText.split("__");  
  document.getElementById("subcatdata").innerHTML=data[0];
  document.getElementById("itemid").innerHTML=data[1];
    }
  }
  xmlhttp.open("GET","get_sitenamedatasubcat.php?site="+str,true);
  xmlhttp.send();
}

function showdata(str)
{
 if(str=="")
  {
  document.getElementById("itemid").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("itemid").innerHTML=xmlhttp.responseText;
    }
  }
  var cat=document.getElementById("maincat").value;
xmlhttp.open("GET","Get_itemcode1.php?partName="+str+"&main="+cat,true);
xmlhttp.send();
}
</script>

<link rel="stylesheet" href="css/new_mxerp.css">

<div class="body_contain">
<div class="tab_div">
<h1>Stock Valuation Report</h1>
<form method="post" action="">
<table width="100%" border="0" cellspacing="0" cellpadding="3">
  <tr class="row1">
    <td width="13%" align="right">Branch <span style="color:#FF0000">*</span></td>
    <td width="20%"><?php      
  $ss1="Select loccode, locationname from locations  where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode in('".$_SESSION['AssignedBranch']."')";
       $site_sql1=DB_query($ss1,$db);   
  ?>
      <select name="site" id="site" onchange="showsitename160(this.value)">
                <option value="0">Select Branch</option>
                <?php 
        
        while($site_row = DB_fetch_array($site_sql1))
        {
          $p='';
          if($site_row['loccode'] == $_POST['site'])  
          $p="selected";
        ?>
                <option value="<?php echo $site_row['loccode']; ?>" <?php echo $p;?>><?php echo $site_row['locationname']; ?></option>
                <?php } ?>
          </select>   </td>
        <td width="13%" align="right">Store <span style="color:#FF0000">*</span></td>
        <td width="20%">
      <div id="storedata7">
              <select name="store1" id="store1">
        <option value='0'>All</option>
                <?php 
        $store_sql = "SELECT id, StoreName,storecode FROM storetype where Store_Site = '".$_REQUEST['site']."'";
        $store_result = DB_query($store_sql,$db);
        while($store_row = DB_fetch_array($store_result))
        {
          $p='';
          if($store_row['id'] == $_REQUEST['store1'])
            $p="selected";
        ?>
                <option value="<?php echo $store_row['id'] ?>"<?php echo $p; ?>><?php echo $store_row['StoreName']?></option>
                <?php } ?>
                </select>
            </div>    </td>
    <td width="13%" align="right">Item Name</td>
    <td><input type="text" name="itemName" value="" onkeyup="showItems(this.value)" /></td>
  </tr>
  <tr class="row1">
  <td align="right">Main Group</td>
  <td><select name="maincat" id="maincat" onchange="showsubcat(this.value)">
  <option value="0">Select</option>
                <?php 
        $store_sql = "SELECT * FROM stockmaincategory  ";
        $store_result = DB_query($store_sql,$db);
        while($store_row = DB_fetch_array($store_result))
        {
          $p='';
          if($store_row['id'] == $_REQUEST['maincat'])
            $p="selected";
        ?>
                <option value="<?php echo $store_row['id'] ?>"<?php echo $p; ?>><?php echo $store_row['stockmaincategoryname']?></option>
                <?php } ?>
                </select></td>
  <td align="right">Sub Group</td>
  <td><div id="subcatdata">
  <?php 
   $store_sql = "SELECT * FROM stockcategory  where stockmaincategory = '".$_POST['maincat']."'";
   ?>
  <select name="subcat"  id="subcat" onchange="showdata(this.value)">
  <option value="0">Select</option>
      <?php
      $store_result = DB_query($store_sql,$db);
      while($store_row = DB_fetch_array($store_result))
      {
        ;
        $p='';
        if($store_row['id'] == $_REQUEST['subcat'])
        $p="selected";
      ?>
      
  <option value="<?php echo $store_row['id'] ; ?>" <?php echo $p ; ?>><?php echo $store_row['categorydescription']; ?></option>
       <?php }?>
                </select></div> </td>
  <td rowspan="2" valign="top">&nbsp;</td>
  <td rowspan="2" valign="top">
  <div id="itemid">
                <div style="overflow:auto; height:100px; border:1px solid #ccc; background:#fff; padding:2px 3px;">
                  <?php 
          $item_sql=DB_query("select id,StockID,item_name from item_master",$db);
          $c3=0;
          while($row3=DB_fetch_array($item_sql))
          { 
            $c='';
            if($_REQUEST['item'][$c3]==$row3['id'])
              {$c="checked";}
          ?>
                  <input type="checkbox" name="item[<?php echo $c3;?>]" id="item_<?php echo $c3;?>" value="<?php echo $row3['id'];?>" <?php echo $c;?>/>
                  <?php echo $row3['StockID']." - ".$row3['item_name'];?><br />
                  <?php 
    
          $c3++;
          }
          if($_REQUEST['view'] && $_REQUEST['item']){
            $itemString[]=$_REQUEST['item'];
            $a=implode(",", $_REQUEST['item']); 
          }  
    
        ?>
                </div>
              </div>  </td>
  </tr>
  
  <tr class="row1">
        <td align="right">From Date</td>
        <td><input type="text" name="from_date" id="fromdate" value="<?php if($_REQUEST['from_date']!='') { echo $_REQUEST['from_date']; } else { echo $first_date; } ?>"  onchange="javascript:checkdate(this.value)"  class="datepicker"></td>
        <td align="right">To Date</td>
        <td><input type="text" name="to_date" id="todate" value="<?php if($_REQUEST['to_date']!='') { echo $_REQUEST['to_date']; } else { echo $cur_date;  };?>"  onchange="javascript:checkdate(this.value)"  class="datepicker">
          <input type="hidden" value="<?php echo ConvertSQLDate($_SESSION['financialYrStart']);?>" id='from'>
        <input type="hidden" value="<?php echo ConvertSQLDate($_SESSION['financialYrEnd']);?>" id='to'>
        </td>
  </tr>
  <tr class="row1">    
    <td colspan="6" style="text-align:center;"><input type="submit" name="view" value="View" onclick="return checkval()" class="search"></td>
  </tr>
</table>

     
</form>
<?php  if($_REQUEST['view']!=''){?>
<p align="right"><a href="stock_valuation_print.php?site=<?php echo $_REQUEST['site'];?>&store_code=<?php echo $_REQUEST['store1']?>&fromdate=<?php echo $_REQUEST['from_date']?>&todate=<?php echo $_REQUEST['to_date']?>" target="_blank"><input type="button" name="print" value="Print" class="search" ></a> <a href="stock_valuation_export.php?site=<?php echo $_REQUEST['site'];?>&store_code=<?php echo $_REQUEST['store1']?>&fromdate=<?php echo $_REQUEST['from_date']?>&todate=<?php echo $_REQUEST['to_date']?>" target="_blank"><input type="button" name="export" value="Export" class="search" ></a></p>

<?php } ?>
<?php
  if(isset($_POST['view']))
  {
   $filter=array();
   $filter2=array();

  $branch=$s->getField('locations','loccode',$_REQUEST['site'],'locationname');
  
  if($_REQUEST['site']!='0')
  {
   $filter[]="site='".$_REQUEST['site']."'";
  }
  $fromdate=$_REQUEST['from_date'];
  $todate=$_REQUEST['to_date'];
  
  $fromdate_brk=explode('/',$fromdate);
  $from=$fromdate_brk[2]."-".$fromdate_brk[1]."-".$fromdate_brk[0];
  $todate_brk=explode('/',$todate);
  $to=$todate_brk[2]."-".$todate_brk[1]."-".$todate_brk[0];
   
   if($_REQUEST['from_date']!='' && $_REQUEST['to_date']!='')
  $filter[]="DATE(trasaction) BETWEEN '".$from."' and '".$to."'";
   else
  $filter[]="DATE(trasaction) BETWEEN '".date('Y-m-d')."' and '".date('Y-m-d')."'";  
  
 if($_REQUEST['store1']!='0'){
  $storedata="store  ".$s->getField('storetype','id',$_REQUEST['store1'],'StoreName');
  $filter[]="store='".$_REQUEST['store1']."'";
 }
  else
  $storedata="ALL Store";
  if($_REQUEST['maincat']!='0' && $_REQUEST['store1']!=='0')
  {
  $sub=$s->getField('stockcategory','id',$_REQUEST['subcat'],'categorydescription');
  $cat=$s->getField('stockmaincategory','id',$_REQUEST['maincat'],'stockmaincategoryname');
  }
  if($_REQUEST['maincat']!='0')
  {
  $message="Showing Records of <u><span class='fntBig'>".$storedata."</span></u> of Branch -- <u><span class='fntBig'>".$branch."</span></u> Category -- <u><span class='fntBig'>".$cat."</span></u> -- and SubCategory -- <u><span class='fntBig'>".$sub."</span></u> and From <u><span class='fntBig'>".$_REQUEST['from_date']."</span></u> to <u><span class='fntBig'>".$_REQUEST['to_date']."</span></u>";
  }
  elseif($_REQUEST['from_date']!="" && $_REQUEST['to_date']!="")
  {
   $message="Showing Records of <u><span class='fntBig'>".$storedata."</span></u> of Branch -- <u><span class='fntBig'>".$branch."</span></u> From <u><span class='fntBig'>".$_REQUEST['from_date']."</span></u> to <u><span class='fntBig'>".$_REQUEST['to_date']."</span></u>";
  }
  elseif($_REQUEST['from_date']=="" && $_REQUEST['to_date']=="")
  {
   $message="Showing Records of <u><span class='fntBig'>".$storedata."</span></u> of Branch -- <u><span class='fntBig'>".$branch."</span></u> From <u><span class='fntBig'>".ConvertSQLDate($_SESSION['financialYrStart'])."</span></u> to <u><span class='fntBig'>".ConvertSQLDate($_SESSION['financialYrEnd'])."</span></u>";
  }
 
   $_SESSION['mess1']=$message;
  
 //for display data on print page starts here
  $get_branch=$_REQUEST['site'];
  $get_branch_name=$s->GetFieldValue('locations','loccode="'.$_REQUEST['site'].'"','locationname');

  $_SESSION['mess_branch']="Branch:".$get_branch_name;
  $_SESSION['get_date']="From  ".$_REQUEST['from_date']." to ".$_REQUEST['to_date']."";
  $_SESSION['get_item1']=$_REQUEST['item'];

  $_SESSION['from_date']=$from;
  $_SESSION['to_date']=$to;
  $_SESSION['store1']=$_REQUEST['store1'];
  $_SESSION['main_cat']=$_REQUEST['maincat'];
  $_SESSION['sub_cat']=$_REQUEST['subcat'];
 // echo $_SESSION['main_cat'];
 // echo $_SESSION['sub_cat'];
  
 //for display data on print page ends here
  
   
   if($_REQUEST['item']!=''){
      $item_string=implode("','",$_REQUEST['item']);
      $filter2[]="id in('".$item_string."')";
    }
   
   if($filter!='')
  {
    $filter=implode(" and ",$filter);
  }

   
   if($filter2!='')
  {
    $filter2=implode(" and ",$filter2);
  }
   
   $item2=$_REQUEST['item'];
   $_SESSION['get_item2']=$item2;

  if($item2!='')
    {
    $item_string1=implode(",",$item2);
    $item1=explode(",",$item_string1);
    $catid='';
    for($mm1=0;$mm1<count($item1);$mm1++)
      {
       $catid[$mm1]=$s->GetFieldValue('item_master','id="'.$item1[$mm1].'"','SubCategoryID');
       
    }
    $catid1= array_unique($catid);
    $item_catid=implode("','",$catid1);
   
     $main_cat=DB_query("SELECT A.id,A.categorydescription,A.stockmaincategory,B.stockmaincategoryname 
    FROM stockcategory A RIGHT JOIN stockmaincategory B
    ON A.stockmaincategory=B.id WHERE B.CompanyId='".$_SESSION['ACGCompanyId']."' 
       AND A.id IN ('".$item_catid."') ORDER BY B.stockmaincategoryname,A.categorydescription",$db);   
      }
               else if($_REQUEST['maincat']!=0 && $_REQUEST['subcat']!=0)
                {
                  $main_cat=DB_query("SELECT A.id,A.categorydescription,A.stockmaincategory
                  ,B.stockmaincategoryname  FROM stockcategory A RIGHT JOIN stockmaincategory B
                ON A.stockmaincategory=B.id WHERE B.CompanyId='".$_SESSION['ACGCompanyId']."' 
                 AND B.id='".$_REQUEST['maincat']."' AND A.id='".$_REQUEST['subcat']."'
                  ORDER BY B.stockmaincategoryname,A.categorydescription
                ",$db);
                 }
                 else if($_REQUEST['maincat']!=0 && $_REQUEST['subcat']==0)
                  {
                   $main_cat=DB_query("SELECT A.id,A.categorydescription,A.stockmaincategory
                  ,B.stockmaincategoryname  FROM stockcategory A RIGHT JOIN stockmaincategory B
                ON A.stockmaincategory=B.id WHERE B.CompanyId='".$_SESSION['ACGCompanyId']."' 
                 AND B.id='".$_REQUEST['maincat']."' ORDER BY B.stockmaincategoryname,A.categorydescription
                ",$db);
                 }
                 else if($_REQUEST['maincat']==0 && $_REQUEST['subcat']!=0)
                  {                 
                 $main_cat=DB_query("SELECT A.id,A.categorydescription,A.stockmaincategory
                  ,B.stockmaincategoryname   FROM stockcategory A RIGHT JOIN stockmaincategory B
                ON A.stockmaincategory=B.id WHERE B.CompanyId='".$_SESSION['ACGCompanyId']."' 
                 AND A.id='".$_REQUEST['subcat']."' ORDER BY B.stockmaincategoryname,A.categorydescription
                ",$db);
                 }
                 else
                  {
                   $main_cat=DB_query("SELECT A.id,A.categorydescription,A.stockmaincategory
                    ,B.stockmaincategoryname    FROM stockcategory A RIGHT JOIN stockmaincategory B
                ON A.stockmaincategory=B.id WHERE B.CompanyId='".$_SESSION['ACGCompanyId']."' 
                 ORDER BY B.stockmaincategoryname,A.categorydescription
                ",$db);
                }

 while($main_cat_row=DB_fetch_array($main_cat))
 {
  $main_cat_array[]=$main_cat_row['id'];
}
//print_r($main_cat_array);

//$_SESSION['get_main_category']=$main_cat;
 ?> 
  <table cellpadding="3" cellspacing="0" border="0" width="100%" class="thborder">
  <tr>
    <th width="10%" rowspan="2">Item Code</th>
    <th rowspan="2">Item Name</th>
    <th rowspan="2">HSN Code</th>
    <th rowspan="2">GST(%)</th>
    <!--<th width="7%" rowspan="2">Type</th>-->
    <th width="10%" rowspan="2">Unit</th>
    <th colspan="3" style="text-align:center;">Opening Balance</th>
    <th colspan="3" style="text-align:center;">Received</th>
    <th colspan="3" style="text-align:center;">Issued</th>   
    <th colspan="3" style="text-align:center;">Closing Balance</th>
  </tr> 
  <tr>
    <th style="text-align:center;" width="5%">Qty.</th>
    <th style="text-align:center;" width="5%">Rate</th>
    <th style="text-align:center;" width="5%">Value</th>
    <th style="text-align:center;" width="5%">Qty.</th>
    <th style="text-align:center;" width="5%">Rate</th>
    <th style="text-align:center;" width="5%">Value</th>
    <th style="text-align:center;" width="5%">Qty.</th>
    <th style="text-align:center;" width="5%">Rate</th>
    <th style="text-align:center;" width="5%">Value</th>
    <th style="text-align:center;" width="5%">Qty</th>
    <th style="text-align:center;" width="5%">Rate</th>
    <th style="text-align:center;" width="5%">Value</th>
  </tr>  
   
    <?php
    $final_closing=array();
     // $sql="select sum(inwardqty) as receiveqty ,sum(inwared_value) as amount
       //   from stock_inward where type!='OPN'";
     // $query=DB_query($sql,$db);
     
    $_SESSION['main_cat_array']=$main_cat_array;

    $_SESSION['filter']=$filter;
    $_SESSION['filter2']=$filter2;
      
     for($rd=0;$rd<count($main_cat_array);$rd++)
     {
if($filter2!='')
    $sql1="select * from item_master where SubCategoryID='".$main_cat_array[$rd]."' and $filter2 ORDER BY id ASC";
    else
    $sql1="select * from item_master where SubCategoryID='".$main_cat_array[$rd]."' ORDER BY id ASC";   
   $sql2=$sql1;
  $sql=DB_query($sql1,$db);
  $sql2=DB_query($sql2,$db);
   $num_row2=DB_num_rows($sql2);   
    ?>
  <tr bgcolor="#e4e4e4" style="color:#00695f;">
    <td colspan="17" align="left" style="text-align:left;"><b><?php echo $s->GetFieldValue('stockmaincategory','id="'.$s->GetFieldValue('stockcategory','id="'.$main_cat_array[$rd].'"','stockmaincategory').'"','stockmaincategoryname');?>&nbsp;<img src="images/orange-right-arrow-button.png" height="20" width="20" style="vertical-align:middle;" />&nbsp;<?php echo $s->GetFieldValue('stockcategory','id="'.$main_cat_array[$rd].'"','categorydescription')?></b></td>
  </tr>
    
     <?php  
     $print_array[]=$_REQUEST['site'];
     $print_array[]=$_REQUEST['store1'];
     $print_array[]=$from;
          
         // echo $from;
     $_SESSION['print_array']=$print_array;
  
     $num=DB_num_rows($sql);

    while($row1=DB_fetch_array($sql))
    {
     // echo $row1['id'];
     //echo "select * from stock_inward where mst_itemid='".$row1['id']."' and type='OP' and $filter";

    //-------------------------------------    Privious Opening     ---------------------------------//
      $ope='';$opeamt='';$operate='';
      $opamt='';$opvalue='';$issueqty='';$issuevalue='';

     $op_data=DB_query("select sum(inwardqty_primary) as inwardqty_primary,sum(inwared_value) as inwared_value from stock_valuation_tbl where mst_itemid='".$row1['id']."' and type='OP' 
      and site='".$_REQUEST['site']."'  and store='".$_REQUEST['store1']."'  and DATE(trasaction) <= '".$to."'",$db);


     $privious_opening=DB_fetch_array($op_data);
     if(DB_num_rows($op_data)>0)
     {
      $opamt[]=$privious_opening['inwardqty_primary'];
      $opvalue[]=$privious_opening['inwared_value'];
    }
    else
    {
     $op_data1=DB_query("select sum(inwardqty_primary) as inwardqty_primary,sum(inwared_value) as inwared_value from stock_valuation_tbl where mst_itemid='".$row1['id']."' and type='OP' 
      and site='".$_REQUEST['site']."'  and store='".$_REQUEST['store1']."'  and DATE(trasaction) between '".$to."' and '".$to."'",$db);
     $privious_opening1=DB_fetch_array($op_data1);
       if(DB_num_rows($op_data1)>0)
       {
        $opamt[]=$privious_opening1['inwardqty_primary'];
        $opvalue[]=$privious_opening1['inwared_value'];
      }

    }

   /*    $priv_rec=DB_query("select sum(inwardqty_primary) as qty,sum(inwared_value) as amt from stock_valuation_tbl 
        where mst_itemid='".$row1['id']."' and type!='OP' and site='".$_REQUEST['site']."'  and store='".$_REQUEST['store1']."'  
        and  DATE(trasaction) < '".$from."'",$db);
   $privious_receive=DB_fetch_array($priv_rec);
   if(DB_num_rows($priv_rec)>0)
   {
    $opamt[]=$privious_receive['qty'];
    $opvalue[]=$privious_receive['amt'];
   } */
   
   /* ------------------- Previous Receive Starts Here----------------------------------- */
   $in_rate_prev=0;
      $priv_rec=DB_query("select * from stock_valuation_tbl where mst_itemid='".$row1['id']."' and type!='OP' and site='".$_REQUEST['site']."'  and store='".$_REQUEST['store1']."' and inwardqty_primary!='0.00'  and  DATE(trasaction) < '".$from."'",$db);
     while($privious_receive=DB_fetch_array($priv_rec))
     {
        //$opamt[]=$privious_receive['qty'];
        //$opvalue[]=$privious_receive['amt'];
       


      $sql_po_rate_prev="select addmrnqty.mrprate as rate from addmrnqty inner join addmrn on addmrn.id=addmrnqty.issue_id where mst_itemid='".$row1['id']."' and site='".$_REQUEST['site']."' and  MRNDate <= date_format('".$privious_receive['trasaction']."','%Y-%m-%d')  and addmrnqty.batch_no='".$privious_receive['batch_no']."' order by addmrn.id desc limit 1";
         $result_po_rate_prev=DB_query($sql_po_rate_prev,$db);
         $rs_po_rate_prev=DB_fetch_array($result_po_rate_prev);
          if($rs_po_rate_prev['rate']=='')
         {
           $sql_po_rate_op_prev="select rate from opening_stockitemwise where itemcode='".$row1['id']."' and site='".$_REQUEST['site']."' and reveive_date < date_format('".$privious_receive['trasaction']."','%Y-%m-%d') order by id desc limit 1";
           $result_po_rate_op_prev=DB_query($sql_po_rate_op_prev,$db);
           $rs_po_rate_op_prev=DB_fetch_array($result_po_rate_op_prev);
         }
             if($rs_po_rate_prev['rate']!='')
             {
              
               $in_rate_prev=$rs_po_rate_prev['rate'];
             }
             else
             {
             
               $in_rate_prev=$rs_po_rate_op_prev['rate'];
             }
            // $recamt+=$receivingdata['inwardqty_primary']*$in_rate;
              
             $opamt[]=$privious_receive['inwardqty_primary']; 
             $opvalue[]=$privious_receive['inwardqty_primary']*$in_rate_prev;
     }
  /* ------------------- Previous Receive Ends Here----------------------------------- */



    /* ------------------- Previous Issued Starts Here----------------------------------- */
  /*   $priv_iss=DB_query("select sum(outwardqty_primary) as qty,sum(outward_value) as amt  from stock_valuation_tbl 
             where mst_itemid='".$row1['id']."' and site='".$_REQUEST['site']."'  and store='".$_REQUEST['store1']."' 
              and  DATE(trasaction) < '".$from."'",$db);
    $privious_issue=DB_fetch_array($priv_iss);
    if(DB_num_rows($priv_iss)>0)
     { 
    $issueqty[]=$privious_issue['qty'];
    $issuevalue[]=$privious_issue['amt'];
     } */
  
 $out_rate_prev=0;
   $priv_iss=DB_query("select * from stock_valuation_tbl where mst_itemid='".$row1['id']."' and site='".$_REQUEST['site']."'  and store='".$_REQUEST['store1']."' and  DATE(trasaction) < '".$from."' and outwardqty_primary!='0.00' ",$db);
    while($privious_issue=DB_fetch_array($priv_iss))
    {
      if(DB_num_rows($priv_iss)>0)
       { 
             $sql_po_rate_out_prev="select addmrnqty.mrprate as rate from addmrnqty inner join addmrn on addmrn.id=addmrnqty.issue_id where mst_itemid='".$row1['id']."' and site='".$_REQUEST['site']."' and  MRNDate <= date_format('".$privious_issue['trasaction']."','%Y-%m-%d')  and addmrnqty.batch_no='".$privious_issue['batch_no']."' order by addmrn.id desc limit 1";
           $result_po_rate_out_prev=DB_query($sql_po_rate_out_prev,$db);
           $rs_po_rate_out_prev=DB_fetch_array($result_po_rate_out_prev);

           if($rs_po_rate_out_prev['rate']=='')
           {
             $sql_po_rate_out_op_prev="select rate from opening_stockitemwise where itemcode='".$row1['id']."' and site='".$_REQUEST['site']."' and reveive_date < date_format('".$privious_issue['trasaction']."','%Y-%m-%d') order by id desc limit 1";
             $result_po_rate_out_op_prev=DB_query($sql_po_rate_out_op_prev,$db);
             $rs_po_rate_out_op_prev=DB_fetch_array($result_po_rate_out_op_prev);
           }
               if($rs_po_rate_out_prev['rate']!='')
               {
                
                 $out_rate_prev=$rs_po_rate_out_prev['rate'];
               }
               else
               {
          
                 $out_rate_prev=$rs_po_rate_out_op_prev['rate'];
               }
           //$iseamt+=$issuingdata['outwardqty_primary']*$out_rate;   
            $issueqty[]=$privious_issue['outwardqty_primary'];
            $issuevalue[]=$privious_issue['outwardqty_primary']*$out_rate_prev;
       }
   }

    if(!empty($opamt))
    $ope1=array_sum($opamt); else $ope1=0;
    if(!empty($opvalue))  
    $opeamt1=array_sum($opvalue);  
    if($opeamt1==''){$opeamt1=0;}
    if(!empty($issueqty))
    $issue1=array_sum($issueqty); else $issue1=0;
    if(!empty($issuevalue))
    $issue_val1=array_sum($issuevalue); else $issue_val1=0;
 
     //$ope=$opengingdata['inwardqty'];
     //if($ope==''){$ope=0;}
     //$opeamt=$opengingdata['inwared_value'];
     $ope=$ope1-$issue1;
     $opeamt=$opeamt1-$issue_val1;
    
     if($ope!=0)
     $operate=round($opeamt/$ope,2);
     if($operate==''){$operate=0;}

      /* ------------------- Previous Issued Ends Here----------------------------------- */

    //*************************************************************************************************//

    /* $opengingdata=DB_fetch_array(DB_query("select * from stock_inward where mst_itemid='".$row1['id']."' and type='OP' and $filter",$db));
     $ope='';$opeamt='';$operate='';
     $ope=$opengingdata['inwardqty'];
     if($ope==''){$ope=0;}
     $opeamt=$opengingdata['inwared_value'];
     if($opeamt==''){$opeamt=0;}
     if($ope!=0)
     $operate=round($opeamt/$ope,2);
     if($operate==''){$operate=0;}*/
    //echo "select sum(inwardqty) as qty,sum(inwared_value) as amt 
    //               from stock_inward where mst_itemid='".$row1['id']."'  and type!='OP'
    //                and  inward_rate!='' and $filter";
    // echo ""
     // echo "select sum(inwardqty_primary) as qty,sum(inwared_value) as amt from stock_valuation_tbl 
     // where mst_itemid='".$row1['id']."'        and type!='OP'      and  inward_rate!='' and $filter";    
      
     /* $receivingdata=DB_fetch_array(DB_query("select sum(inwardqty_primary) as qty,sum(inwared_value) as amt from stock_valuation_tbl 
      where mst_itemid='".$row1['id']."'        and type!='OP'      and $filter",$db));  */
$rec='';$recamt='';$recrate='';$in_rate='';
   //echo "select * from stock_valuation_tbl where mst_itemid='".$row1['id']."'  and type!='OP'      and $filter";

    $receivingdata1=DB_query("select * from stock_valuation_tbl where mst_itemid='".$row1['id']."'  and type!='OP' and inwardqty_primary!='0.00' and $filter",$db);
    while($receivingdata=DB_fetch_array($receivingdata1))
    {
         $rec+=$receivingdata['inwardqty_primary'];

         /* echo $sql_mrn_batch="select issue_id from addmrnqty inner join addmrn where mst_itemid='".$receivingdata['mst_itemid']."' and batch_no='".$receivingdata['batch_no']."' and MRNDate<=date_format('".$receivingdata['trasaction']."','%Y-%m-%d') "; */
        
         $sql_po_rate="select addmrnqty.mrprate as rate from addmrnqty inner join addmrn on addmrn.id=addmrnqty.issue_id where mst_itemid='".$row1['id']."' and site='".$_REQUEST['site']."' and  MRNDate <= date_format('".$receivingdata['trasaction']."','%Y-%m-%d')  and addmrnqty.batch_no='".$receivingdata['batch_no']."' order by addmrn.id desc limit 1";
         $result_po_rate=DB_query($sql_po_rate,$db);
         $rs_po_rate=DB_fetch_array($result_po_rate);
          if($rs_po_rate['rate']=='')
         {
           $sql_po_rate_op="select rate from opening_stockitemwise where itemcode='".$row1['id']."' and site='".$_REQUEST['site']."' and reveive_date <= date_format('".$receivingdata['trasaction']."','%Y-%m-%d') order by id desc limit 1";
           $result_po_rate_op=DB_query($sql_po_rate_op,$db);
           $rs_po_rate_op=DB_fetch_array($result_po_rate_op);
         }
             if($rs_po_rate['rate']!='')
             {
              
               $in_rate=$rs_po_rate['rate'];
             }
             else
             {
             
               $in_rate=$rs_po_rate_op['rate'];
             }
            //echo $in_rate."###".$$receivingdata['inwardqty_primary'];
         $recamt+=$receivingdata['inwardqty_primary']*$in_rate;
    }

     
     //$rec=$receivingdata['qty'];
     if($rec==''){$rec=0;}
     //$recamt=$receivingdata['amt'];
     if($recamt==''){$recamt=0;}
      if($rec!=0)
     $recrate=round($recamt/$rec,2);

     if($recrate==''){$recrate=0;}
//echo "select sum(outwardqty_primary) as qty,sum(outward_value) as amt 
                  // from stock_valuation_tbl where mst_itemid='".$row1['id']."' and inward_rate!=''
                  //  and $filter";
    /*  $issuingdata=DB_fetch_array(DB_query("select  sum(outwardqty_primary) as qty,sum(outward_value) as amt 
                   from stock_valuation_tbl where mst_itemid='".$row1['id']."'    and $filter",$db)); */

      $ise='';$iseamt='';$iserate='';$out_rate='';
     $issuingdata1=DB_query("select * from stock_valuation_tbl where mst_itemid='".$row1['id']."'  and outwardqty_primary!='0.00'  and $filter",$db);
     while($issuingdata=DB_fetch_array($issuingdata1))
     {

       $ise+=$issuingdata['outwardqty_primary'];
      

         $sql_po_rate_out="select addmrnqty.mrprate as rate from addmrnqty inner join addmrn on addmrn.id=addmrnqty.issue_id where mst_itemid='".$row1['id']."' and site='".$_REQUEST['site']."' and  MRNDate <= date_format('".$issuingdata['trasaction']."','%Y-%m-%d')  and addmrnqty.batch_no='".$issuingdata['batch_no']."' order by addmrn.id desc limit 1";
         $result_po_rate_out=DB_query($sql_po_rate_out,$db);
         $rs_po_rate_out=DB_fetch_array($result_po_rate_out);

         if($rs_po_rate_out['rate']=='')
         {
           $sql_po_rate_out_op="select rate from opening_stockitemwise where itemcode='".$row1['id']."' and site='".$_REQUEST['site']."' and reveive_date <= date_format('".$issuingdata['trasaction']."','%Y-%m-%d') order by id desc limit 1";
           $result_po_rate_out_op=DB_query($sql_po_rate_out_op,$db);
           $rs_po_rate_out_op=DB_fetch_array($result_po_rate_out_op);
         }
             if($rs_po_rate_out['rate']!='')
             {
              
               $out_rate=$rs_po_rate_out['rate'];
             }
             else
             {
        
               $out_rate=$rs_po_rate_out_op['rate'];
             }

         //echo $out_rate."###".$issuingdata['outwardqty_primary']."<hr/>";
         $iseamt+=$issuingdata['outwardqty_primary']*$out_rate;

     }
    //echo $recamt."#####".$iseamt;
    
     //$ise=$issuingdata['qty'];
     if($ise==''){$ise=0;}
     //$iseamt=$issuingdata['amt'];
     if($iseamt==''){$iseamt=0;}
      if($ise!=0)
     $iserate=round($iseamt/$ise,2);
 
     if($iserate==''){$iserate=0;}
  $closingqty='';$closingamt='';$closingrate='';
  $closingqty=($ope+$rec)-$ise;
  if($closingqty==''){$closingqty=0;}
  $closingamt=($opeamt+$recamt)-$iseamt;
  if($closingamt==''){$closingamt=0;}
   if($closingqty!=0)
  $closingrate=round($closingamt/$closingqty,2);
  if($closingrate==''){$closingrate=0;}
   ?>  
  <tr>
    <td><?php echo $itemcode=$s->getField('item_master','id',$row1['id'],'StockID'); ?></td>
    <?php /*?><!--<td width="10%" rowspan="2"><?php echo $s->getField('item_master','id',$row1['id'],'item_name');?></td>--><?php */?>  
    <td><?php echo $s->getField('item_master','id',$row1['id'],'item_name');?></td>
    <td><?php echo $s->GetFieldValue('item_master',"id='".$row1['id']."'",'hsn_code'); ?></td>
    <td><?php echo $s->GetFieldValue('item_master',"id='".$row1['id']."'",'gst_percentage'); ?></td>
    <!--<td>Primary</td>-->
    <td><?php $unit_id=$s->getField('item_master','id',$row1['id'],'mst_unitid'); echo $s->getField('unitsofmeasure','unitid',$unit_id,'unitname');?></td>
    <td style="text-align:right;"><?php echo number_format((float)$ope,2); ?></td>
    <td style="text-align:right;"><?php echo number_format((float)$operate,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$opeamt,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$rec,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$recrate,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$recamt,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$ise,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$iserate,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$iseamt,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$closingqty,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$closingrate,2); ?></td>
    <td style="text-align:right"><?php echo number_format((float)$closingamt,2); $final_closing[]=$closingamt;?></td>
  </tr>
         
    <?php  
     }    }   ?>

     <tr>
 <td style="text-align:right;" colspan="16"><strong>Closing</strong></td>
 <td style="text-align:right;"><?php if(!empty($final_closing) && array_sum($final_closing)!='0') { echo round(array_sum($final_closing),2); } else { echo "0.00"; } ?></td>
     </tr>
    
 </table>
  <?php } ?>
</div>
</div>
<script type="text/javascript">
  function checkdate(date)
{
  var from =document.getElementById('from').value;
  var to =document.getElementById('to').value;
  
    var cdate=date.split("/");
    var sdate=from.split("/");
    var edate=to.split("/");

    cdate[1]=cdate[1]-1;
    sdate[1]=sdate[1]-1;
    edate[1]=edate[1]-1;
       
    var dateC = new Date(cdate[2], cdate[1], cdate[0]); //Year, Month, Date 
    var dateS = new Date(sdate[2], sdate[1], sdate[0]); //Year, Month, Date
      var dateE = new Date(edate[2], edate[1], edate[0]); //Year, Month, Date

      if (dateS > dateE) {
          alert("Start Date is not greather then Date End.");
          document.getElementById('fromdate').value=from;
          document.getElementById('todate').value=to;
          
      }

      if (dateC > dateE) {
          alert("Date Not greather than "+to);
         document.getElementById('fromdate').value=from;
          document.getElementById('todate').value=to;
         
      }

      if (dateC < dateS) {
          alert(" Date Not less than "+from);
          document.getElementById('fromdate').value=from;
          document.getElementById('todate').value=to;
         
      } 
  
  
}

</script>