<?php
session_start();
include('../../includes/config.php');
include('../../includes/header.php');

// Date filters (you can make these dynamic with a form)
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');

// 1. Total Income (net of VAT) — only paid sales
$total_income = 0;
$sql = "
    SELECT SUM(total_amount - vat_total) AS net_sales
    FROM sales_transactions
    WHERE status = 'completed'
      AND created_at BETWEEN ? AND ?
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $date_from, $date_to);
$stmt->execute();
$result = $stmt->get_result();
if ($result) {
    $row = $result->fetch_assoc();
    $total_income = $row['net_sales'] ?? 0;
} else {
    $total_income = 0;
}
echo "<pre>Total Income Debug: "; print_r($row); echo "</pre>";


// 2. COGS (based on quantity × cost_price)
$cogs = 0;
$sql = "
    SELECT si.quantity, p.cost_price
    FROM sales_items si
    INNER JOIN products p ON si.product_id = p.id
    INNER JOIN sales_transactions st ON si.transaction_id = st.id
    WHERE st.status = 'completed'
      AND st.created_at BETWEEN ? AND ?
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $date_from, $date_to);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $cogs += $row['quantity'] * $row['cost_price'];
}

// 3. Gross Profit
$gross_profit = $total_income - $cogs;

// 4. Operating Expenses
$operating_expenses = 0;
$sql = "
    SELECT SUM(amount) AS total_expense
    FROM expenses
    WHERE status = 'approved'
      AND deleted_at IS NULL
      AND expense_date BETWEEN ? AND ?
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $date_from, $date_to);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$operating_expenses = $result['total_expense'] ?? 0;

// 5. Net Profit
$net_profit = $gross_profit - $operating_expenses;
?>

<!-- Income Statement Display -->
<div class="container glassmorphic mt-5 p-4">
    <h2 class="text-center mb-4">Income Statement</h2>
    <p class="text-center text-white">
        Period: <?= htmlspecialchars($date_from) ?> to <?= htmlspecialchars($date_to) ?>
    </p>

    <table class="table table-bordered table-striped text-white">
        <tr>
            <th>Total Income (Net of VAT)</th>
            <td>MWK <?= number_format($total_income, 2) ?></td>
        </tr>
        <tr>
            <th>Cost of Goods Sold (COGS)</th>
            <td>MWK <?= number_format($cogs, 2) ?></td>
        </tr>
        <tr>
            <th>Gross Profit</th>
            <td>MWK <?= number_format($gross_profit, 2) ?></td>
        </tr>
        <tr>
            <th>Operating Expenses</th>
            <td>MWK <?= number_format($operating_expenses, 2) ?></td>
        </tr>
        <tr class="table-success">
            <th>Net Profit</th>
            <td><strong>MWK <?= number_format($net_profit, 2) ?></strong></td>
        </tr>
    </table>
</div>

<?php include('../../includes/footer.php'); ?>
