<?php
session_start();
include('includes/dbconn.php'); // Make sure the path to dbconn.php is correct

$companyId = $_SESSION['company_id']; // From session
$option = $_GET['option'] ?? 'daily'; // Default to 'daily' if no option is set

// Determine the date range based on the selected option
switch ($option) {
    case 'daily':
        $startDate = new DateTime('today');
        $endDate = new DateTime('tomorrow');
        break;
    case 'weekly':
        $startDate = new DateTime('monday this week');
        $endDate = new DateTime('monday next week');
        break;
    case 'monthly':
        $startDate = new DateTime('first day of this month');
        $endDate = new DateTime('first day of next month');
        break;
    default:
        // Default to daily
        $startDate = new DateTime('today');
        $endDate = new DateTime('tomorrow');
        break;
}

$sql = "SELECT SUM(amount) AS total_sales FROM transactions 
        WHERE company_id = ? 
        AND transaction_date >= ? AND transaction_date < ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iss", $companyId, $startDate->format('Y-m-d'), $endDate->format('Y-m-d'));
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

$totalSales = $result['total_sales'] ?? 0; // Default to 0 if no sales

echo json_encode([
    'total' => number_format((float)$totalSales, 2, '.', ''),
    'period' => $option
]);
