<?php
include 'includes/config.php';

$date = isset($_GET['date']) ? $_GET['date'] : null;

try {
    // Fetch total sale and sale with tax filtered by date
    if ($date) {
        $stmt = $conn->prepare("SELECT SUM(total_amount) AS total_sale FROM stock_sale WHERE DATE(date_sale) = :date");
        $stmt->execute(['date' => $date]);
    } else {
        $stmt = $conn->query("SELECT SUM(total_amount) AS total_sale FROM stock_sale");
    }
    $totalSale = $stmt->fetchColumn();
    $totalSale = $totalSale !== null ? floatval($totalSale) : 0.0;
    $saleWithTax = $totalSale;

    // Fetch total purchase and purchase with tax filtered by date
    if ($date) {
        $stmt = $conn->prepare("SELECT SUM(quantity * purchase_price) AS total_purchase FROM purchase_lines WHERE DATE(purchase_date) = :date");
        $stmt->execute(['date' => $date]);
    } else {
        $stmt = $conn->query("SELECT SUM(quantity * purchase_price) AS total_purchase FROM purchase_lines");
    }
    $totalPurchase = $stmt->fetchColumn();
    $totalPurchase = $totalPurchase !== null ? floatval($totalPurchase) : 0.0;
    $purchaseWithTax = $totalPurchase;

    // Fetch total deposit amount from cash_deposit to calculate sale due, filtered by date
    if ($date) {
        $stmt = $conn->prepare("SELECT SUM(amount) AS total_deposit FROM cash_deposit WHERE DATE(date_deposit) = :date");
        $stmt->execute(['date' => $date]);
    } else {
        $stmt = $conn->query("SELECT SUM(amount) AS total_deposit FROM cash_deposit");
    }
    $totalDeposit = $stmt->fetchColumn();
    $totalDeposit = $totalDeposit !== null ? floatval($totalDeposit) : 0.0;
    $saleDue = $totalSale - $totalDeposit;

    // Define purchase return and sale return (can be adjusted as needed)
    $purchaseReturn = 0.00;
    $saleReturn = 0.00;
    $purchaseDue = $totalPurchase;

    // Calculate overall differences
    $salePurchaseDiff = $totalSale - $saleReturn - $totalPurchase + $purchaseReturn;
    $dueAmount = $saleDue - $purchaseDue;

    // Format all amounts to include commas and two decimals
    $response = [
        'total_sale' => number_format($totalSale, 2),
        'sale_with_tax' => number_format($saleWithTax, 2),
        'sale_return' => number_format($saleReturn, 2),
        'sale_due' => number_format($saleDue, 2),
        'total_purchase' => number_format($totalPurchase, 2),
        'purchase_with_tax' => number_format($purchaseWithTax, 2),
        'purchase_return' => number_format($purchaseReturn, 2),
        'purchase_due' => number_format($purchaseDue, 2),
        'sale_purchase_diff' => number_format($salePurchaseDiff, 2),
        'due_amount' => number_format($dueAmount, 2),
    ];

    header('Content-Type: application/json');
    echo json_encode($response);

} catch (PDOException $e) {
    error_log("Database query error: " . $e->getMessage());
    echo json_encode(['error' => 'Database query error.']);
}
?>
