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

require "db.php";

/*
|--------------------------------------------------------------------------
| PETTY CASH – BANK MOVEMENT (STAFF VIEW)
|--------------------------------------------------------------------------
| - No bank names
| - No staff names
| - Only affects petty cash balance
|--------------------------------------------------------------------------
*/

$msg = "";

/* ================= SUBMIT TRANSACTION ================= */
if (isset($_POST['submit'])) {

    $action  = $_POST['action']; // DEPOSIT | WITHDRAW
    $amount  = (float)$_POST['amount'];
    $remarks = trim($_POST['remarks']);

    if ($amount <= 0) {
        $msg = "Invalid amount";
    } else {

        if ($remarks === '') {
            $remarks = ($action === 'DEPOSIT')
                ? 'PETTY CASH DEPOSITED TO BANK'
                : 'PETTY CASH WITHDRAWN FROM BANK';
        }

        /* Get petty cash account (STAFF) */
        $staffAcc = mysqli_fetch_assoc(mysqli_query($conn,"
            SELECT id
            FROM hps_cash_accounts
            WHERE account_type = 'STAFF'
            ORDER BY id
            LIMIT 1
        "));

        if (!$staffAcc) {
            $msg = "Petty cash account not configured";
        } else {

            $staff_id = (int)$staffAcc['id'];

            if ($action === 'DEPOSIT') {
                // Petty cash → Bank (OUT)
                $from = $staff_id;
                $to   = NULL;
                $ref  = 'PETTY_BANK_DEPOSIT';
            } else {
                // Bank → Petty cash (IN)
                $from = NULL;
                $to   = $staff_id;
                $ref  = 'PETTY_BANK_WITHDRAW';
            }

            mysqli_query($conn,"
                INSERT INTO hps_cashbook
                (trans_date, description, from_account, to_account, amount, ref_type)
                VALUES
                (
                    CURDATE(),
                    '".mysqli_real_escape_string($conn,$remarks)."',
                    ".($from === NULL ? "NULL" : $from).",
                    ".($to === NULL ? "NULL" : $to).",
                    $amount,
                    '$ref'
                )
            ");

            $msg = "Bank transaction recorded";
        }
    }
}

/* ================= TODAY BANK TRANSACTIONS ================= */
$today = date('Y-m-d');

$history = mysqli_query($conn,"
    SELECT
        trans_date,
        description,
        amount,
        ref_type
    FROM hps_cashbook
    WHERE ref_type IN ('PETTY_BANK_DEPOSIT','PETTY_BANK_WITHDRAW')
      AND trans_date = '$today'
    ORDER BY id DESC
");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Petty Cash – Bank Transactions</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 – Bank Transactions</h4>

<?php if ($msg): ?>
<div class="alert alert-info"><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>

<form method="post">

<div class="mb-2">
    <label>Transaction Type</label>
    <select name="action" class="form-control" required>
        <option value="DEPOSIT">Deposit to Bank</option>
        <option value="WITHDRAW">Withdraw from Bank</option>
    </select>
</div>

<div class="mb-2">
    <label>Amount</label>
    <input type="number"
           name="amount"
           step="0.01"
           class="form-control"
           required>
</div>

<div class="mb-2">
    <label>Remarks</label>
    <input type="text"
           name="remarks"
           class="form-control"
           placeholder="optional">
</div>

<button name="submit" class="btn btn-success w-100">
    Save Transaction
</button>

</form>

<hr>

<h6>Today’s Bank Activity</h6>

<table class="table table-sm table-bordered">
<thead class="table-dark">
<tr>
    <th>Date</th>
    <th>Description</th>
    <th class="text-end">In</th>
    <th class="text-end">Out</th>
</tr>
</thead>
<tbody>

<?php if (mysqli_num_rows($history) == 0): ?>
<tr>
    <td colspan="4" class="text-center">No transactions today</td>
</tr>
<?php endif; ?>

<?php while($h = mysqli_fetch_assoc($history)): ?>
<tr>
    <td><?= $h['trans_date'] ?></td>
    <td><?= htmlspecialchars($h['description']) ?></td>
    <td class="text-end">
        <?= ($h['ref_type']=='PETTY_BANK_WITHDRAW') ? number_format($h['amount'],2) : '' ?>
    </td>
    <td class="text-end">
        <?= ($h['ref_type']=='PETTY_BANK_DEPOSIT') ? number_format($h['amount'],2) : '' ?>
    </td>
</tr>
<?php endwhile; ?>

</tbody>
</table>

</div>

</body>
</html>
