<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

$admin = current_user();

/* ===============================
   SAFE AUDIT FALLBACK
================================ */
if (!function_exists('audit')) {
    function audit(mysqli $conn, int $actorId, string $action, array $meta = []): void
    {
        $stmt = $conn->prepare("
            INSERT INTO audit_logs (actor_id, action, meta, ip)
            VALUES (?, ?, ?, ?)
        ");
        $json = json_encode($meta, JSON_UNESCAPED_UNICODE);
        $ip   = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

        $stmt->bind_param("isss", $actorId, $action, $json, $ip);
        $stmt->execute();
    }
}

/* ===============================
   POST: CREDIT / DEBIT SAVINGS
================================ */
if (is_post()) {
    csrf_verify();

    $accountId = (int)($_POST['account_id'] ?? 0);
    $amount    = (float)($_POST['amount'] ?? 0);
    $type      = $_POST['type'] ?? ''; // credit | debit

    if ($accountId < 1 || $amount <= 0) {
        flash('err','Invalid amount.');
        redirect('savings.php');
    }

    $conn->begin_transaction();
    try {
        $st = $conn->prepare("SELECT * FROM accounts WHERE id=? FOR UPDATE");
        $st->bind_param("i", $accountId);
        $st->execute();
        $acct = $st->get_result()->fetch_assoc();
        if (!$acct) throw new Exception('Account not found');

        if ($type === 'debit' && (float)$acct['balance'] < $amount) {
            throw new Exception('Insufficient balance');
        }

        /* CREATE TRANSACTION */
        $ref = now_ref('SAV');
        $st = $conn->prepare("
            INSERT INTO ledger_txn (ref,type,status)
            VALUES (?, 'savings', 'posted')
        ");
        $st->bind_param("s", $ref);
        $st->execute();
        $txnId = $conn->insert_id;

        $dir = $type === 'credit' ? 'credit' : 'debit';

        $st = $conn->prepare("
            INSERT INTO ledger_entries (txn_id,account_id,amount,direction,currency)
            VALUES (?,?,?,?,?)
        ");
        $st->bind_param("iidss", $txnId, $accountId, $amount, $dir, $acct['currency']);
        $st->execute();

        /* UPDATE BALANCE */
        $op = $type === 'credit' ? '+' : '-';
        $conn->query("UPDATE accounts SET balance = balance $op $amount WHERE id=$accountId");

        audit($conn, (int)$admin['id'], 'SAVINGS_POST', [
            'account' => $accountId,
            'type'    => $type,
            'amount'  => $amount
        ]);

        $conn->commit();
        flash('msg','Savings entry posted successfully.');
    } catch (Throwable $e) {
        $conn->rollback();
        flash('err', $e->getMessage());
    }

    redirect('savings.php');
}

/* ===============================
   LOAD SAVINGS ACCOUNTS
================================ */
$rows = [];
$res = $conn->query("
    SELECT a.*, u.full_name, u.email
    FROM accounts a
    JOIN users u ON u.id = a.user_id
    WHERE a.account_type = 'savings'
    ORDER BY a.id DESC
");
while ($r = $res->fetch_assoc()) $rows[] = $r;

$title = 'Savings — Admin';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<div class="container-fluid py-4">

  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h3 class="fw-bold mb-0">Savings Accounts</h3>
      <small class="text-muted">Manage credits and debits</small>
    </div>
    <a class="btn btn-outline-secondary btn-sm" href="dashboard.php">
      ← Dashboard
    </a>
  </div>

  <?php if ($m = flash('msg')): ?>
    <div class="alert alert-success"><?= e($m) ?></div>
  <?php endif; ?>

  <?php if ($m = flash('err')): ?>
    <div class="alert alert-danger"><?= e($m) ?></div>
  <?php endif; ?>

  <div class="card ab-card border-0 shadow-sm">
    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Account No</th>
            <th>Customer</th>
            <th>Balance</th>
            <th>Currency</th>
            <th class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>

        <?php foreach ($rows as $r): ?>
          <tr>
            <td class="fw-semibold"><?= e($r['account_no']) ?></td>

            <td>
              <div class="fw-semibold"><?= e($r['full_name']) ?></div>
              <small class="text-muted"><?= e($r['email']) ?></small>
            </td>

            <td class="fw-bold">
              <?= money($r['balance']) ?>
            </td>

            <td>
              <span class="badge bg-secondary"><?= e($r['currency']) ?></span>
            </td>

            <td class="text-end">
              <div class="d-flex justify-content-end gap-2 flex-wrap">

                <form method="post" class="d-flex gap-1">
                  <?= csrf_field() ?>
                  <input type="hidden" name="account_id" value="<?= (int)$r['id'] ?>">
                  <input type="hidden" name="type" value="credit">
                  <input type="number" step="0.01" name="amount"
                         class="form-control form-control-sm"
                         placeholder="Amount"
                         style="width:110px" required>
                  <button class="btn btn-sm btn-success">
                    Credit
                  </button>
                </form>

                <form method="post" class="d-flex gap-1">
                  <?= csrf_field() ?>
                  <input type="hidden" name="account_id" value="<?= (int)$r['id'] ?>">
                  <input type="hidden" name="type" value="debit">
                  <input type="number" step="0.01" name="amount"
                         class="form-control form-control-sm"
                         placeholder="Amount"
                         style="width:110px" required>
                  <button class="btn btn-sm btn-outline-danger">
                    Debit
                  </button>
                </form>

                <a href="customer_transactions.php?id=<?= (int)$r['user_id'] ?>"
                   class="btn btn-sm btn-outline-secondary">
                  View
                </a>

              </div>
            </td>
          </tr>
        <?php endforeach; ?>

        <?php if (!$rows): ?>
          <tr>
            <td colspan="5" class="text-center text-muted py-4">
              No savings accounts found
            </td>
          </tr>
        <?php endif; ?>

        </tbody>
      </table>
    </div>
  </div>

</div>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
