<?php
header('Content-Type: application/json');
session_start();
include_once('../../includes/config.php');

if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$startDate = isset($_GET['startDate']) ? $_GET['startDate'] : date('Y-m-01');
$endDate = isset($_GET['endDate']) ? $_GET['endDate'] : date('Y-m-t');
$supplierId = isset($_GET['supplierId']) ? $_GET['supplierId'] : '';
$purchaseType = isset($_GET['purchaseType']) ? $_GET['purchaseType'] : '';
$hsnCode = isset($_GET['hsnCode']) ? trim($_GET['hsnCode']) : '';

try {
    // Build the HSN-wise aggregated query
    $query = "
        SELECT 
            COALESCE(NULLIF(pgd.HSNCode, ''), 'NOT SPECIFIED') as HSNCode,
            COUNT(DISTINCT p.ID) as TransactionCount,
            SUM(pgd.Quantity) as TotalQuantity,
            SUM(pgd.TaxableAmount) as TaxableAmount,
            SUM(pgd.CGSTAmount) as CGSTAmount,
            SUM(pgd.SGSTAmount) as SGSTAmount,
            SUM(pgd.IGSTAmount) as IGSTAmount,
            SUM(pgd.TotalTaxAmount) as TotalTax,
            SUM(pgd.FinalAmount) as TotalAmount,
            AVG(pgd.TaxPercentage) as AvgTaxRate,
            MAX(pgd.TaxType) as TaxType,
            GROUP_CONCAT(DISTINCT i.ItemName SEPARATOR ', ') as ItemNames
        FROM tblpurchases p
        INNER JOIN tblpurchases_gst_details pgd ON p.ID = pgd.PurchaseID
        LEFT JOIN tblitems i ON pgd.ProductID = i.ID
        LEFT JOIN tblsuppliers s ON p.SupplierID = s.ID
        WHERE p.PurchaseDate BETWEEN ? AND ?
    ";
    
    $params = [$startDate, $endDate];
    $types = 'ss';
    
    // Add supplier filter
    if ($supplierId) {
        $query .= " AND s.SupplierID = ?";
        $params[] = $supplierId;
        $types .= 's';
    }
    
    // Add purchase type filter
    if ($purchaseType) {
        $query .= " AND p.PurchaseType = ?";
        $params[] = $purchaseType;
        $types .= 's';
    }
    
    // Add HSN code filter
    if ($hsnCode) {
        $query .= " AND pgd.HSNCode = ?";
        $params[] = $hsnCode;
        $types .= 's';
    }
    
    $query .= " GROUP BY pgd.HSNCode ORDER BY TotalAmount DESC";
    
    $stmt = mysqli_prepare($con, $query);
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    $hsnData = [];
    $summary = [
        'totalPurchases' => 0,
        'taxableAmount' => 0,
        'cgstAmount' => 0,
        'sgstAmount' => 0,
        'igstAmount' => 0,
        'totalTax' => 0,
        'totalQuantity' => 0,
        'hsnCount' => 0,
        'transactionCount' => 0
    ];
    
    while ($row = mysqli_fetch_assoc($result)) {
        $hsnData[] = $row;
        
        $summary['totalPurchases'] += floatval($row['TotalAmount']);
        $summary['taxableAmount'] += floatval($row['TaxableAmount']);
        $summary['cgstAmount'] += floatval($row['CGSTAmount']);
        $summary['sgstAmount'] += floatval($row['SGSTAmount']);
        $summary['igstAmount'] += floatval($row['IGSTAmount']);
        $summary['totalTax'] += floatval($row['TotalTax']);
        $summary['totalQuantity'] += floatval($row['TotalQuantity']);
        $summary['transactionCount'] += intval($row['TransactionCount']);
        $summary['hsnCount']++;
    }
    
    // Get all unique HSN codes for filter dropdown
    $hsnListQuery = "
        SELECT DISTINCT 
            COALESCE(NULLIF(HSNCode, ''), 'NOT SPECIFIED') as HSNCode
        FROM tblpurchases_gst_details
        WHERE HSNCode IS NOT NULL
        ORDER BY HSNCode
    ";
    $hsnListResult = mysqli_query($con, $hsnListQuery);
    $hsnList = [];
    while ($hsnRow = mysqli_fetch_assoc($hsnListResult)) {
        $hsnList[] = $hsnRow['HSNCode'];
    }
    
    // Get supplier info if filtered
    $supplierInfo = null;
    if ($supplierId) {
        $supplierQuery = "SELECT SupplierName, City FROM tblsuppliers WHERE SupplierID = ? LIMIT 1";
        $supplierStmt = mysqli_prepare($con, $supplierQuery);
        mysqli_stmt_bind_param($supplierStmt, 's', $supplierId);
        mysqli_stmt_execute($supplierStmt);
        $supplierResult = mysqli_stmt_get_result($supplierStmt);
        $supplierInfo = mysqli_fetch_assoc($supplierResult);
    }
    
    // Get purchase type info if filtered
    $purchaseTypeInfo = null;
    if ($purchaseType) {
        $typeQuery = "SELECT PurchaseType FROM tblpurchase_type_config WHERE PurchaseType = ? LIMIT 1";
        $typeStmt = mysqli_prepare($con, $typeQuery);
        mysqli_stmt_bind_param($typeStmt, 's', $purchaseType);
        mysqli_stmt_execute($typeStmt);
        $typeResult = mysqli_stmt_get_result($typeStmt);
        $typeRow = mysqli_fetch_assoc($typeResult);
        $purchaseTypeInfo = $typeRow ? $typeRow['PurchaseType'] : null;
    }
    
    echo json_encode([
        'success' => true,
        'hsnData' => $hsnData,
        'summary' => $summary,
        'hsnList' => $hsnList,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'supplierInfo' => $supplierInfo,
        'purchaseTypeInfo' => $purchaseTypeInfo
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
