<?php
$testdisplay ='';
 $totalval=0;
include("../../operainfo/getq2.php");
$x=getsecurity();

$stock_ref=safetext2(isset($_GET['stk']) ? $_GET['stk'] : '');
$hostcompanyid=safetext2(isset($_GET['hostcompanyid']) ? $_GET['hostcompanyid'] : '');
$monthyearonly=safetext2(isset($_GET['monthyearonly']) ? $_GET['monthyearonly'] : '');
print "<h1>Sales $stock_ref $global_company_name[$hostcompanyid]</h1>";
print "<a href=\"/intranet/databases/stock/showstock.php$x&stk=$stock_ref&hostcompanyid=$hostcompanyid\"><button>Older History Files</button></a>";
print "<button onclick=\"get_newsalesreport('$stock_ref','$hostcompanyid')\">Refresh</button>";
print "<button onclick=\"get_stockdeletedorders('$stock_ref','$hostcompanyid','0','')\">Cancelled Orders</button>";
// Need the Pricelist to currency link
$sql = "SELECT * FROM global_companys_bankaccounts WHERE companyid = ?";
$stmt = pdoquery($sql, array($hostcompanyid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $pricelist = $row['pricelist'];
    $currencypricelist[$pricelist] = $row['currency'];
}

// Need to pickup Invoice Dates
$sql = "SELECT * FROM viamedquote_orders_details WHERE stockref = ? GROUP BY orderid";
$stmt = pdoquery($sql, array($stock_ref));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $orderid = $row['orderid'];
    $orderpricelist[$orderid] = $row['pricelist'];
}


$sql = "SELECT invoiceref, invoicecommitedon FROM viamedquote_orders_invoices WHERE invoicecommitedon > 0 GROUP BY invoiceref";
$stmt = pdoquery($sql, array());
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $invoiceref = $row['invoiceref'];
    $invoicecommittedon[$invoiceref] = $row['invoicecommitedon'];
}




$sql = "SELECT COUNT(stockref) AS totalcount, SUM(goodstotal) AS sumgoods, viamedquote_orders_invoices_details.invoiceref, viamedquote_orders_invoices_details.deliveryid, viamedquote_orders_invoices_details.goodstotal, viamedquote_orders_invoices_details.orderid, viamedquote_orders.company_id FROM viamedquote_orders, viamedquote_orders_invoices_details WHERE viamedquote_orders_invoices_details.stockref = ? AND viamedquote_orders.hostcompany = ? AND viamedquote_orders_invoices_details.orderid = viamedquote_orders.id GROUP BY viamedquote_orders_invoices_details.invoiceref, viamedquote_orders_invoices_details.stockref, viamedquote_orders_invoices_details.deliveryid, viamedquote_orders_invoices_details.goodstotal ORDER BY invoiceref";
$lowestdate = $nowis;
$highestdate = 0;
$stmt = pdoquery($sql, array($stock_ref, $hostcompanyid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$currenctcodelist['ALL'] = 'ALL';
$testdisplay .= "<table class=CSSTable_n2><tr><td>INV</td><td>Delivery ID</td><td>Link</td><td>Qty</td><td>Raw Value</td><td>Currency</td><td>Pricelist</td></tr>";
foreach ($rows as $row) {
    $invoiceref = $row['invoiceref'];
    $invcommitdate = $invoicecommittedon[$invoiceref];
    $companyid = $row['company_id'];
    if ($invcommitdate > 0) {
        $orderid = $row['orderid'];
        $pricelist = $orderpricelist[$orderid];
        $deliveryid = $row['deliveryid'];

        $currenctcode = isset($currencypricelist[$pricelist]) ? $currencypricelist[$pricelist] : '';

        if ($deliveryid > 0) {
            $mod = 1;
        } else {
            $mod = -1;
        }

        $qtyinvoiced = (int)$row['totalcount'] * $mod;
        $goodstotal = $row['sumgoods'] * $mod;
        $datemonthlink = date("mY", $invcommitdate);
        $datemonthpricelistlink = date("mY", $invcommitdate) . $pricelist;

        if ($monthyearonly == '' || $monthyearonly == $datemonthlink) {
            $currenctcodelist[$currenctcode] = $currenctcode;

            if ($goodstotal == 0) {
				$totalfreedatemonthlinkqty[$datemonthlink] = isset($totalfreedatemonthlinkqty[$datemonthlink]) ? $totalfreedatemonthlinkqty[$datemonthlink] : 0;
                $totalfreedatemonthlinkqty[$datemonthlink] = $totalfreedatemonthlinkqty[$datemonthlink] + $qtyinvoiced;
            }
            $daymonthlink = date("dmY", $invcommitdate);
			$totaldatemonthlinkqty[$datemonthlink] = isset($totaldatemonthlinkqty[$datemonthlink]) ? $totaldatemonthlinkqty[$datemonthlink] : 0;
            $totaldatemonthlinkqty[$datemonthlink] = $totaldatemonthlinkqty[$datemonthlink] + $qtyinvoiced;
            $datemonthcurrencylink = $datemonthlink . "ALL";
			$totalqtydatemonthcurrencylink[$datemonthcurrencylink] = isset($totalqtydatemonthcurrencylink[$datemonthcurrencylink]) ? $totalqtydatemonthcurrencylink[$datemonthcurrencylink] : 0;
            $totalqtydatemonthcurrencylink[$datemonthcurrencylink] = $totalqtydatemonthcurrencylink[$datemonthcurrencylink] + $qtyinvoiced;
            $datemonthcurrencylink = $datemonthlink . $currenctcode;
			$totalqtydatemonthcurrencylink[$datemonthcurrencylink] = isset($totalqtydatemonthcurrencylink[$datemonthcurrencylink]) ? $totalqtydatemonthcurrencylink[$datemonthcurrencylink] : 0;
            $totalqtydatemonthcurrencylink[$datemonthcurrencylink] = $totalqtydatemonthcurrencylink[$datemonthcurrencylink] + $qtyinvoiced;
			$totalvaluedatemonthcurrencylink[$datemonthcurrencylink] = isset($totalvaluedatemonthcurrencylink[$datemonthcurrencylink]) ? $totalvaluedatemonthcurrencylink[$datemonthcurrencylink] : 0;
            $totalvaluedatemonthcurrencylink[$datemonthcurrencylink] = $totalvaluedatemonthcurrencylink[$datemonthcurrencylink] + $goodstotal;
 			$totaldaymonthlinkqty[$daymonthlink]= isset( $totaldaymonthlinkqty[$daymonthlink]) ? $totaldaymonthlinkqty[$daymonthlink]: 0;
            $totaldaymonthlinkqty[$daymonthlink] = $totaldaymonthlinkqty[$daymonthlink] + $qtyinvoiced;

            if ($lowestdate > $invcommitdate) {
                $lowestdate = $invcommitdate;
            }
            if ($highestdate < $invcommitdate) {
                $highestdate = $invcommitdate;
            }
            $testdisplay .= "<tr><Td>$invoiceref</td><td>$deliveryid</td><td>$datemonthlink</td><td>$qtyinvoiced</td><td>$goodstotal</td><td>$currenctcode</td><td>$pricelist</td></tr>";
        }

        $companyidlist[$companyid] = $companyid;
        $datemonthcustomerlink = date("mY", $invcommitdate) . $companyid;
		$customerdisplaylineqty[$datemonthcustomerlink]  = isset($customerdisplaylineqty[$datemonthcustomerlink] ) ? $customerdisplaylineqty[$datemonthcustomerlink]  : 0;
        $customerdisplaylineqty[$datemonthcustomerlink] = $customerdisplaylineqty[$datemonthcustomerlink] + $qtyinvoiced;
		$customerdisplaylinevalue[$datemonthcustomerlink]  = isset($customerdisplaylinevalue[$datemonthcustomerlink]) ?$customerdisplaylinevalue[$datemonthcustomerlink] : 0;
        $customerdisplaylinevalue[$datemonthcustomerlink] = $customerdisplaylinevalue[$datemonthcustomerlink] + $goodstotal;
    }
}
$lowestdateyear=date("Y",$lowestdate);


if ($highestdate==0) {
$highestdateyear=$lowestdateyear;
} else {
$highestdateyear=date("Y",$highestdate);
}



$maindisplay = "<h1>$lowestdateyear To $highestdateyear</h1>";
	if ($hostcompanyid==4) {
		$currenctcodelist=null;
		$currenctcodelist['ALL']='ALL';
	}
foreach ($currenctcodelist as $currenctcode) {

$curdip="";
if ($currenctcode=='USD') {
 $curdip=" $ ";
}
if ($currenctcode=='GBP') {
 $curdip=" &pound; ";
}
if ($currenctcode=='EUR') {
 $curdip=" &euro; ";
}

if ($currenctcode=='ALL') {
 $curdip="";
}

$maindisplay .= "<h1>$currenctcode Quantities</h1><table class=CSSTable_n2 width=75%><tr><td>Year</td>";

// Do month Thing!
$month=1;
while ($month < 13) {
	$displaymonth = date("M",mktime(1,1,1,$month,1,2000));
	$maindisplay .= "<td align=middle>$displaymonth</td>";
	$month=$month+1;
}
// End Month Thing
$maindisplay .= "<td>Total</td></tr>";
$year=$lowestdateyear;
while ($year < $highestdateyear+1) {
	$maindisplay .= "<TR bgcolor=\"#92adc8\" onMouseOver=\"this.bgColor='#d4deea';\" onMouseOut=\"this.bgColor='#92adc8';\">";
	$maindisplay .= "<td><a href=\"/intranet/databases/stock/stksales.php$x&stkref=$stock_ref&year=$year&hostcompanyid=$hostcompanyid&cur=$currenctcode\"><img src=\"/intranet/images/mag.png\" width=16 height=16></a>$year</td>";
	
// Do month Thing!
	$month=1;
	$total=0;
	while ($month < 13) {
		$datemonthlink=date("mY",mktime(1,1,1,$month,1,$year));		
		$datemonthcurrencylink=$datemonthlink.$currenctcode;
		$totalqtydatemonthcurrencylink[$datemonthcurrencylink] = isset ($totalqtydatemonthcurrencylink[$datemonthcurrencylink]) ? $totalqtydatemonthcurrencylink[$datemonthcurrencylink] : 0;
		$totalqtydatemonthcurrencylink[$datemonthcurrencylink] =$totalqtydatemonthcurrencylink[$datemonthcurrencylink]+0;
		$maindisplay .= "<td align=middle>";
			$totalqtydatemonthcurrencylink[$datemonthcurrencylink] = isset ($totalqtydatemonthcurrencylink[$datemonthcurrencylink]) ? $totalqtydatemonthcurrencylink[$datemonthcurrencylink] : 0;
	$totalvaluedatemonthcurrencylink[$datemonthcurrencylink] = isset ($totalvaluedatemonthcurrencylink[$datemonthcurrencylink]) ? $totalvaluedatemonthcurrencylink[$datemonthcurrencylink]: 0;
if ($totalqtydatemonthcurrencylink[$datemonthcurrencylink] > 0 ) {

$maindisplay .= "
<a href=\"/intranet/databases/stock/stksales.php$x&stkref=$stock_ref&year=$year&hostcompanyid=$hostcompanyid&cur=$currenctcode&startmon=$month&endmon=$month\">

$totalqtydatemonthcurrencylink[$datemonthcurrencylink]<bR>
$curdip$totalvaluedatemonthcurrencylink[$datemonthcurrencylink]</a>
";
}
$maindisplay .= "</td>";
		$total=$total+$totalqtydatemonthcurrencylink[$datemonthcurrencylink];
		$totalval=$totalval+$totalvaluedatemonthcurrencylink[$datemonthcurrencylink];
		$month=$month+1;
	}
// End Month Thing	

	$maindisplay .= "<td>$total<br>";
	if ($totalval > 0 ) {
	$maindisplay .= "$curdip$totalval";
}
	$maindisplay .= "</td></tr>";
	$year++;
	$totalval=0;
}
$maindisplay .= "</table>";


}
print $maindisplay ;


if ($monthyearonly=='') {
	// Show recent customers

// Checked for PHP5.6 / 8.x compatibility
$datefrom = mktime(1, 1, 1, date("n") - 18, 1, date("Y"));

$datetoo  = $nowis;
$prndatefrom= date("d M Y",$datefrom);
$prndateto= date("d M Y",$datetoo);
print "<h1>Customers <br>$prndatefrom- $prndateto</h1>";
print "<br>";	
$customeroutput = "<table class=CSSTable_n2><tr><td>CID</td><td>Customer</td>";
$datecountmonth=0;

while ( $datecountmonth < 18 ) {
	$monthcount=(18-$datecountmonth);
	$cdate=mktime(1,1,1,date("m")-$monthcount,1,date("Y"));
	$dddate = date("m Y",$cdate);
	$customeroutput .= "<td>";
	$customeroutput .= "$dddate ";
	$customeroutput .="</td>";
	$datecountmonth++;
	}
$customeroutput .= "</tr>";
if (!isset($companyidlist) || !is_array($companyidlist)) {
    $companyidlist = array(); // Ensure it's at least an empty array
}
foreach($companyidlist as $companyid) {
$linetotal=0;
$datecountmonth=0;
$customeroutputline="<tr><td>" . linkcrm($x,$companyid,'') . "$companyid</td><td><a href=\"/intranet/databases/sales_reports/zoomcompanystockyear.php$x&stkref=$stock_ref&companyid=$companyid\">
<input type=button   value='Zoom'></a>" . getcompanyname($companyid) . "</td>";
	while ( $datecountmonth < 18 ) {
	$monthcount=(18-$datecountmonth);
	$cdate=mktime(1,1,1,date("m")-$monthcount,1,date("y"));
	$dddate = date("m Y",$cdate);
	$datemonthcustomerlink=date("mY",$cdate).$companyid;
	$customerdisplaylineqty[$datemonthcustomerlink]= isset( $customerdisplaylineqty[$datemonthcustomerlink] ) ? $customerdisplaylineqty[$datemonthcustomerlink] : 0 ;
	$linetotal=$linetotal+$customerdisplaylineqty[$datemonthcustomerlink];
	$customeroutputline .= "<td>" . $customerdisplaylineqty[$datemonthcustomerlink] . "</td>";
	$datecountmonth++;
	}
	$customeroutputline .= "</tr>";
	if ($linetotal > 0 ) {
		$customeroutput .= $customeroutputline;
		}
}


$customeroutput .= "</table>";

	print $customeroutput ;
	

//print $customeroutput ;
	} else {
	print "$monthyearonly ";	
		}


print " <br><br><br><br>";
?>

