<?php

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

require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/banking.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/helpers/audit.php';
require_once __DIR__ . '/../../app/middleware/auth.php';
require_once __DIR__ . '/../services/SystemAccounts.php';

session_boot();
require_login();

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

$admin   = current_user();
$adminId = (int)($admin['id'] ?? 0);

/* ===============================
   SYSTEM ACCOUNTS SERVICE
================================ */
$sysAccounts = new SystemAccounts($conn);

/* ===============================
   PROCESS ACTION
================================ */
if (is_post()) {
  csrf_verify();

  $wireId = (int)($_POST['wire_id'] ?? 0);
  $action = trim($_POST['action'] ?? '');

  $conn->begin_transaction();

  try {

    if ($wireId <= 0) throw new Exception('Invalid wire id');
    if (!in_array($action, ['approve','reject'], true)) {
      throw new Exception('Invalid action');
    }

    /* LOCK WIRE + GET CUSTOMER ACTIVE ACCOUNT */
    $wst = $conn->prepare("
      SELECT
        wt.*,
        lt.id  AS txn_id,
        lt.ref AS ref,
        a.id   AS acct_id,
        a.currency AS acct_currency
      FROM wire_transfers wt
      JOIN ledger_txn lt ON lt.id = wt.txn_id
      JOIN accounts a
        ON a.user_id = wt.user_id
       AND a.owner_type = 'user'
       AND a.account_type IN ('savings','current')
       AND a.status = 'active'
      WHERE wt.id = ?
      LIMIT 1
      FOR UPDATE
    ");
    $wst->bind_param("i", $wireId);
    $wst->execute();
    $wire = $wst->get_result()->fetch_assoc();

    if (!$wire) throw new Exception('Wire not found');
    if (($wire['status'] ?? '') !== 'pending_review') {
      throw new Exception('Wire is not pending review');
    }

    $currency = strtoupper(trim($wire['currency'] ?? $wire['acct_currency'] ?? 'GHS'));

    /* ===============================
       REJECT
    ================================ */
    if ($action === 'reject') {

      $st = $conn->prepare("
        UPDATE wire_transfers
        SET status='rejected',
            reviewed_by=?,
            reviewed_at=UTC_TIMESTAMP()
        WHERE id=?
      ");
      $st->bind_param("ii", $adminId, $wireId);
      $st->execute();

      $st = $conn->prepare("UPDATE ledger_txn SET status='rejected' WHERE id=?");
      $st->bind_param("i", $wire['txn_id']);
      $st->execute();

      $msg = "Your wire transfer {$wire['ref']} was rejected.";
      $n = $conn->prepare("
        INSERT INTO notifications (user_id, title, message)
        VALUES (?, 'Wire transfer rejected', ?)
      ");
      $n->bind_param("is", $wire['user_id'], $msg);
      $n->execute();

    }
    /* ===============================
       APPROVE
    ================================ */
    else {

      $amount = (float)$wire['amount'];
      $fee    = (float)($wire['fee'] ?? 0);
      $total  = $amount + $fee;

      if ($total <= 0) throw new Exception('Invalid amount');

      /* ✅ SYSTEM CONTROL ACCOUNT (SAFE & IDEMPOTENT) */
      $controlAccount = $sysAccounts->ensureControl($currency);
      $controlId      = (int)$controlAccount['id'];

      /* CHECK CUSTOMER BALANCE */
      $bal = account_balance($conn, (int)$wire['acct_id']);
      if ($bal < $total) throw new Exception('Insufficient funds');

      $newBal = $bal - $total;

      /* UPDATE STATUSES */
      $st = $conn->prepare("
        UPDATE wire_transfers
        SET status='processed',
            reviewed_by=?,
            reviewed_at=UTC_TIMESTAMP()
        WHERE id=?
      ");
      $st->bind_param("ii", $adminId, $wireId);
      $st->execute();

      $st = $conn->prepare("UPDATE ledger_txn SET status='posted' WHERE id=?");
      $st->bind_param("i", $wire['txn_id']);
      $st->execute();

      /* LEDGER: CUSTOMER DEBIT */
      $st = $conn->prepare("
        INSERT INTO ledger_entries
          (txn_id, account_id, direction, amount, currency, balance_after)
        VALUES
          (?, ?, 'debit', ?, ?, ?)
      ");
      $st->bind_param(
        "iidss",
        $wire['txn_id'],
        $wire['acct_id'],
        $total,
        $currency,
        $newBal
      );
      $st->execute();

      /* LEDGER: CONTROL CREDIT */
      $st = $conn->prepare("
        INSERT INTO ledger_entries
          (txn_id, account_id, direction, amount, currency)
        VALUES
          (?, ?, 'credit', ?, ?)
      ");
      $st->bind_param(
        "iids",
        $wire['txn_id'],
        $controlId,
        $total,
        $currency
      );
      $st->execute();

      $msg = "Your wire transfer {$wire['ref']} was processed successfully.";
      $n = $conn->prepare("
        INSERT INTO notifications (user_id, title, message)
        VALUES (?, 'Wire transfer processed', ?)
      ");
      $n->bind_param("is", $wire['user_id'], $msg);
      $n->execute();
    }

    /* AUDIT */
    $meta = json_encode(['wire_id'=>$wireId,'action'=>$action], JSON_UNESCAPED_SLASHES);
    $ip   = client_ip();

    $a = $conn->prepare("
      INSERT INTO audit_logs (actor_id, action, meta, ip)
      VALUES (?, 'WIRE_REVIEW', ?, ?)
    ");
    $a->bind_param("iss", $adminId, $meta, $ip);
    $a->execute();

    $conn->commit();
    flash('msg','Saved');

  } catch (Throwable $e) {
    $conn->rollback();
    flash('err', $e->getMessage());
  }

  redirect('wire_approvals.php');
}

/* ===============================
   LOAD PENDING
================================ */
$pending = [];
$res = $conn->query("
  SELECT
    wt.*,
    lt.ref,
    u.full_name,
    u.email
  FROM wire_transfers wt
  JOIN ledger_txn lt ON lt.id=wt.txn_id
  JOIN users u ON u.id=wt.user_id
  WHERE wt.status='pending_review'
  ORDER BY wt.id DESC
");
if ($res) {
  while ($r = $res->fetch_assoc()) $pending[] = $r;
}

$title = 'Wire Approvals — Eliteguanrantytrust Bank';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>


<div class="container py-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h3 class="fw-bold mb-0">Wire approvals</h3>
      <div class="ab-muted">Approve/reject customer wire transfers (OTP verified).</div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="dashboard.php">Back</a>
    </div>
  </div>

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

  <div class="card ab-card p-3">
    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead>
          <tr>
            <th>Ref</th>
            <th>Customer</th>
            <th>Amount</th>
            <th>Status</th>
            <th>Created</th>
            <th class="text-end">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($pending as $w): ?>
          <?php
            $cur = strtoupper(trim($w['currency'] ?? 'GHS'));
            $amountTotal = (float)$w['amount'] + (float)($w['fee'] ?? 0);
          ?>
          <tr>
            <td class="fw-bold"><?= e($w['ref']) ?></td>
            <td>
              <div class="fw-semibold"><?= e($w['full_name']) ?></div>
              <div class="text-muted small"><?= e($w['email']) ?></div>
            </td>
            <td><?= e($cur) ?> <?= money($amountTotal) ?></td>
            <td><span class="badge bg-warning text-dark">Pending</span></td>
            <td class="text-muted small"><?= e($w['created_at']) ?></td>
            <td class="text-end">
              <form method="post" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="wire_id" value="<?= (int)$w['id'] ?>">
                <input type="hidden" name="action" value="approve">
                <button class="btn btn-sm btn-success" onclick="return confirm('Approve this wire?')">
                  Approve
                </button>
              </form>

              <form method="post" class="d-inline" onsubmit="return confirm('Reject this wire?')">
                <?= csrf_field() ?>
                <input type="hidden" name="wire_id" value="<?= (int)$w['id'] ?>">
                <input type="hidden" name="action" value="reject">
                <button class="btn btn-sm btn-outline-danger">
                  Reject
                </button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>

          <?php if (!$pending): ?>
            <tr>
              <td colspan="6" class="text-center text-muted py-4">
                No pending wires.
              </td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Quick info card (no behavior change) -->
  <div class="card ab-card p-3 mt-3">
    <div class="fw-bold mb-1">Multi-currency control accounts</div>
    <div class="ab-muted">
      On approve, the system automatically finds/creates a control account using
      <code>BANK_CONTROL_&lt;CURRENCY&gt;</code> (e.g. <code>BANK_CONTROL_GHS</code>, <code>BANK_CONTROL_USD</code>)
      and credits it with the total amount (amount + fee).
    </div>
  </div>

</div>

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