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

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
$u = current_user();
$userId = (int)$u['id'];

/* ===============================
   LOAD PRIMARY ACCOUNT
================================ */
$primary = get_primary_account($conn, $userId);
if (!$primary) die('No primary account');

/* ===============================
   LOAD OTHER ACCOUNTS
================================ */
$targets = [];
$st = $conn->prepare("
  SELECT * FROM accounts
  WHERE user_id=? AND id<>?
  ORDER BY account_type ASC
");
$st->bind_param("ii", $userId, $primary['id']);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) $targets[] = $r;

/* ===============================
   HANDLE TRANSFER
================================ */
if (is_post()) {
  $toId   = (int)($_POST['to_account'] ?? 0);
  $amount = (float)($_POST['amount'] ?? 0);
  $note   = trim($_POST['note'] ?? 'Internal transfer');

  if ($amount <= 0) {
    flash('msg','Invalid amount');
    redirect('internal_transfer.php');
  }

  if ($amount > (float)$primary['balance']) {
    flash('msg','Insufficient balance');
    redirect('internal_transfer.php');
  }

  // verify target
  $st = $conn->prepare("SELECT * FROM accounts WHERE id=? AND user_id=?");
  $st->bind_param("ii", $toId, $userId);
  $st->execute();
  $to = $st->get_result()->fetch_assoc();
  if (!$to) {
    flash('msg','Invalid destination account');
    redirect('internal_transfer.php');
  }

  /* TRANSACTION */
  $conn->begin_transaction();

  $ref = now_ref('INT');

  // ledger_txn
  $st = $conn->prepare("
    INSERT INTO ledger_txn (ref,type,status,narration,created_by)
    VALUES (?,?,?,?,?)
  ");
  $type='internal'; $status='posted';
  $st->bind_param("ssssi", $ref, $type, $status, $note, $userId);
  $st->execute();
  $txnId = $conn->insert_id;

  // debit primary
  $st = $conn->prepare("
    INSERT INTO ledger_entries
    (txn_id,account_id,direction,amount,currency)
    VALUES (?,?,?,?,?)
  ");
  $dir='debit'; $cur=$primary['currency'];
  $st->bind_param("iisds", $txnId, $primary['id'], $dir, $amount, $cur);
  $st->execute();

  // credit target
  $dir='credit'; $cur=$to['currency'];
  $st->bind_param("iisds", $txnId, $to['id'], $dir, $amount, $cur);
  $st->execute();

  // update balances
  $conn->query("
    UPDATE accounts
    SET balance = balance - {$amount}
    WHERE id = {$primary['id']}
  ");
  $conn->query("
    UPDATE accounts
    SET balance = balance + {$amount}
    WHERE id = {$to['id']}
  ");

  $conn->commit();

  flash('msg','Transfer completed');
  redirect('accounts.php');
}

$title = 'Internal Transfer';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<main style="margin-left:240px;min-height:100vh">
<div class="container-fluid py-4">

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

<div class="card ab-card p-4" style="max-width:520px">
  <h5 class="fw-bold mb-3">Internal Transfer</h5>

  <div class="mb-2">
    <div class="ab-muted">From (Primary)</div>
    <div class="fw-semibold">
      <?= e($primary['account_type']) ?> • <?= e($primary['account_no']) ?><br>
      Balance: <?= e($primary['currency']) ?> <?= number_format($primary['balance'],2) ?>
    </div>
  </div>

  <form method="post">
    <label class="form-label mt-2">To Account</label>
    <select name="to_account" class="form-select mb-2" required>
      <?php foreach($targets as $t): ?>
        <option value="<?= (int)$t['id'] ?>">
          <?= e($t['account_type']) ?> • <?= e($t['account_no']) ?>
        </option>
      <?php endforeach; ?>
    </select>

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

    <label class="form-label">Note</label>
    <input name="note" class="form-control mb-3">

    <button class="btn ab-btn text-white w-100">
      Transfer Funds
    </button>
  </form>
</div>

</div>
</main>

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