<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

// 날짜 기본값 설정 (최근 1개월)
$currentDate = date("Y-m-t"); // 말일 기준
// $defaultFromDate = date("Y-m-d", strtotime("-1 month"));
$defaultFromDate = date("Y-m-01");
$fromdate = isset($_REQUEST['fromdate']) && $_REQUEST['fromdate'] ? $_REQUEST['fromdate'] : $defaultFromDate;
$todate   = isset($_REQUEST['todate']) && $_REQUEST['todate'] ? $_REQUEST['todate'] : $currentDate;

$tablename = 'instock';

try {
	// instock 테이블에서 검사일(inspection_date) 기준, 납품업체별로 매입가(VAT별도)의 합계를 구하고,
	// 합계가 0인 업체는 제외(HAVING 절 사용)
	$sql = "SELECT supplier, SUM(purchase_price_excl_vat) as total_amount
			FROM {$DB}.{$tablename}
			WHERE inspection_date BETWEEN :fromdate AND :todate
			  AND is_deleted IS NULL
			GROUP BY supplier
			HAVING SUM(purchase_price_excl_vat) > 0
			ORDER BY total_amount DESC";

	$stmh = $pdo->prepare($sql);
	$stmh->bindValue(':fromdate', $fromdate);
	$stmh->bindValue(':todate', $todate);
	$stmh->execute();
	$rows = $stmh->fetchAll(PDO::FETCH_ASSOC);

	// 차트 데이터 생성 (Highcharts용)
	$chartData = [];
	foreach ($rows as $row) {
		$chartData[] = [
			"name" => $row['supplier'],
			"y" => (float)$row['total_amount']
		];
	}
	$jsonChartData = json_encode($chartData, JSON_UNESCAPED_UNICODE);
} catch (PDOException $Exception) {
	die("오류: " . $Exception->getMessage());
}
?>