<?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'";
    }

    $gettopcust = mysqli_query($conn, "SELECT `custcode`, count(*) as cnt FROM `chalmain` where custcode != 'CA01' $vdatecond
                               group by custcode order by count(*) desc LIMIT 0,5") or die(mysqli_error($conn));

    while ($ftopcust = mysqli_fetch_array($gettopcust)) {
        $custcode = $ftopcust['custcode'];
        $getcustname = mysqli_query($conn, "SELECT `name` FROM `customer` where `custcode` = '$custcode'") or die(mysqli_error($conn));
        $fcustname = mysqli_fetch_array($getcustname);
        $count = $ftopcust['cnt'];

        $rows[] = ['custcode' => $fcustname[name],
            'count' => $count,];
        $ctr++;
    }
}

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