<?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');

$fseries = $_SESSION["series_" . $dbname];

$month = $_REQUEST['month'];

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

    mysqli_query($conn, "create temporary table sal_ret_data SELECT sum(abs(qty)) as iqty, itemcode from transacn WHERE month(`vouchdt`) = '$month'  
                                      and series = '$fseries' and (source = 'SL' or source = 'SR') group by itemcode ") or die(mysqli_error($conn));
    
    $gettopitem = mysqli_query($conn, "SELECT sum(a.iqty) as sqty, a.itemcode, b.`name` as `itemname` FROM `sal_ret_data` a, `item` b 
                                              WHERE a.itemcode = b.code group by b.`code` order by sum(a.iqty) asc LIMIT 0,20") or die(mysqli_error($conn));
    
    while ($ftopitem = mysqli_fetch_array($gettopitem)) {
        $itemgrp = $ftopitem['itemcode'] . ' - ' . $ftopitem['itemname'];;
        $qty = $ftopitem['sqty'];

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

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