<?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();
}

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

try {
    // Build the main query to get location-wise sales
    $query = "
        SELECT 
            COALESCE(c.City, 'Unknown Location') as Location,
            COUNT(DISTINCT c.ID) as TotalCustomers,
            COUNT(DISTINCT s.ID) as TotalBills,
            COALESCE(SUM(sd.Quantity), 0) as TotalQuantity,
            COALESCE(SUM(sd.Amount), 0) as TotalAmount,
            COALESCE(SUM(sd.DiscountAmount), 0) as TotalDiscount,
            COALESCE(SUM(sd.Amount - sd.DiscountAmount), 0) as TotalSales,
            COALESCE(SUM((sd.Amount - sd.DiscountAmount) - (sd.Quantity * COALESCE(i.PurchasePrice, 0))), 0) as TotalProfit
        FROM tblsales s
        INNER JOIN tblcustomers c ON s.CustomerID = c.ID
        INNER JOIN tblsales_details sd ON s.ID = sd.SaleID
        LEFT JOIN tblitems i ON sd.ProductCode = i.ItemCode
        WHERE s.SaleDate BETWEEN ? AND ?
    ";
    
    $params = [$startDate, $endDate];
    $types = 'ss';
    
    // Add location filter
    if (!empty($location)) {
        $query .= " AND c.City = ?";
        $params[] = $location;
        $types .= 's';
    }
    
    // Add customer filter
    if (!empty($customerId)) {
        $query .= " AND c.CustomerID = ?";
        $params[] = $customerId;
        $types .= 's';
    }
    
    // Add sales type filter
    if (!empty($salesType)) {
        $query .= " AND s.SalesType = ?";
        $params[] = $salesType;
        $types .= 's';
    }
    
    $query .= " GROUP BY c.City ORDER BY TotalSales DESC";
    
    $stmt = mysqli_prepare($con, $query);
    if (!$stmt) {
        throw new Exception('Query preparation failed: ' . mysqli_error($con));
    }
    
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    $locations = [];
    $summary = [
        'totalLocations' => 0,
        'totalCustomers' => 0,
        'totalBills' => 0,
        'totalQuantity' => 0,
        'totalAmount' => 0,
        'totalDiscount' => 0,
        'totalSales' => 0,
        'totalProfit' => 0,
        'avgProfitMargin' => 0
    ];
    
    while ($row = mysqli_fetch_assoc($result)) {
        $locations[] = $row;
        $summary['totalCustomers'] += (int)$row['TotalCustomers'];
        $summary['totalBills'] += (int)$row['TotalBills'];
        $summary['totalQuantity'] += (float)$row['TotalQuantity'];
        $summary['totalAmount'] += (float)$row['TotalAmount'];
        $summary['totalDiscount'] += (float)$row['TotalDiscount'];
        $summary['totalSales'] += (float)$row['TotalSales'];
        $summary['totalProfit'] += (float)$row['TotalProfit'];
    }
    
    $summary['totalLocations'] = count($locations);
    
    // Calculate average profit margin
    if ($summary['totalSales'] > 0) {
        $summary['avgProfitMargin'] = ($summary['totalProfit'] / $summary['totalSales']) * 100;
    }
    
    // Get location info if filtered
    $locationInfo = null;
    if (!empty($location)) {
        $locationInfo = $location;
    }
    
    // Get customer info if filtered
    $customerInfo = null;
    if (!empty($customerId)) {
        $custQuery = "SELECT CustomerName, City FROM tblcustomers WHERE CustomerID = ?";
        $custStmt = mysqli_prepare($con, $custQuery);
        mysqli_stmt_bind_param($custStmt, 's', $customerId);
        mysqli_stmt_execute($custStmt);
        $custResult = mysqli_stmt_get_result($custStmt);
        if ($custRow = mysqli_fetch_assoc($custResult)) {
            $customerInfo = $custRow;
        }
    }
    
    // Get sales type info if filtered
    $salesTypeInfo = null;
    if (!empty($salesType)) {
        $salesTypeInfo = $salesType;
    }
    
    echo json_encode([
        'success' => true,
        'summary' => $summary,
        'locations' => $locations,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'locationInfo' => $locationInfo,
        'customerInfo' => $customerInfo,
        'salesTypeInfo' => $salesTypeInfo
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching data: ' . $e->getMessage()
    ]);
}
?>
