<?php
session_start();
include('includes/dbconn.php'); // Ensure this is the path to your DB connection script

$companyId = $_SESSION['company_id']; // From session
$option = $_GET['option'] ?? 'daily';

// Helper function to get the date condition based on the selected option
function getDateCondition($option) {
    switch ($option) {
        case 'daily':
            return "expense_date = CURDATE()";
        case 'weekly':
            // Assuming the week starts on Monday
            return "expense_date >= DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)";
        case 'monthly':
            return "MONTH(expense_date) = MONTH(CURDATE()) AND YEAR(expense_date) = YEAR(CURDATE())";
        default:
            return "expense_date = CURDATE()";
    }
}

$dateCondition = getDateCondition($option);

// SQL to fetch the total expenses for the company
$sql = "SELECT SUM(amount) AS total_expenses FROM expenses 
        WHERE company_id = ? AND {$dateCondition}";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $companyId);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

$totalExpenses = $result['total_expenses'] ?? 0;

header('Content-Type: application/json');
echo json_encode([
    'total' => number_format((float)$totalExpenses, 2, '.', ''),
    'period' => $option
]);

$stmt->close();
?>
