<?php
/**
 * pledge_close.php (root page)
 * Upload: /home/jewellersbd/public_html/erp.jewellersbd.com/pledge_close.php
 * Features: Discount + Multi Account payment
 * UI Updated: Dark Navy + Gold ERP Style
 * Language Updated: সুদ -> লকার ভাড়া
 */

require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/db.php';

if (session_status() === PHP_SESSION_NONE) session_start();

if (empty($_SESSION['user_id'])) {
    header('Location: ui/login.html');
    exit;
}

$pledge_id = (int)($_GET['pledge_id'] ?? 0);
if ($pledge_id <= 0) {
    die('<p style="padding:20px;color:red">pledge_id দেওয়া হয়নি।</p>');
}

$s = $pdo->prepare("
    SELECT 
        p.*, 
        pa.name AS party_name, 
        pa.phone AS party_phone 
    FROM pawn_pledges p 
    LEFT JOIN parties pa ON pa.id = p.party_id 
    WHERE p.id = ? 
    LIMIT 1
");
$s->execute([$pledge_id]);
$pledge = $s->fetch(PDO::FETCH_ASSOC);

if (!$pledge) {
    die('<p style="padding:20px;color:red">বন্ধক পাওয়া যায়নি।</p>');
}

$accounts = $pdo->query("
    SELECT 
        id, 
        account_name, 
        account_name_bn, 
        current_balance 
    FROM cash_accounts 
    WHERE is_active = 1 
      AND deleted_at IS NULL 
    ORDER BY sort_order, id
")->fetchAll(PDO::FETCH_ASSOC);

$ph = $pdo->prepare("
    SELECT 
        SUM(interest_paid) ti, 
        SUM(principal_paid) tp 
    FROM pawn_payments 
    WHERE pledge_id = ?
");
$ph->execute([$pledge_id]);
$totals = $ph->fetch(PDO::FETCH_ASSOC);

$total_interest_paid  = (float)($totals['ti'] ?? 0);
$total_principal_paid = (float)($totals['tp'] ?? 0);

$outstanding   = (float)$pledge['outstanding_principal'];
$interest_rate = (float)$pledge['interest_rate'];

$pledge_date   = new DateTime($pledge['pledge_date']);
$today         = new DateTime(date('Y-m-d'));
$days          = (int)$pledge_date->diff($today)->days;
$calc_interest = round($outstanding * ($interest_rate / 100) * ($days / 30), 2);

function toVori(float $g): string {
    $V = 11.664;
    $v = floor($g / $V);
    $r = $g - ($v * $V);
    $a = floor($r / ($V / 16));
    $r2 = $r - ($a * ($V / 16));
    $ro = floor($r2 / ($V / 96));

    $p = [];
    if ($v > 0) $p[] = $v . ' ভরি';
    if ($a > 0) $p[] = $a . ' আনা';
    if ($ro > 0) $p[] = $ro . ' রতি';

    return $p ? implode(' ', $p) : '০';
}

$base_url = '//' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>বন্ধক বন্ধ — <?= htmlspecialchars($pledge['pledge_code']) ?></title>

<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+Bengali:wght@400;600;700&display=swap" rel="stylesheet">

<style>
:root {
  --bg:#07111f;
  --bg2:#0d1b2e;
  --top:#111f35;
  --card:#111f35;
  --card2:#0a1525;
  --field:#081322;
  --border:#223858;
  --border2:#2d4a73;
  --gold:#f2c230;
  --gold2:#d4a843;
  --gold-soft:rgba(242,194,48,.16);
  --green:#22c55e;
  --green-soft:rgba(34,197,94,.16);
  --red:#ef4444;
  --red-soft:rgba(239,68,68,.16);
  --blue:#3b82f6;
  --blue-soft:rgba(59,130,246,.16);
  --purple:#a78bfa;
  --purple-soft:rgba(167,139,250,.16);
  --orange:#fb923c;
  --orange-soft:rgba(251,146,60,.16);
  --text:#eef6ff;
  --muted:#8ea4c0;
  --soft:#b8c7da;
}

* {
  box-sizing:border-box;
  margin:0;
  padding:0;
}

body {
  font-family:'Noto Serif Bengali','Segoe UI',system-ui,sans-serif;
  background:
    radial-gradient(circle at 18% 0%, rgba(242,194,48,.10), transparent 30%),
    radial-gradient(circle at 85% 18%, rgba(59,130,246,.14), transparent 28%),
    var(--bg);
  color:var(--text);
  font-size:14px;
  min-height:100vh;
  padding-bottom:45px;
}

.topbar {
  background:linear-gradient(135deg,#101d31,#162944);
  padding:0 14px;
  height:58px;
  display:flex;
  align-items:center;
  gap:10px;
  position:sticky;
  top:0;
  z-index:100;
  border-bottom:2px solid var(--gold);
  box-shadow:0 8px 24px rgba(0,0,0,.35);
}

.topbar h1 {
  font-size:17px;
  font-weight:700;
  color:#fff;
  flex:1;
}

.topbar a {
  color:var(--gold);
  text-decoration:none;
  font-size:12px;
  font-weight:700;
  padding:8px 11px;
  border:1px solid rgba(242,194,48,.45);
  border-radius:10px;
  background:rgba(242,194,48,.06);
}

.container {
  max-width:720px;
  margin:0 auto;
  padding:14px 12px 40px;
}

.card {
  background:linear-gradient(180deg,rgba(17,31,53,.98),rgba(10,21,37,.98));
  border-radius:18px;
  padding:16px;
  margin-bottom:14px;
  border:1px solid var(--border);
  box-shadow:0 10px 30px rgba(0,0,0,.25);
}

.card-title {
  font-size:15px;
  font-weight:700;
  color:var(--gold);
  padding-bottom:12px;
  margin-bottom:14px;
  border-bottom:1px solid var(--border);
  display:flex;
  align-items:center;
  gap:8px;
}

.pills {
  display:grid;
  grid-template-columns:repeat(2,1fr);
  gap:10px;
  margin-bottom:14px;
}

.pill {
  background:linear-gradient(180deg,#111f35,#0a1525);
  border:1px solid var(--border);
  border-radius:16px;
  padding:13px 10px;
  text-align:center;
  box-shadow:0 8px 22px rgba(0,0,0,.20);
}

.pl {
  font-size:12px;
  color:var(--muted);
  font-weight:700;
  margin-bottom:4px;
}

.pv {
  font-size:21px;
  font-weight:900;
  margin-top:2px;
}

.pv-blue { color:#60a5fa; }
.pv-red { color:#fb7185; }
.pv-gold { color:var(--gold); }
.pv-purple { color:var(--purple); }

.ig {
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:10px;
}

.ig > div {
  background:var(--card2);
  border:1px solid var(--border);
  border-radius:12px;
  padding:11px;
}

.ig label {
  font-size:12px;
  color:var(--muted);
  display:block;
  margin-bottom:5px;
}

.ig .v {
  font-size:15px;
  font-weight:700;
  color:var(--text);
}

.warn-box {
  background:linear-gradient(135deg,rgba(251,146,60,.18),rgba(251,146,60,.07));
  border:1px solid rgba(251,146,60,.45);
  border-left:5px solid var(--orange);
  border-radius:18px;
  padding:15px;
  margin-bottom:14px;
}

.warn-box .wt {
  font-size:15px;
  font-weight:800;
  color:#fed7aa;
  margin-bottom:8px;
}

.warn-box ul {
  padding-left:18px;
  font-size:13px;
  color:#ffd9b2;
  line-height:1.8;
}

.fg {
  margin-bottom:13px;
}

.fg label {
  display:block;
  font-size:13px;
  font-weight:700;
  color:var(--soft);
  margin-bottom:7px;
}

.fg input,
.fg select {
  width:100%;
  padding:13px 14px;
  border:1.5px solid var(--border2);
  border-radius:13px;
  font-size:16px;
  color:var(--text);
  background:var(--field);
  outline:none;
  transition:.15s;
}

.fg input::placeholder {
  color:#58708f;
}

.fg input:focus,
.fg select:focus {
  border-color:var(--gold);
  box-shadow:0 0 0 3px rgba(242,194,48,.12);
}

.fg .hint {
  font-size:12px;
  color:var(--muted);
  margin-top:5px;
}

.fr {
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:12px;
}

.disc-box {
  background:linear-gradient(135deg,rgba(167,139,250,.18),rgba(167,139,250,.07));
  border:1px solid rgba(167,139,250,.42);
  border-left:5px solid var(--purple);
  border-radius:18px;
  padding:15px;
  margin-bottom:14px;
}

.disc-title {
  font-size:15px;
  font-weight:800;
  color:#ddd6fe;
  margin-bottom:12px;
}

.disc-tabs {
  display:flex;
  gap:8px;
  margin-bottom:12px;
}

.disc-tab {
  flex:1;
  padding:10px;
  border-radius:12px;
  border:1.5px solid var(--border2);
  background:var(--field);
  color:var(--muted);
  font-size:13px;
  font-weight:800;
  cursor:pointer;
  text-align:center;
}

.disc-tab.on {
  border-color:var(--purple);
  background:rgba(167,139,250,.16);
  color:#ddd6fe;
}

.summary-box {
  border-radius:18px;
  padding:16px;
  margin-bottom:14px;
  background:linear-gradient(135deg,rgba(242,194,48,.18),rgba(242,194,48,.07));
  border:1px solid rgba(242,194,48,.45);
}

.sb-row {
  display:flex;
  justify-content:space-between;
  padding:8px 0;
  font-size:14px;
  border-bottom:1px solid rgba(255,255,255,.08);
}

.sb-row:last-child {
  border-bottom:none;
}

.sb-row.total {
  font-size:18px;
  font-weight:900;
  padding-top:12px;
}

.sb-lbl {
  color:var(--soft);
}

.acc-box {
  background:linear-gradient(135deg,rgba(59,130,246,.18),rgba(59,130,246,.07));
  border:1px solid rgba(59,130,246,.42);
  border-left:5px solid var(--blue);
  border-radius:18px;
  padding:15px;
  margin-bottom:14px;
}

.acc-title {
  font-size:14px;
  font-weight:800;
  color:#bfdbfe;
  margin-bottom:12px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:8px;
}

.acc-title button {
  background:rgba(59,130,246,.12);
  border:1px solid rgba(59,130,246,.40);
  color:#93c5fd;
  border-radius:10px;
  padding:7px 10px;
  font-size:12px;
  font-weight:800;
  cursor:pointer;
}

.acc-row {
  display:grid;
  grid-template-columns:1fr 1fr auto;
  gap:9px;
  margin-bottom:10px;
  align-items:end;
}

.acc-row:last-child {
  margin-bottom:0;
}

.btn-del-acc {
  width:38px;
  height:46px;
  background:rgba(239,68,68,.16);
  border:1px solid rgba(239,68,68,.45);
  color:#fca5a5;
  border-radius:12px;
  cursor:pointer;
  font-size:15px;
  display:flex;
  align-items:center;
  justify-content:center;
  flex-shrink:0;
}

.acc-check {
  font-size:13px;
  color:#93c5fd;
  margin-top:8px;
  font-weight:700;
}

.final-warning {
  background:rgba(239,68,68,.16);
  border:1.5px solid rgba(239,68,68,.55);
  border-left:5px solid var(--red);
  border-radius:18px;
  padding:15px;
  margin-bottom:14px;
  text-align:center;
}

.final-warning .big {
  font-size:17px;
  font-weight:900;
  color:#fecaca;
}

.final-warning .small {
  font-size:13px;
  color:#fca5a5;
  margin-top:5px;
  line-height:1.5;
}

.btn-close {
  width:100%;
  padding:15px;
  background:linear-gradient(135deg,#dc2626,#ef4444);
  color:#fff;
  border:none;
  border-radius:14px;
  font-size:17px;
  font-weight:900;
  cursor:pointer;
  box-shadow:0 8px 22px rgba(239,68,68,.22);
}

.btn-close:disabled {
  background:#64748b;
  cursor:not-allowed;
  box-shadow:none;
}

.btn-back {
  width:100%;
  padding:14px;
  background:linear-gradient(135deg,#101d31,#162944);
  color:#fff;
  border:none;
  border-radius:14px;
  font-size:15px;
  font-weight:800;
  cursor:pointer;
  margin-top:10px;
  border-bottom:3px solid var(--gold);
}

.alert {
  padding:12px 14px;
  border-radius:12px;
  margin-bottom:12px;
  font-size:14px;
  font-weight:700;
  display:none;
}

.alert-success {
  background:rgba(34,197,94,.16);
  color:#86efac;
  border:1px solid rgba(34,197,94,.35);
}

.alert-error {
  background:rgba(239,68,68,.16);
  color:#fca5a5;
  border:1px solid rgba(239,68,68,.35);
}

.closed-banner {
  background:rgba(239,68,68,.16);
  border:1px solid rgba(239,68,68,.38);
  border-left:5px solid var(--red);
  border-radius:18px;
  padding:18px;
  text-align:center;
  color:#fecaca;
  font-weight:800;
  font-size:15px;
  margin-bottom:14px;
}

@media(max-width:520px) {
  .container {
    padding:12px 10px 36px;
  }

  .topbar h1 {
    font-size:15px;
  }

  .topbar a {
    font-size:12px;
    padding:7px 9px;
  }

  .pills {
    grid-template-columns:repeat(2,1fr);
  }

  .pv {
    font-size:20px;
  }

  .ig {
    grid-template-columns:1fr 1fr;
    gap:9px;
  }

  .ig > div {
    padding:10px;
  }

  .ig .v {
    font-size:14px;
  }

  .fr {
    grid-template-columns:1fr 1fr;
    gap:9px;
  }

  .acc-row {
    grid-template-columns:1fr 1fr auto;
    gap:7px;
  }

  .fg input,
  .fg select {
    font-size:15px;
    padding:12px;
  }
}

@media(max-width:380px) {
  .fr {
    grid-template-columns:1fr;
  }

  .acc-row {
    grid-template-columns:1fr;
  }

  .btn-del-acc {
    width:100%;
    height:40px;
  }
}
</style>
</head>

<body>

<div class="topbar">
  <span style="font-size:20px">🔒</span>
  <h1>বন্ধক বন্ধ করুন</h1>
  <a href="pledge_payment.php?pledge_id=<?= $pledge_id ?>">পেমেন্ট</a>
  <a href="ui/pledges.html">তালিকা</a>
</div>

<div class="container">

<?php if ($pledge['status'] === 'CLOSED'): ?>

  <div class="closed-banner">
    ⛔ এই বন্ধক ইতিমধ্যে বন্ধ হয়ে গেছে।
    <br>
    <small><?= !empty($pledge['closed_at']) ? date('d M Y', strtotime($pledge['closed_at'])) : '' ?></small>
  </div>

  <button class="btn-back" onclick="location.href='ui/pledges.html'">← তালিকায় যান</button>

<?php else: ?>

  <div class="pills">
    <div class="pill">
      <div class="pl">মূল ঋণ</div>
      <div class="pv pv-blue">৳<?= number_format($pledge['loan_amount'], 0) ?></div>
    </div>

    <div class="pill">
      <div class="pl">বকেয়া মূল</div>
      <div class="pv pv-red">৳<?= number_format($outstanding, 0) ?></div>
    </div>

    <div class="pill">
      <div class="pl">লকার ভাড়া বাকি</div>
      <div class="pv pv-gold">৳<?= number_format($calc_interest, 0) ?></div>
    </div>

    <div class="pill">
      <div class="pl">মোট বাকি</div>
      <div class="pv pv-purple">৳<?= number_format($outstanding + $calc_interest, 0) ?></div>
    </div>
  </div>

  <div class="card">
    <div class="card-title">🔖 বন্ধক তথ্য</div>

    <div class="ig">
      <div>
        <label>কোড</label>
        <span class="v"><?= htmlspecialchars($pledge['pledge_code']) ?></span>
      </div>

      <div>
        <label>গ্রাহক</label>
        <span class="v"><?= htmlspecialchars($pledge['party_name'] ?? '—') ?></span>
      </div>

      <div>
        <label>ফোন</label>
        <span class="v"><?= htmlspecialchars($pledge['party_phone'] ?? '—') ?></span>
      </div>

      <div>
        <label>বন্ধক তারিখ</label>
        <span class="v"><?= date('d M Y', strtotime($pledge['pledge_date'])) ?></span>
      </div>

      <div>
        <label>ওজন</label>
        <span class="v"><?= number_format((float)$pledge['gross_weight'], 3) ?> g</span>
      </div>

      <div>
        <label>ভরি / আনা / রতি</label>
        <span class="v"><?= toVori((float)$pledge['gross_weight']) ?></span>
      </div>

      <div>
        <label>কারাট / বিশুদ্ধতা</label>
        <span class="v"><?= htmlspecialchars($pledge['karat']) ?> / <?= $pledge['actual_purity'] ?>%</span>
      </div>

      <div>
        <label>লকার ভাড়ার হার</label>
        <span class="v"><?= $interest_rate ?>% / মাস · <?= $days ?> দিন</span>
      </div>
    </div>
  </div>

  <div class="warn-box">
    <div class="wt">⚠️ বন্ধক বন্ধ করার আগে নিশ্চিত করুন</div>
    <ul>
      <li>গ্রাহকের কাছ থেকে সব টাকা নিয়েছেন</li>
      <li>গহনা ফেরত দেওয়ার জন্য প্রস্তুত</li>
      <li>বন্ধ করলে আর payment নেওয়া যাবে না</li>
    </ul>
  </div>

  <div class="card">
    <div class="card-title">🔒 চূড়ান্ত পেমেন্ট ও বন্ধ করুন</div>

    <div id="alert-success" class="alert alert-success"></div>
    <div id="alert-error" class="alert alert-error"></div>

    <div class="fr" style="margin-bottom:12px">
      <div class="fg">
        <label>শেষ লকার ভাড়া</label>
        <input type="number" id="final_interest" min="0" step="0.01"
               value="<?= $calc_interest ?>" inputmode="decimal" oninput="recalc()">
        <div class="hint">হিসাব: ৳<?= number_format($calc_interest, 2) ?></div>
      </div>

      <div class="fg">
        <label>শেষ মূল — বকেয়া ৳<?= number_format($outstanding, 0) ?></label>
        <input type="number" id="final_principal" min="0" step="0.01"
               value="<?= $outstanding ?>" max="<?= $outstanding ?>" inputmode="decimal" oninput="recalc()">
      </div>
    </div>

    <div class="disc-box">
      <div class="disc-title">🎁 ছাড় / Discount</div>

      <div class="disc-tabs">
        <div class="disc-tab on" id="tab-tk" onclick="setDiscTab('tk')">৳ টাকায়</div>
        <div class="disc-tab" id="tab-pct" onclick="setDiscTab('pct')">% শতাংশে</div>
      </div>

      <div class="fr">
        <div class="fg">
          <label id="disc-label">ছাড়ের পরিমাণ (৳)</label>
          <input type="number" id="discount_val" min="0" step="1" value="0"
                 inputmode="decimal" oninput="recalc()">
          <div class="hint" id="disc-hint">এই পরিমাণ মোট থেকে বাদ যাবে</div>
        </div>

        <div class="fg">
          <label>ছাড়ের কারণ</label>
          <input type="text" id="discount_reason" placeholder="যেমন: পুরাতন বন্ধক / সমন্বয়">
        </div>
      </div>
    </div>

    <div class="summary-box" id="summary-before">
      <div class="sb-row">
        <span class="sb-lbl">লকার ভাড়া</span>
        <span id="s-interest">৳<?= number_format($calc_interest, 2) ?></span>
      </div>

      <div class="sb-row">
        <span class="sb-lbl">মূল টাকা</span>
        <span id="s-principal">৳<?= number_format($outstanding, 2) ?></span>
      </div>

      <div class="sb-row">
        <span class="sb-lbl" style="color:#ddd6fe">ছাড়</span>
        <span id="s-discount" style="color:#ddd6fe">৳০</span>
      </div>

      <div class="sb-row total">
        <span>মোট নেওয়া হবে</span>
        <span id="s-total" style="color:#60a5fa">৳<?= number_format($outstanding + $calc_interest, 2) ?></span>
      </div>
    </div>

    <div class="fr" style="margin-bottom:12px">
      <div class="fg">
        <label>তারিখ</label>
        <input type="date" id="close_date" value="<?= date('Y-m-d') ?>">
      </div>

      <div class="fg">
        <label>মন্তব্য</label>
        <input type="text" id="close_note" placeholder="গহনা ফেরত দেওয়া হয়েছে">
      </div>
    </div>

    <div class="acc-box">
      <div class="acc-title">
        <span>🏦 কোন Account-এ জমা হবে?</span>
        <button type="button" onclick="addAccRow()">+ Account যোগ</button>
      </div>

      <div id="acc-rows"></div>

      <div class="acc-check" id="acc-check">জমা মোট: ৳০ | বাকি: ৳০</div>
    </div>

    <div class="final-warning">
      <div class="big">🔒 বন্ধক বন্ধ করা স্থায়ী!</div>
      <div class="small">একবার বন্ধ করলে আর পেমেন্ট নেওয়া যাবে না। গহনা ফেরত দিন।</div>
    </div>

    <button class="btn-close" id="btn-close">🔒 বন্ধক বন্ধ করুন ও গহনা ফেরত দিন</button>
    <button class="btn-back" onclick="location.href='pledge_payment.php?pledge_id=<?= $pledge_id ?>'">← পেমেন্ট পেজে ফিরুন</button>
  </div>

<?php endif; ?>

</div>

<script>
const PLEDGE_ID   = <?= $pledge_id ?>;
const OUTSTANDING = <?= $outstanding ?>;
const CALC_INT    = <?= $calc_interest ?>;
const API         = '<?= $base_url ?>/api/pawn/pledge_close.php';
const ACCOUNTS    = <?= json_encode(array_values($accounts), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

let discMode = 'tk';
let accRowCount = 0;

document.addEventListener('DOMContentLoaded', function() {
    addAccRow();
    recalc();
});

function setDiscTab(mode) {
    discMode = mode;

    document.getElementById('tab-tk').classList.toggle('on', mode === 'tk');
    document.getElementById('tab-pct').classList.toggle('on', mode === 'pct');
    document.getElementById('discount_val').value = 0;

    if (mode === 'tk') {
        document.getElementById('disc-label').textContent = 'ছাড়ের পরিমাণ (৳)';
        document.getElementById('disc-hint').textContent  = 'এই পরিমাণ মোট থেকে বাদ যাবে';
    } else {
        document.getElementById('disc-label').textContent = 'ছাড়ের পরিমাণ (%)';
        document.getElementById('disc-hint').textContent  = 'মোটের উপর শতাংশ ছাড়';
    }

    recalc();
}

function addAccRow() {
    accRowCount++;
    const n = accRowCount;

    const div = document.createElement('div');
    div.className = 'acc-row';
    div.id = 'arow-' + n;

    const opts = ACCOUNTS.map(a => {
        const name = a.account_name_bn || a.account_name || ('Account #' + a.id);
        const bal  = Number(a.current_balance || 0).toLocaleString('en-BD', {maximumFractionDigits:0});
        return `<option value="${a.id}">${name} (৳${bal})</option>`;
    }).join('');

    div.innerHTML = `
        <div class="fg" style="margin:0">
            <label>Account</label>
            <select id="asel-${n}" onchange="syncAccounts()">${opts}</select>
        </div>

        <div class="fg" style="margin:0">
            <label>পরিমাণ (৳)</label>
            <input type="number" id="aamt-${n}" min="0" step="1" value="0" inputmode="decimal" oninput="syncAccounts()">
        </div>

        ${n > 1 ? `<button type="button" class="btn-del-acc" onclick="removeAccRow(${n})">✕</button>` : '<div></div>'}
    `;

    document.getElementById('acc-rows').appendChild(div);
    syncAccounts();
}

function removeAccRow(n) {
    const el = document.getElementById('arow-' + n);
    if (el) el.remove();
    syncAccounts();
}

function getGross() {
    const lockerRent = parseFloat(document.getElementById('final_interest').value) || 0;
    const principal  = parseFloat(document.getElementById('final_principal').value) || 0;
    return lockerRent + principal;
}

function getDiscount() {
    const val = parseFloat(document.getElementById('discount_val').value) || 0;

    if (discMode === 'pct') {
        return Math.round(getGross() * val / 100 * 100) / 100;
    }

    return val;
}

function getNetTotal() {
    return Math.max(0, getGross() - getDiscount());
}

function syncAccounts() {
    const total = getNetTotal();
    let accSum = 0;

    document.querySelectorAll('[id^="aamt-"]').forEach(inp => {
        accSum += parseFloat(inp.value) || 0;
    });

    const remaining = Math.max(0, total - accSum);

    const box = document.getElementById('acc-check');
    box.textContent =
        'জমা মোট: ৳' + accSum.toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2}) +
        ' | বাকি: ৳' + remaining.toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2});

    box.style.color = remaining > 0.01 ? '#fca5a5' : '#86efac';
}

function autoFillFirstAcc() {
    const rows = document.querySelectorAll('[id^="aamt-"]');

    if (rows.length === 1) {
        rows[0].value = getNetTotal().toFixed(2);
        syncAccounts();
    }
}

function recalc() {
    const lockerRent = parseFloat(document.getElementById('final_interest').value) || 0;
    const principal  = parseFloat(document.getElementById('final_principal').value) || 0;
    const disc       = getDiscount();
    const net        = Math.max(0, lockerRent + principal - disc);

    document.getElementById('s-interest').textContent =
        '৳' + lockerRent.toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2});

    document.getElementById('s-principal').textContent =
        '৳' + principal.toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2});

    document.getElementById('s-discount').textContent =
        disc > 0
            ? '− ৳' + disc.toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2})
            : '৳০';

    document.getElementById('s-total').textContent =
        '৳' + net.toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2});

    autoFillFirstAcc();
    syncAccounts();
}

document.addEventListener('click', function(e) {
    if (e.target.closest('#btn-close')) {
        submitClose();
    }
});

function submitClose() {
    const lockerRent = parseFloat(document.getElementById('final_interest').value) || 0;
    const principal  = parseFloat(document.getElementById('final_principal').value) || 0;
    const disc       = getDiscount();
    const net        = getNetTotal();
    const date       = document.getElementById('close_date').value;
    const note       = document.getElementById('close_note').value.trim();
    const discReason = document.getElementById('discount_reason').value.trim();

    hideAlerts();

    if (principal > OUTSTANDING + 0.01) {
        showError('মূল পরিমাণ বকেয়ার বেশি হতে পারে না।');
        return;
    }

    const payments = [];

    document.querySelectorAll('[id^="arow-"]').forEach(row => {
        const n = row.id.replace('arow-', '');
        const accId = parseInt(document.getElementById('asel-' + n)?.value) || 0;
        const amt   = parseFloat(document.getElementById('aamt-' + n)?.value) || 0;

        if (accId > 0 && amt > 0) {
            payments.push({
                cash_account_id: accId,
                amount: amt
            });
        }
    });

    const payTotal = payments.reduce((s, p) => s + p.amount, 0);

    if (net > 0 && payments.length === 0) {
        showError('কমপক্ষে একটি account-এ পরিমাণ দিন।');
        return;
    }

    if (net > 0 && Math.abs(payTotal - net) > 1) {
        showError(
            'Account-এর মোট (' + payTotal.toFixed(2) + ') মোট নেওয়ার পরিমাণের (' + net.toFixed(2) + ') সাথে মিলছে না।'
        );
        return;
    }

    if (!confirm('নিশ্চিত? বন্ধক বন্ধ করলে আর পেমেন্ট নেওয়া যাবে না!\n\nগ্রাহককে গহনা ফেরত দিয়েছেন?')) {
        return;
    }

    const btn = document.getElementById('btn-close');
    btn.disabled = true;
    btn.textContent = '⏳ বন্ধ হচ্ছে…';

    const fd = new FormData();
    fd.append('pledge_id',       PLEDGE_ID);
    fd.append('close_date',      date);
    fd.append('final_interest',  lockerRent);
    fd.append('final_principal', principal);
    fd.append('discount',        disc);
    fd.append('discount_reason', discReason);
    fd.append('payments',        JSON.stringify(payments));
    fd.append('close_note',      note);

    fetch(API, { method:'POST', body:fd })
        .then(r => {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(data => {
            if (data.success) {
                showSuccess('✅ ' + data.message);
                btn.textContent = '✅ বন্ধ হয়েছে';
                setTimeout(() => location.href = 'ui/pledges.html', 2000);
            } else {
                showError(data.message || 'অজানা ত্রুটি।');
                btn.disabled = false;
                btn.textContent = '🔒 বন্ধক বন্ধ করুন ও গহনা ফেরত দিন';
            }
        })
        .catch(err => {
            showError('Error: ' + err.message);
            btn.disabled = false;
            btn.textContent = '🔒 বন্ধক বন্ধ করুন ও গহনা ফেরত দিন';
        });
}

function showSuccess(m) {
    const e = document.getElementById('alert-success');
    e.textContent = m;
    e.style.display = 'block';
}

function showError(m) {
    const e = document.getElementById('alert-error');
    e.textContent = m;
    e.style.display = 'block';
}

function hideAlerts() {
    document.getElementById('alert-success').style.display = 'none';
    document.getElementById('alert-error').style.display = 'none';
}
</script>

</body>
</html>