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

// Get filters from request
$dateRange = $_GET['dateRange'] ?? 'this_month';
$salesType = $_GET['salesType'] ?? '';
$customer = $_GET['customer'] ?? '';
$category = $_GET['category'] ?? '';
$dateFrom = $_GET['dateFrom'] ?? '';
$dateTo = $_GET['dateTo'] ?? '';

// Build date conditions
$dateCondition = '';
switch ($dateRange) {
    case 'today':
        $dateCondition = "DATE(s.SaleDate) = CURDATE()";
        break;
    case 'yesterday':
        $dateCondition = "DATE(s.SaleDate) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
        break;
    case 'this_week':
        $dateCondition = "YEARWEEK(s.SaleDate, 1) = YEARWEEK(CURDATE(), 1)";
        break;
    case 'last_week':
        $dateCondition = "YEARWEEK(s.SaleDate, 1) = YEARWEEK(DATE_SUB(CURDATE(), INTERVAL 1 WEEK), 1)";
        break;
    case 'this_month':
        $dateCondition = "YEAR(s.SaleDate) = YEAR(CURDATE()) AND MONTH(s.SaleDate) = MONTH(CURDATE())";
        break;
    case 'last_month':
        $dateCondition = "YEAR(s.SaleDate) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND MONTH(s.SaleDate) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))";
        break;
    case 'this_year':
        $dateCondition = "YEAR(s.SaleDate) = YEAR(CURDATE())";
        break;
    case 'custom':
        if ($dateFrom && $dateTo) {
            $dateFrom = mysqli_real_escape_string($con, $dateFrom);
            $dateTo = mysqli_real_escape_string($con, $dateTo);
            $dateCondition = "DATE(s.SaleDate) BETWEEN '$dateFrom' AND '$dateTo'";
        } else {
            $dateCondition = "1=1";
        }
        break;
    default:
        $dateCondition = "1=1";
}

// Build WHERE clause
$whereConditions = [$dateCondition];

if (!empty($salesType)) {
    $salesType = mysqli_real_escape_string($con, $salesType);
    $whereConditions[] = "s.SalesType = '$salesType'";
}

if (!empty($customer)) {
    $customer = mysqli_real_escape_string($con, $customer);
    $whereConditions[] = "s.CustomerID = '$customer'";
}

if (!empty($category)) {
    $category = mysqli_real_escape_string($con, $category);
    $whereConditions[] = "i.CategoryID = '$category'";
}

$whereClause = implode(' AND ', $whereConditions);

// Get total sales amount
$totalSalesQuery = "
    SELECT 
        COALESCE(SUM(s.FinalAmount), 0) as totalSales
    FROM tblsales s
    WHERE $whereClause
";

$totalSalesResult = mysqli_query($con, $totalSalesQuery);
$totalSalesData = mysqli_fetch_assoc($totalSalesResult);
$totalSalesAmount = $totalSalesData['totalSales'];

// Get total invoices count
$totalInvoicesQuery = "
    SELECT 
        COUNT(DISTINCT s.ID) as totalInvoices
    FROM tblsales s
    WHERE $whereClause
";

$totalInvoicesResult = mysqli_query($con, $totalInvoicesQuery);
$totalInvoicesData = mysqli_fetch_assoc($totalInvoicesResult);
$totalInvoices = $totalInvoicesData['totalInvoices'];

// Get total items sold
$totalItemsSoldQuery = "
    SELECT 
        COALESCE(SUM(sd.Quantity), 0) as totalItems
    FROM tblsales s
    LEFT JOIN tblsales_details sd ON s.ID = sd.SaleID
    LEFT JOIN tblitems i ON sd.ProductID = i.ID
    WHERE $whereClause
";

$totalItemsSoldResult = mysqli_query($con, $totalItemsSoldQuery);
$totalItemsSoldData = mysqli_fetch_assoc($totalItemsSoldResult);
$totalItemsSold = $totalItemsSoldData['totalItems'];

// Calculate average invoice value
$avgInvoiceValue = $totalInvoices > 0 ? ($totalSalesAmount / $totalInvoices) : 0;

// Prepare response
$response = [
    'success' => true,
    'data' => [
        'totalSalesAmount' => number_format($totalSalesAmount, 2, '.', ''),
        'totalInvoices' => $totalInvoices,
        'totalItemsSold' => $totalItemsSold,
        'avgInvoiceValue' => number_format($avgInvoiceValue, 2, '.', '')
    ]
];

echo json_encode($response);
?>
