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

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

try {
    // Get parameters
    $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']) : '';
    
    // Validate dates
    if (!strtotime($startDate) || !strtotime($endDate)) {
        throw new Exception('Invalid date format');
    }
    
    // Build query
    $query = "
        SELECT 
            s.ID,
            s.InvoiceNumber,
            s.SalesType,
            stc.Description as SalesTypeDescription,
            s.SaleDate,
            s.CustomerID,
            c.CustomerName,
            c.GSTNumber,
            c.City,
            s.SubTotal,
            s.TotalAmount,
            s.FinalAmount,
            s.PaymentStatus,
            COALESCE(SUM(gst.TaxableAmount), 0) as TaxableAmount,
            COALESCE(MAX(gst.CGSTPercent), 0) as CGSTPercent,
            COALESCE(SUM(gst.CGSTAmount), 0) as CGSTAmount,
            COALESCE(MAX(gst.SGSTPercent), 0) as SGSTPercent,
            COALESCE(SUM(gst.SGSTAmount), 0) as SGSTAmount,
            COALESCE(MAX(gst.IGSTPercent), 0) as IGSTPercent,
            COALESCE(SUM(gst.IGSTAmount), 0) as IGSTAmount,
            COALESCE(SUM(gst.TotalTaxAmount), 0) as TotalTax,
            COALESCE(MAX(gst.TaxType), 'INTRA') as TaxType
        FROM tblsales s
        LEFT JOIN tblcustomers c ON s.CustomerID = c.ID
        LEFT JOIN tblsales_type_config stc ON s.SalesType = stc.SalesType
        LEFT JOIN tblsales_gst_details gst ON s.ID = gst.SaleID
        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";
    }
    
    $query .= " GROUP BY s.ID, s.InvoiceNumber, s.SalesType, stc.Description, s.SaleDate, s.CustomerID, 
                c.CustomerName, c.GSTNumber, c.City, s.SubTotal, s.TotalAmount, s.FinalAmount, s.PaymentStatus
                ORDER BY s.SaleDate DESC, s.ID DESC";
    
    // Prepare and execute
    $stmt = mysqli_prepare($con, $query);
    if (!$stmt) {
        throw new Exception('Database error: ' . mysqli_error($con));
    }
    
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    $sales = [];
    $summary = [
        'totalSales' => 0,
        'taxableAmount' => 0,
        'cgstAmount' => 0,
        'sgstAmount' => 0,
        'igstAmount' => 0,
        'totalTax' => 0
    ];
    
    while ($row = mysqli_fetch_assoc($result)) {
        $sales[] = $row;
        // For returns, subtract from totals instead of adding
        $isReturn = strpos($row['SalesType'], 'RETURN') !== false;
        $multiplier = $isReturn ? -1 : 1;
        
        $summary['totalSales'] += floatval($row['FinalAmount']) * $multiplier;
        $summary['taxableAmount'] += floatval($row['TaxableAmount']) * $multiplier;
        $summary['cgstAmount'] += floatval($row['CGSTAmount']) * $multiplier;
        $summary['sgstAmount'] += floatval($row['SGSTAmount']) * $multiplier;
        $summary['igstAmount'] += floatval($row['IGSTAmount']) * $multiplier;
        $summary['totalTax'] += floatval($row['TotalTax']) * $multiplier;
    }
    
    // Get customer info if filtered
    $customerInfo = null;
    if ($customerId) {
        $customerQuery = "SELECT CustomerID, CustomerName, GSTNumber, City FROM tblcustomers WHERE CustomerID = ?";
        $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);
    }
    
    $response = [
        'success' => true,
        'summary' => $summary,
        'sales' => $sales,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'customerInfo' => $customerInfo,
        'salesTypeInfo' => $salesType
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
