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

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

// Adjust the date condition for each table
$transactionDateCondition = getDateCondition($option, 'transaction_date');
$expenseDateCondition = getDateCondition($option, 'expense_date');

$profitQuery = "SELECT SUM(amount) AS profit FROM transactions WHERE company_id = ? AND {$transactionDateCondition} AND type = 'Credit'";
$lossQuery = "SELECT SUM(amount) AS loss FROM expenses WHERE company_id = ? AND {$expenseDateCondition}";

// Fetch profit
$stmt = $conn->prepare($profitQuery);
if (!$stmt) {
    error_log("Error in prepare statement for profit: " . $conn->error);
    // Handle error appropriately
    exit;
}
$stmt->bind_param("i", $companyId);
$stmt->execute();
$profitResult = $stmt->get_result()->fetch_assoc();
$profit = $profitResult['profit'] ?? 0;

// Fetch loss
$stmt = $conn->prepare($lossQuery);
if (!$stmt) {
    error_log("Error in prepare statement for loss: " . $conn->error);
    // Handle error appropriately
    exit;
}
$stmt->bind_param("i", $companyId);
$stmt->execute();
$lossResult = $stmt->get_result()->fetch_assoc();
$loss = $lossResult['loss'] ?? 0;

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

$stmt->close();
?>
