<?php
session_start();
include('includes/dbconn.php');
include('shared_functions.php'); // Include the shared functions

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

$dateCondition = getDateCondition($option, 'due_date');

$sql = "SELECT SUM(total_amount) AS total_paid FROM invoices 
        WHERE company_id = ? AND payment_status in ('Pending', 'Paid') AND {$dateCondition}";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $companyId);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

$totalPaid = $result['total_paid'] ?? 0;

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

$stmt->close();
?>
