<?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"];
$tdate = date('Y-m-d');

$ctr = 0;
$rows = array();
if ($_REQUEST['weeklyfrmdt'] != '') {

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

    if ($month != '') {
        $vdatecond = "and month(`date`)='$month'";
    } else {
        $vdatecond = "and `date`>='$weeklyfrmdt' and `date`<='$weeklytodt'";
    }

//    $gettopitemgrp = mysqli_query($conn, "SELECT sum(a.`qty`) as sqty, a.`itemcode`, c.`name` as itemgrpname FROM `chaltran` a, 
//                                  `item` b, `itemgrp` c WHERE a.`itemcode` = b.`code` and b.`itemgrp` = c.`code` and 
//                                  a.chalno in (SELECT chalno FROM chalmain WHERE `date`>='$weeklyfrmdt' and `date`<='$weeklytodt')
//                                  group by c.code order by sum(qty) desc LIMIT 0,5") or die(mysqli_error($conn));

    mysqli_query($conn, "create temporary table chalitemtran SELECT sum(`qty`) as iqty, itemcode FROM `chaltran` WHERE 
                                  chalno in (SELECT chalno FROM chalmain WHERE chalno != '' $vdatecond)
                                  group by itemcode") or die(mysqli_error($conn));

    mysqli_query($conn, "create temporary table chalitemgrp SELECT a.`iqty`, a.`itemcode`, b.`itemgrp` FROM `chalitemtran` a, `item` b 
                 WHERE a.`itemcode`=b.`code`") or die(mysqli_error($conn));

    $gettopitemgrp = mysqli_query($conn, "SELECT sum(a.`iqty`) as `sqty`, b.`name` as `itemgrpname` FROM `chalitemgrp` a, `itemgrp` b 
                                  WHERE a.`itemgrp`=b.`code` group by b.`code` order by sum(a.`iqty`) desc LIMIT 0,5") or die(mysqli_error($conn));

    while ($ftopitemgrp = mysqli_fetch_array($gettopitemgrp)) {

        $itemgrp = $ftopitemgrp['itemgrpname'];
        $qty = $ftopitemgrp['sqty'];

        $rows[] = ['itemgrp' => $itemgrp,
            'qty' => $qty,];
        $ctr++;
    }
}

header("Content-type: application\json");
echo json_encode($rows);
