<?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':
        $days = 1;
        $dateCondition = "DATE(s.SaleDate) >= DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
        break;
    case 'this_week':
        $days = 7;
        $dateCondition = "DATE(s.SaleDate) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
        break;
    case 'this_month':
        $days = 30;
        $dateCondition = "DATE(s.SaleDate) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
        break;
    case 'this_year':
        $days = 365;
        $dateCondition = "DATE(s.SaleDate) >= DATE_SUB(CURDATE(), INTERVAL 365 DAY)";
        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'";
            $days = (strtotime($dateTo) - strtotime($dateFrom)) / (60 * 60 * 24) + 1;
        } else {
            $days = 30;
            $dateCondition = "DATE(s.SaleDate) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
        }
        break;
    default:
        $days = 30;
        $dateCondition = "DATE(s.SaleDate) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
}

// 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 sales trend data grouped by date
$salesTrendQuery = "
    SELECT 
        DATE(s.SaleDate) as saleDate,
        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 DATE(s.SaleDate)
    ORDER BY DATE(s.SaleDate) ASC
    LIMIT 30
";

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

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

if ($result && mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $labels[] = date('M d', strtotime($row['saleDate']));
        $values[] = floatval($row['totalAmount']);
    }
} else {
    // If no data, create empty labels for last 7 days
    for ($i = 6; $i >= 0; $i--) {
        $date = date('M d', strtotime("-$i days"));
        $labels[] = $date;
        $values[] = 0;
    }
}

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

echo json_encode($response);
?>
