<?php session_name('CAKEPHP'); session_start();
error_reporting(FALSE);
$PageSecurity = 11;
include('includes/DefinePOClass.php');
include('includes/DefineSerialItems.php');
include('includes/SQL_CommonFunctions.inc');
$title = _('Expiry Products');
include('cocoon_config.php');

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

//For hmis User
$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);
}


?>
<script language="javascript" type="text/javascript">
  function get_itemsubgroup(str) {
    if (str == "") {
      document.getElementById("sub_id").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("sub_id").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "item_subcategory.php?main=" + str, true);
    xmlhttp.send();
  }

  function get_item(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;
      }
    }
    xmlhttp.open("GET", "Get_itemcode.php?sub=" + str, true);
    xmlhttp.send();
  }

  function showItems(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;
      }
    }
    xmlhttp.open("GET", "Get_itemcode.php?partName=" + str, true);
    xmlhttp.send();
  }



  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_sitenamedata2.php?site=" + str, true);
    xmlhttp.send();

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


  }
</script>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
  <div class="tab_div">
    <h1>Issue Register</h1>
    <form method="post" action="">
      <table width="100%" border="0" cellpadding="3" cellspacing="0">
        <tr class="row1">
          <!-- <td width="13%" ><strong>Branch</strong></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="">Select Site</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</td>
          <td width="35%">
            <div id="storedata7">
              <?php
              if ($get_store_id != '') {
                $store_sql = "SELECT id, StoreName,storecode FROM storetype where id in(" . $main_store . "," . $get_store_id . ") order by id ASC";
              } else if ($main_store != '') {
                $store_sql = "SELECT id, StoreName,storecode FROM storetype where id in(" . $main_store . ") order by id ASC";
              } else {
                $store_sql = "SELECT id, StoreName,storecode FROM storetype order by id ASC";
              }
              $store_result = DB_query($store_sql, $db);
              ?>
              <select name="store1">
                <option value="0">Select</option>
                <?php
                while ($store_row = DB_fetch_array($store_result)) {

                ?>
                  <option value="<?php echo $store_row['id']; ?>" <?php echo ($_REQUEST['store1'] == $store_row['id'] ? 'selected' : '') ?>><?php echo $store_row['StoreName']; ?></option>
                <?php } ?>
              </select>
            </div>
          </td>
          <td width="13%" align="right">Item Code</td>
          <td><input type="text" name="itemcode" value="<?php echo $_REQUEST['itemcode']; ?>"></td>
        </tr>
        <tr class="row1">
          <td align="right">From Date</td>
          <td><input type="text" name="from_date" id="fromdate" class="datepicker" value="<?php if (isset($_REQUEST['from_date'])) {
                                                                                            echo $_REQUEST['from_date'];
                                                                                          } else {
                                                                                            echo $first_date;
                                                                                          } ?>" onchange="javascript:checkdate(this.value)"></td>
          <td align="right">To Date</td>
          <td><input type="text" name="to_date" id="todate" value="<?php if (isset($_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'>
            <input type="hidden" id='cur_date' value="<?php echo $cur_date; ?>">
          </td>
        </tr>
        <tr class="row1">
          <td style="text-align:center;" colspan="4">
            <input type="submit" name="view" class="search" value="Search" onclick="return validate_branch();">
          </td>
        </tr>
      </table>

    </form>
    <?php
    function getFieldvalue_cake($table, $condition, $val, $field)
    {
      global $db;
      //echo "select ".$field." from ".$table." where ".$condition." ='".$val."'";
      $sql = mysqli_query($db, "select " . $field . " from " . $table . " where " . $condition . " ='" . $val . "'");
      $r = mysqli_fetch_array($sql);
      //echo "select ".$field." from ".$table." where ".$condition." ='".$val."'"; 
      return ($r[$field]);
    }
    if ($_REQUEST['view'] != '') {

      $fromdate = $_REQUEST['from_date'];
      $todate = $_REQUEST['to_date'];
      //$emp=$_REQUEST['employee'];
      //$cont=$_REQUEST['contactor'];
      $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];
      //$sitename=$s->getField('locations','loccode',$_REQUEST['site'],'locationname');
      $ref_storeid = $s->getField('storetype', 'id', $_REQUEST['store1'], 'ref_storemaster_id');
      $storecode = getFieldvalue_cake('store_masters', 'id', $ref_storeid, 'store_code');


      $filter = array();
      if ($_REQUEST['itemcode'] != '') {
        $filter[] = "item_code = '" . $_REQUEST['itemcode'] . "'";
      }
      if ($_REQUEST['store1'] != '0') {
        $filter[] = "store_code = '" . $storecode . "'";
      }
      if ($_REQUEST['from_date'] != '' && $_REQUEST['to_date'] != '') {
        $filter[] = "expire_date BETWEEN '$from' and '$to'";
      }
      if ($filter != '') {
        $filter = implode(' and ', $filter);
      }
      if ($_REQUEST['site'] != '' && $_REQUEST['from_date'] != '' && $_REQUEST['to_date'] != '') {
        $message = "Showing Records of Branch <u><span class='fntBig'>" . $sitename . "</span></u> From <u><span class='fntBig'>" . $from . "</span></u> to <u><span class='fntBig'>" . $to . "</span></u>";
      } else if ($_REQUEST['site'] != '' && $_REQUEST['from_date'] == '' && $_REQUEST['to_date'] == '') {
        $message = "Showing Records of Branch <u><span class='fntBig'>" . $sitename . "</span></u>";
      } else if ($_REQUEST['site'] == '' && $_REQUEST['from_date'] != '' && $_REQUEST['to_date'] != '') {
        $message = "Showing Records From <u><span class='fntBig'>" . $from . "</span></u> to <u><span class='fntBig'>" . $to . "</span></u>";
      }
      if ($filter != '') {

        //$sql ="SELECT * FROM opening_stockitemwise WHERE $filter and companyID='".$_SESSION['ACGCompanyId']."' group by opening_stockitemwise.id ";
        $sql = "SELECT * FROM batchdetails WHERE $filter group by id ";
      } else {
        //$sql ="SELECT * FROM opening_stockitemwise WHERE companyID='".$_SESSION['ACGCompanyId']."' group by opening_stockitemwise.id ";
        $sql = "SELECT * FROM batchdetails WHERE group by id ";
      }

      $_SESSION['expiryreport'] = $sql;
      $_SESSION['mess'] = $message;

    ?>
      <p align="center"><strong><?php echo $message; ?></strong> <a href="expiryproductsreports.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" class="search" style="float:right;">Print</a></p>

      <table width="100%" cellpadding="3" cellspacing="0" border="0" class="thborder">
        <tr>
          <th width="5%">S. No.</th>
          <th width="15%">Store</th>
          <th width="10%">Item Code</th>
          <th>Item Name</th>
          <th width="12%">Batch No.</th>
          <th width="10%" class="text-right">Quantity</th>
          <th width="10%" class="text-right">Value </th>
          <th width="10%" class="text-right">Amount</th>
          <th width="10%">Expiry Date</th>
        </tr>
        <?php
        $i = 1;
        $result = mysqli_query($link1, $sql);
        $numrow1 = mysqli_num_rows($result);
        if (mysqli_num_rows($result) > 0) {
          while ($myrow = mysqli_fetch_array($result)) {
            //if($myrow['expiry'] <= $todate)
            // {
            $hmis_storename = getFieldvalue_cake('store_masters', 'store_code', $myrow['store_code'], 'store_desc');
            $hmis_itemname = getFieldvalue_cake('itemforms', 'item_code', $myrow['item_code'], 'item_desc');

        ?>
            <tr>
              <td><?php echo $i; ?></td>
              <td><?php echo $hmis_storename; ?></td>
              <td><?php echo $myrow['item_code']; ?></td>
              <td><?php echo $hmis_itemname; ?></td>
              <td><?php echo $myrow['batch_no']; ?></td>
              <td style="text-align:right;"><?php echo number_format((float)$myrow['qty'], 2);
                                            $stock[] = $myrow['qty']; ?></td>
              <td style="text-align:right;"><?php echo $myrow['mrp'];
                                            $amount[] = $myrow['mrp']; ?></td>
              <td style="text-align:right;"><?php echo $myrow['mrp'] * $myrow['qty'];
                                            $total_amount[] = $myrow['mrp'] * $myrow['qty']; ?></td>
              <td><?php echo date('d/m/Y', strtotime($myrow['expire_date'])); ?></td>
            </tr>

          <?php $i++;
          }
          if ($numrow1 > 0) { ?>
            <tr>
              <td colspan="5" style="padding:0px;" valign="top">
              <td style="text-align:right;"><strong>Total Value</strong></td>
              <td class="f12 wdt6" style="text-align:right"><strong><?php echo number_format(array_sum($amount), 2); ?></strong></td>
              <td class="f12 wdt6" style="text-align:right"><strong><?php echo number_format(array_sum($total_amount), 2); ?></strong></td>
              <td>&nbsp;</td>
            </tr>

          <?php } ?>

        <?php } else { ?>
          <tr>
            <td colspan="9" align="center">No Records</td>
          </tr> <?php } ?>
        </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 cur_date = document.getElementById('cur_date').value;
    var cdate = date.split("/");
    var sdate = from.split("/");
    var edate = cur_date.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 = cur_date;
    }

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

    // }

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

    // }




  }

  function validate_branch() {
    var branch = $('#site').val();
    if (branch == 0 && branch == '') {
      alert("Select Branch");
      return false;
    }
    return true;
  }
</script>