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

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

$startDate = isset($_GET['startDate']) && $_GET['startDate'] ? $_GET['startDate'] : date('Y-m-01');
$endDate = isset($_GET['endDate']) && $_GET['endDate'] ? $_GET['endDate'] : date('Y-m-t');
$customerId = isset($_GET['customerId']) ? trim($_GET['customerId']) : '';
$salesType = isset($_GET['salesType']) ? trim($_GET['salesType']) : '';
$paymentStatus = isset($_GET['paymentStatus']) ? trim($_GET['paymentStatus']) : '';

try {
    // Build the WHERE clause for sales
    $whereClauses = ["s.SaleDate BETWEEN '$startDate' AND '$endDate'"];
    
    if (!empty($customerId)) {
        $whereClauses[] = "c.CustomerID = '" . mysqli_real_escape_string($con, $customerId) . "'";
    }
    
    if (!empty($salesType)) {
        $whereClauses[] = "s.SalesType = '" . mysqli_real_escape_string($con, $salesType) . "'";
    }
    
    if (!empty($paymentStatus)) {
        $whereClauses[] = "s.PaymentStatus = '" . mysqli_real_escape_string($con, $paymentStatus) . "'";
    }
    
    $whereSQL = implode(' AND ', $whereClauses);
    
    // Get all sales with customer details
    $salesQuery = "
        SELECT 
            s.*,
            c.CustomerName,
            c.CustomerID as CustomerCode,
            c.Mobile,
            c.Address,
            c.City,
            c.State,
            c.GSTNumber
        FROM tblsales s
        INNER JOIN tblcustomers c ON s.CustomerID = c.ID
        WHERE $whereSQL
        ORDER BY s.SaleDate DESC, s.ID DESC
    ";
    
    $salesResult = mysqli_query($con, $salesQuery);
    
    if (!$salesResult) {
        throw new Exception('Database error: ' . mysqli_error($con));
    }
    
    $invoices = [];
    $totalBills = 0;
    $totalSubTotal = 0;
    $totalDiscount = 0;
    $totalBillAmount = 0;
    $totalProfit = 0;
    $totalPaid = 0;
    $totalUnpaid = 0;
    
    while ($sale = mysqli_fetch_assoc($salesResult)) {
        $saleId = $sale['ID'];
        
        // Get items for this sale
        $itemsQuery = "
            SELECT 
                ProductID,
                ProductCode,
                ProductName,
                HSNCode,
                Rate,
                Quantity,
                DiscountAmount,
                TaxableAmount,
                TaxPercentage,
                TaxType,
                CGSTPercent,
                CGSTAmount,
                SGSTPercent,
                SGSTAmount,
                IGSTPercent,
                IGSTAmount,
                TotalTaxAmount,
                FinalAmount
            FROM tblsales_gst_details
            WHERE SaleID = $saleId
            ORDER BY ID
        ";
        
        $itemsResult = mysqli_query($con, $itemsQuery);
        $items = [];
        $gstSummary = [];
        
        while ($item = mysqli_fetch_assoc($itemsResult)) {
            $items[] = $item;
            
            // Build GST summary
            $taxPercent = floatval($item['TaxPercentage']);
            if (!isset($gstSummary[$taxPercent])) {
                $gstSummary[$taxPercent] = [
                    'taxable' => 0,
                    'cgst' => 0,
                    'sgst' => 0,
                    'igst' => 0,
                    'total' => 0
                ];
            }
            
            $gstSummary[$taxPercent]['taxable'] += floatval($item['TaxableAmount']);
            $gstSummary[$taxPercent]['cgst'] += floatval($item['CGSTAmount']);
            $gstSummary[$taxPercent]['sgst'] += floatval($item['SGSTAmount']);
            $gstSummary[$taxPercent]['igst'] += floatval($item['IGSTAmount']);
            $gstSummary[$taxPercent]['total'] += floatval($item['TotalTaxAmount']);
        }
        
        // Calculate profit for this sale
        $profitQuery = "
            SELECT 
                SUM((sgd.Rate - COALESCE(p.PurchasePrice, 0)) * sgd.Quantity) as Profit
            FROM tblsales_gst_details sgd
            LEFT JOIN tblproducts p ON sgd.ProductID = p.ID
            WHERE sgd.SaleID = $saleId
        ";
        $profitResult = mysqli_query($con, $profitQuery);
        $profitRow = mysqli_fetch_assoc($profitResult);
        $profit = floatval($profitRow['Profit'] ?? 0);
        
        $finalAmount = floatval($sale['FinalAmount'] ?: $sale['TotalAmount']);
        $paidAmount = floatval($sale['PaymentAmount']);
        $unpaidAmount = $finalAmount - $paidAmount;
        
        // Add to invoice array
        $invoices[] = array_merge($sale, [
            'items' => $items,
            'gstSummary' => $gstSummary,
            'Profit' => $profit
        ]);
        
        // Accumulate totals
        $totalBills++;
        $totalSubTotal += floatval($sale['SubTotal']);
        $totalDiscount += floatval($sale['DiscountAmount']);
        $totalBillAmount += $finalAmount;
        $totalProfit += $profit;
        $totalPaid += $paidAmount;
        $totalUnpaid += $unpaidAmount;
    }
    
    // Get filter display info
    $filterInfo = [];
    
    if (!empty($customerId)) {
        $customerQuery = "SELECT CustomerName, City FROM tblcustomers WHERE CustomerID = '" . mysqli_real_escape_string($con, $customerId) . "'";
        $customerResult = mysqli_query($con, $customerQuery);
        if ($customerRow = mysqli_fetch_assoc($customerResult)) {
            $filterInfo['customerName'] = $customerRow['CustomerName'] . ($customerRow['City'] ? ' - ' . $customerRow['City'] : '');
        }
    }
    
    if (!empty($salesType)) {
        $filterInfo['salesType'] = $salesType;
    }
    
    if (!empty($paymentStatus)) {
        $filterInfo['paymentStatus'] = $paymentStatus;
    }
    
    $response = [
        'success' => true,
        'invoices' => $invoices,
        'summary' => [
            'totalBills' => $totalBills,
            'totalSubTotal' => $totalSubTotal,
            'totalDiscount' => $totalDiscount,
            'totalBillAmount' => $totalBillAmount,
            'totalProfit' => $totalProfit,
            'totalPaid' => $totalPaid,
            'totalUnpaid' => $totalUnpaid
        ],
        'startDate' => $startDate,
        'endDate' => $endDate,
        'filters' => $filterInfo
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
