<?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');
$customerId = isset($_GET['customerId']) ? $_GET['customerId'] : '';
$salesType = isset($_GET['salesType']) ? $_GET['salesType'] : '';
$hsnCode = isset($_GET['hsnCode']) ? trim($_GET['hsnCode']) : '';

try {
    // Build the HSN-wise aggregated query
    $query = "
        SELECT 
            COALESCE(NULLIF(sgd.HSNCode, ''), 'NOT SPECIFIED') as HSNCode,
            COUNT(DISTINCT s.ID) as TransactionCount,
            SUM(sgd.Quantity) as TotalQuantity,
            SUM(sgd.TaxableAmount) as TaxableAmount,
            SUM(sgd.CGSTAmount) as CGSTAmount,
            SUM(sgd.SGSTAmount) as SGSTAmount,
            SUM(sgd.IGSTAmount) as IGSTAmount,
            SUM(sgd.TotalTaxAmount) as TotalTax,
            SUM(sgd.FinalAmount) as TotalAmount,
            AVG(sgd.TaxPercentage) as AvgTaxRate,
            MAX(sgd.TaxType) as TaxType,
            GROUP_CONCAT(DISTINCT i.ItemName SEPARATOR ', ') as ItemNames
        FROM tblsales s
        INNER JOIN tblsales_gst_details sgd ON s.ID = sgd.SaleID
        LEFT JOIN tblitems i ON sgd.ProductID = i.ID
        LEFT JOIN tblcustomers c ON s.CustomerID = c.ID
        WHERE s.SaleDate BETWEEN ? AND ?
    ";
    
    $params = [$startDate, $endDate];
    $types = 'ss';
    
    // Add customer filter
    if ($customerId) {
        $query .= " AND c.CustomerID = ?";
        $params[] = $customerId;
        $types .= 's';
    }
    
    // Add sales type filter
    if ($salesType) {
        $query .= " AND s.SalesType = ?";
        $params[] = $salesType;
        $types .= 's';
    }
    
    // Add HSN code filter
    if ($hsnCode) {
        $query .= " AND sgd.HSNCode = ?";
        $params[] = $hsnCode;
        $types .= 's';
    }
    
    $query .= " GROUP BY sgd.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 = [
        'totalSales' => 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['totalSales'] += 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 tblsales_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 customer info if filtered
    $customerInfo = null;
    if ($customerId) {
        $customerQuery = "SELECT CustomerName, City FROM tblcustomers WHERE CustomerID = ? LIMIT 1";
        $customerStmt = mysqli_prepare($con, $customerQuery);
        mysqli_stmt_bind_param($customerStmt, 's', $customerId);
        mysqli_stmt_execute($customerStmt);
        $customerResult = mysqli_stmt_get_result($customerStmt);
        $customerInfo = mysqli_fetch_assoc($customerResult);
    }
    
    // Get sales type info if filtered
    $salesTypeInfo = null;
    if ($salesType) {
        $typeQuery = "SELECT SalesType FROM tblsales_type_config WHERE SalesType = ? LIMIT 1";
        $typeStmt = mysqli_prepare($con, $typeQuery);
        mysqli_stmt_bind_param($typeStmt, 's', $salesType);
        mysqli_stmt_execute($typeStmt);
        $typeResult = mysqli_stmt_get_result($typeStmt);
        $typeRow = mysqli_fetch_assoc($typeResult);
        $salesTypeInfo = $typeRow ? $typeRow['SalesType'] : null;
    }
    
    echo json_encode([
        'success' => true,
        'hsnData' => $hsnData,
        'summary' => $summary,
        'hsnList' => $hsnList,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'customerInfo' => $customerInfo,
        'salesTypeInfo' => $salesTypeInfo
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
