<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require "db.php";

/*
|--------------------------------------------------------------------------
| PETTY CASH POSITION (STAFF ONLY)
|--------------------------------------------------------------------------
| - Shows only petty cash held by staff
| - No staff names
| - No CEO / Bank balances
| - Zero balances hidden
|--------------------------------------------------------------------------
*/

/* ================= FETCH PETTY CASH ================= */
$q = mysqli_query($conn,"
    SELECT
        IFNULL(SUM(
            CASE
                WHEN c.to_account = a.id THEN c.amount
                WHEN c.from_account = a.id THEN -c.amount
                ELSE 0
            END
        ),0) AS balance
    FROM hps_cash_accounts a
    LEFT JOIN hps_cashbook c
        ON c.to_account = a.id
        OR c.from_account = a.id
    WHERE a.account_type = 'STAFF'
    GROUP BY a.account_type
    HAVING balance != 0
");

/* Default values */
$petty_balance = 0;

/* Only one row expected (all staff combined) */
if ($row = mysqli_fetch_assoc($q)) {
    $petty_balance = (float)$row['balance'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Petty Cash Position</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="p-3 bg-light">

<div class="container" style="max-width:600px;">

<h4 class="mb-3">Petty Cash Position</h4>

<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
    <th>Account</th>
    <th class="text-end">Balance</th>
</tr>
</thead>
<tbody>

<tr>
    <td>Petty Cash (Staff)</td>
    <td class="text-end <?= ($petty_balance < 0 ? 'text-danger' : 'text-success') ?>">
        <?= number_format($petty_balance, 2) ?>
    </td>
</tr>

</tbody>

<tfoot class="table-warning">
<tr>
    <th>TOTAL PETTY CASH IN HAND</th>
    <th class="text-end"><?= number_format($petty_balance, 2) ?></th>
</tr>
</tfoot>
</table>

</div>

</body>
</html>
