<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

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

//browse($fseries);
$zyear = right($zdb, 4);
//browse($zdb);
//browse($zyear);
$zd = left($zdb, -4);
//browse($zd);
$mfrdate = getzdates($zyear, 'S');
$mtodate = getzdates($zyear, 'E');
//browse($mfrdate);
//browse($mtodate);
mysqli_select_db($conn, $zdb);

$admin = $_SESSION["admin_" . $dbname];
$zroot = $_SESSION["zdbroot"];
//browse($zroot);
$tdate = date('Y-m-d');

$yytmp = mysqli_query($conn, "SELECT finyear from $zroot.compyear WHERE finyear < '$zyear' ") or die(mysqli_error($conn));
$fftmp = mysqli_fetch_array($yytmp);
$pyno = mysqli_num_rows($yytmp);

$ctr = 0;
$rows = array();
$prodcode =  $_REQUEST['prodcode'] ;
$accode =  $_REQUEST['accode'] ;

$acond = '';
if ($accode != ''){
    $acond = " and accode = '$accode' " ;
}
    //    browse($acond);
    

for ($i = 1; $i <= 12; $i++) {

    if ($i < 10) {
        $j = $i + 3;
    } else {
        $j = $i - 9;
    }

    $monthName = date("F", strtotime('00-'.$j.'-01'));
    
    $prev = 0 ;
    $curr = 0 ;
    
    if ($pyno > 0) {
        $pyear = $fftmp['finyear'];
        $pdata = $zd . $pyear ;
//        browse($pdata);
        $prevsale = mysqli_query($conn, "SELECT sum(qty) as tqty from $pdata.transacn WHERE month(`vouchdt`) = '$j' and itemcode = '$prodcode' and series = '$fseries'
                                         $acond and (source = 'SL' or source = 'SR') ") or die(mysqli_error($conn));
        $fetprev = mysqli_fetch_array($prevsale);
        $prev = abs($fetprev['tqty']);
    }
    
    $tradesale = mysqli_query($conn, "SELECT sum(qty) as tqty from transacn WHERE month(`vouchdt`) = '$j' and itemcode = '$prodcode' and series = '$fseries'
                                      $acond and (source = 'SL' or  source = 'SR') ") or die(mysqli_error($conn));
    $fetlocal = mysqli_fetch_array($tradesale);
    $curr = abs($fetlocal['tqty']);
    
    if($prev == ''){
        $prev = 0;
    }

    if($curr == ''){
        $curr = 0;
    }

    $rows[] = ['month' => $monthName,
        'prev' => $prev,
        'curr' => $curr];
    $ctr++;
}
//}

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