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

$zdb = $_SESSION["zdbyear_" . $dbname];
$zyear = right($zdb, 4);
$zd = left($zdb, -4);
$mfrdate = getzdates($zyear, 'S');
$mtodate = getzdates($zyear, 'E');
mysqli_select_db($conn, $zdb);

$admin = $_SESSION["admin_" . $dbname];
$zroot = $_SESSION["zdbroot"];
$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'] ;

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

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

    $monthName = date("F", mktime(null, null, null, $j));
    
    $prev = 0 ;
    $curr = 0 ;
    
    if ($pyno > 0) {
        $pyear = $fftmp['finyear'];
        $pdata = $zd . $pyear ;
        
        $prevsale = mysqli_query($conn, "SELECT sum(qty) as tqty from $pdata.transacn WHERE month(`vouchdt`) = '$j' and barcode= '$prodcode' 
                                         and (source = 'SL' or source = 'SLDE' or source = 'SLEX' or source = 'SLOT'  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 barcode= '$prodcode' 
                                      and (source = 'SL' or source = 'SLDE' or source = 'SLEX' or source = 'SLOT'  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);
