<?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');
$year = date('Y') ;

$month = $_REQUEST['month'];
$firstdt = $year . '-' . $month . '-01' ;
        
$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 (source = 'SL' or source = 'SLDE' or source = 'SLEX' or source = 'SLOT')) ") 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 (source = 'SL' or source = 'SLDE' or source = 'SLEX' or source = 'SLOT') 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);
            $lastchalday = abs(round($diff / 86400));
        }

        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)) {

//        $custcode = $flowcustdno['accode'];
//        $getcustname = mysqli_query($conn, "SELECT `name` FROM `customer` where `custcode` = '$custcode'") or die(mysqli_error($conn));
//        $fcustname = mysqli_fetch_array($getcustname);
        

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