<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);
$admin = $_SESSION["admin_" . $dbname];
$zroot = $_SESSION["zdbroot"];
$date = date('Y-m-d');
$ctr = 0;
$rows = array();
if ($_REQUEST['weeklyfrmdt'] != '') {

    $weeklyfrmdt = $_REQUEST['weeklyfrmdt'];
    $weeklytodt = $_REQUEST['weeklytodt'];

    
    mysqli_query($conn, "create temporary table itemdbf SELECT `name`, `itemgrp` FROM `item` group by `name` ") or die(mysqli_error($conn));
    
    $curitem = "";
    mysqli_query($conn, "create temporary table trandbf1 SELECT `itemname` FROM `itemtran` WHERE `source`='CH' and 
                `vouchdt`>='$weeklyfrmdt' and `vouchdt`<='$weeklytodt' group by `itemname`") or die(mysqli_error($conn));
//    while ($fcurweekitem = mysqli_fetch_array($getthisweekitem)) {
//        $curitem .= $fcurweekitem[itemcode] . ",";
//    }

    mysqli_query($conn, "create temporary table checkdbf SELECT *, 0000 as dno FROM itemdbf WHERE `name` 
                 NOT IN (select itemname from trandbf1) ") or die(mysqli_error($conn));
    
    
    $getlowitem = mysqli_query($conn, "SELECT * FROM checkdbf group by name order by name ") or die(mysqli_error($conn));
    while ($flowitem = mysqli_fetch_array($getlowitem)) {
        $iname = $flowitem['itemname'] ;

        $getlastchal = mysqli_query($conn, "SELECT  `vouchno`, `vouchdt` FROM `itemtran` WHERE `source`='CH' and `itemcode`='$icode' order by `vouchdt` desc LIMIT 0,1") or die(mysqli_error($conn));
        $flastchal = mysqli_fetch_array($getlastchal);


        if ($flastchal[vouchno] != '') {
            $diff = strtotime($flastchal[vouchdt]) - strtotime($weeklyfrmdt);
            $lastchalday = abs(round($diff / 86400));
        }

        mysqli_query($conn, "UPDATE checkdbf SET `dno`='$lastchalday' WHERE `name`='$iname' ") or die(mysqli_error($conn));
        $ctr++;
    }

    $getlowitemdno = mysqli_query($conn, "SELECT a.`itemgrp`, a.`dno`, b.`name` as grpname FROM `checkdbf` a, `itemgrp` b where a.itemgrp = b.code order by a.dno desc LIMIT 0,5") or die(mysqli_error($conn));
    while ($flowitemdno = mysqli_fetch_array($getlowitemdno)) {

        $rows[] = ['grpname' => $flowitemdno['grpname'],
            'datediff' => $flowitemdno['dno'],];
    }
}
header("Content-type: application\json");
echo json_encode($rows);
