<?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 query
    $query = "SELECT 
        s.ID,
        s.InvoiceNumber,
        s.SalesType,
        s.SaleDate,
        s.CustomerID,
        c.CustomerName,
        c.CustomerCode,
        c.Mobile,
        c.City,
        s.SubTotal,
        s.BillDiscount,
        s.BillDiscountType,
        s.DiscountAmount,
        s.TotalAmount,
        s.RoundOffAmount,
        s.FinalAmount,
        s.PaymentMode,
        s.PaymentStatus,
        s.PaymentAmount,
        s.CashAmount,
        s.UpiAmount,
        s.CreditAmount,
        s.ReferenceNumber,
        s.Notes,
        COALESCE(SUM(sd.ProfitAmount), 0) as TotalProfit,
        COUNT(sd.ID) as ItemCount,
        u.FullName as AddedByName,
        stc.Description as SalesTypeDescription
    FROM tblsales s
    LEFT JOIN tblcustomers c ON s.CustomerID = c.ID
    LEFT JOIN tblsales_details sd ON s.ID = sd.SaleID
    LEFT JOIN tblusers u ON s.AddedBy = u.ID
    LEFT JOIN tblsales_type_config stc ON s.SalesType = stc.SalesType
    WHERE s.SaleDate BETWEEN ? AND ?";
    
    $params = [$startDate, $endDate];
    $types = "ss";
    
    // Add customer filter
    if ($customerId) {
        $query .= " AND c.CustomerCode = ?";
        $params[] = $customerId;
        $types .= "s";
    }
    
    // Add sales type filter
    if ($salesType) {
        $query .= " AND s.SalesType = ?";
        $params[] = $salesType;
        $types .= "s";
    }
    
    // Add payment status filter
    if ($paymentStatus) {
        $query .= " AND s.PaymentStatus = ?";
        $params[] = $paymentStatus;
        $types .= "s";
    }
    
    $query .= " GROUP BY s.ID ORDER BY s.SaleDate DESC, s.ID DESC";
    
    $stmt = $con->prepare($query);
    if (!$stmt) {
        throw new Exception("Query preparation failed: " . $con->error);
    }
    
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $sales = [];
    $summary = [
        'totalBills' => 0,
        'totalSubTotal' => 0,
        'totalDiscount' => 0,
        'totalBillAmount' => 0,
        'totalProfit' => 0,
        'totalPaid' => 0,
        'totalUnpaid' => 0,
        'totalCash' => 0,
        'totalUpi' => 0,
        'totalCredit' => 0
    ];
    
    while ($row = $result->fetch_assoc()) {
        $sales[] = $row;
        
        $summary['totalBills']++;
        $summary['totalSubTotal'] += $row['SubTotal'];
        $summary['totalDiscount'] += $row['DiscountAmount'];
        $summary['totalBillAmount'] += $row['FinalAmount'];
        $summary['totalProfit'] += $row['TotalProfit'];
        
        if ($row['PaymentStatus'] === 'Paid') {
            $summary['totalPaid'] += $row['FinalAmount'];
        } elseif ($row['PaymentStatus'] === 'Unpaid') {
            $summary['totalUnpaid'] += $row['FinalAmount'];
        } elseif ($row['PaymentStatus'] === 'Partial') {
            $summary['totalPaid'] += $row['PaymentAmount'];
            $summary['totalUnpaid'] += ($row['FinalAmount'] - $row['PaymentAmount']);
        }
        
        $summary['totalCash'] += $row['CashAmount'];
        $summary['totalUpi'] += $row['UpiAmount'];
        $summary['totalCredit'] += $row['CreditAmount'];
    }
    
    // Get customer info if filtered
    $customerInfo = null;
    if ($customerId) {
        $custStmt = $con->prepare("SELECT CustomerName, CustomerCode, City FROM tblcustomers WHERE CustomerCode = ?");
        $custStmt->bind_param("s", $customerId);
        $custStmt->execute();
        $custResult = $custStmt->get_result();
        if ($custResult->num_rows > 0) {
            $customerInfo = $custResult->fetch_assoc();
        }
        $custStmt->close();
    }
    
    // Get sales type description if filtered
    $salesTypeInfo = null;
    if ($salesType) {
        $typeStmt = $con->prepare("SELECT Description FROM tblsales_type_config WHERE SalesType = ?");
        $typeStmt->bind_param("s", $salesType);
        $typeStmt->execute();
        $typeResult = $typeStmt->get_result();
        if ($typeResult->num_rows > 0) {
            $typeRow = $typeResult->fetch_assoc();
            $salesTypeInfo = $typeRow['Description'];
        }
        $typeStmt->close();
    }
    
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'sales' => $sales,
        'summary' => $summary,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'customerInfo' => $customerInfo,
        'salesTypeInfo' => $salesTypeInfo,
        'paymentStatusInfo' => $paymentStatus
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
