<?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';
$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($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 sales by type
$salesByTypeQuery = "
    SELECT 
        s.SalesType as salesType,
        COALESCE(SUM(s.FinalAmount), 0) as totalAmount
    FROM tblsales s
    LEFT JOIN tblsales_details sd ON s.ID = sd.SaleID
    LEFT JOIN tblitems i ON sd.ProductID = i.ID
    WHERE $whereClause
    GROUP BY s.SalesType
    ORDER BY totalAmount DESC
    LIMIT 10
";

$result = mysqli_query($con, $salesByTypeQuery);

$labels = [];
$values = [];

if ($result && mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $labels[] = $row['salesType'];
        $values[] = floatval($row['totalAmount']);
    }
} else {
    // Default data if no results
    $labels = ['No Data'];
    $values = [0];
}

$response = [
    'success' => true,
    'data' => [
        'labels' => $labels,
        'values' => $values
    ]
];

echo json_encode($response);
?>
