<?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(balance) AS total_unpaid FROM invoices 
        WHERE company_id = ? AND payment_status = 'Unpaid' AND {$dateCondition}";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $companyId);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

$totalUnpaid = $result['total_unpaid'] ?? 0;

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

$stmt->close();
?>
