<?php
require_once "labClass.php";
$con = new labClass();

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Date filters
$startDate = $_GET['start_date'] ?? null;
$endDate   = $_GET['end_date'] ?? null;

$whereMiamala = $whereOther = $whereWithdraw = "";
$stmt = $con->genStatement($whereOther, $whereMiamala, $whereWithdraw, $startDate, $endDate);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// --- Compute Opening Balance ---
$openingBalance = 0;
if ($startDate) {
    $stmt2 = $con->genStatement("", "", "", null, $startDate);
    $rowsBefore = $stmt2->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rowsBefore as $row) {
        if ($row['tdate'] < $startDate) {
            $openingBalance += $row['amount'];
        }
    }
}

// --- Build Statement Grouped by Date ---
$statement = [];
$runningBalance = $openingBalance;

foreach ($rows as $row) {
    $date = $row['tdate'];
    $amt  = $row['amount'];

    if (!isset($statement[$date])) {
        $statement[$date] = [
            'date' => $date,
            'transactions' => []
        ];
    }

    $runningBalance += $amt;
    $row['globalBalance'] = $runningBalance;
    $statement[$date]['transactions'][] = $row;
}

// --- Final Global Balance ---
$netAmount = $runningBalance;
?>

<style>
  .txn-sep td {
    border-top: 1px solid #007bff !important;
    padding: 0 !important;
  }

  .date-sep td {
    border-top: 4px solid #007bff !important;
    padding: 0 !important;
  }

  .custom-blue-border, 
  .custom-blue-border th, 
  .custom-blue-border td {
      border: 1px solid #007bff !important;
  }

  .withdraw {
    color: red !important;
    font-weight: 600;
  }

  .deposit {
    color: green !important;
    font-weight: 600;
  }

  .negative-balance {
    color: red !important;
    font-weight: 600;
  }

  @media print {
    .txn-sep td { border-top: 1px solid #007bff !important; }
    .date-sep td { border-top: 4px solid #007bff !important; }
  }
</style>

<table class="table table-bordered custom-blue-border">
    <thead class="table-light">
        <tr>
            <th>Date</th>
            <th>Description</th>
            <th>Debit</th>
            <th>Credit</th>
            <th>Balance</th>
        </tr>
    </thead>
    <tbody>
        <!-- Opening Balance -->
        <tr class="table-warning">
            <td colspan="4" class="text-end"><strong>Opening Balance (Before <?= htmlspecialchars($startDate ?? 'All Dates') ?>):</strong></td>
            <td><strong><?= number_format($openingBalance, 2) ?></strong></td>
        </tr>

        <?php if (empty($statement)): ?>
            <tr>
                <td colspan="5" class="text-center text-muted">No records found for selected range</td>
            </tr>
        <?php else: ?>
            <?php foreach ($statement as $day): ?>
                <?php foreach ($day['transactions'] as $i => $txn): ?>
                <tr>
                    <?php if ($i === 0): ?>
                        <td rowspan="<?= count($day['transactions']) ?>"><?= htmlspecialchars($day['date']) ?></td>
                    <?php endif; ?>
                    <td><?= htmlspecialchars($txn['description']) ?></td>

                    <!-- Debit (Deposit / Income) -->
                    <td class="deposit">
                        <?= $txn['amount'] > 0 ? number_format($txn['amount'], 2) : '' ?>
                    </td>

                    <!-- Credit (Withdrawal / Expense) -->
                    <td class="withdraw">
                        <?= $txn['amount'] < 0 ? number_format(abs($txn['amount']), 2) : '' ?>
                    </td>

                    <!-- Running Balance -->
                    <td class="<?= $txn['globalBalance'] < 0 ? 'negative-balance' : '' ?>">
                        <?= number_format($txn['globalBalance'], 2) ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <tr class="date-sep"><td colspan="5"></td></tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>

    <tfoot>
        <tr class="table-info">
            <th colspan="4" class="text-end">Global Net Balance Remaining:</th>
            <th class="<?= $netAmount < 0 ? 'negative-balance' : '' ?>">
                <?= number_format($netAmount, 2) ?>
            </th>
        </tr>
    </tfoot>
</table>
