<?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"];
$fseries = $_SESSION["series_" . $dbname];

$date = date('Y-m-d');
$year = date('Y') ;

$month = $_REQUEST['month'];
$firstdt = $year . '-' . $month . '-01' ;

//browse($firstdt);

$ctr = 0;
$rows = array();

if ($_REQUEST['month'] != '') {

    mysqli_query($conn, "create temporary table custdbf SELECT `accode`, `name`, 0000 as `dno`, 'YYYY-mm-dd' as ddate FROM `accmast` 
                                                        WHERE `accode` not in (SELECT `accode` FROM `actran` WHERE month(`date`) = '$month'
                                                        and series = '$fseries' and source = 'SL') ") or die(mysqli_error($conn));

    $getlowcust = mysqli_query($conn, "SELECT `accode`, `name`, `dno`, ddate FROM `custdbf`") or die(mysqli_error($conn));
    while ($flowcust = mysqli_fetch_array($getlowcust)) {
        
        $getlastchal = mysqli_query($conn, "SELECT `vouchno`, `date` FROM `actran` WHERE `accode` = '$flowcust[accode]' 
                                            and series = '$fseries' and source = 'SL' order by date desc LIMIT 0,1") or die(mysqli_error($conn));
        $flastchal = mysqli_fetch_array($getlastchal);
        
        if ($flastchal['vouchno'] != '') {
            $diff = strtotime($flastchal['date']) - strtotime($firstdt);
//            browse($diff);
            $lastchalday = abs(round($diff / 86400));
//            browse($lastchalday);
        }

        mysqli_query($conn, "UPDATE `custdbf` SET `dno`='$lastchalday', `ddate`='$flastchal[date]'  WHERE `accode`='$flowcust[accode]'") or die(mysqli_error($conn));
        $ctr++;
    }
    
    $getlowcustdno = mysqli_query($conn, "SELECT `accode`, `name`, `dno`, `ddate` FROM `custdbf` order by dno desc LIMIT 0,10") or die(mysqli_error($conn));
    while ($flowcustdno = mysqli_fetch_array($getlowcustdno)) {

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