<?php
$date_today       = date('Y-m-d');
$date_month_start = '2021-01-01';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>বন্ধক ম্যানেজমেন্ট — বধুবরণ জুয়েলার্স</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:#080F1E;--card:#0F1A30;
  --border:#1A2D50;--gold:#F5B800;
  --blue:#4F8EF7;--green:#10B981;--red:#EF4444;
  --purple:#A78BFA;--text:#E8F0FE;--sub:#5C7DA8;
}
body{background:var(--bg);color:var(--text);font-family:'Segoe UI',Arial,sans-serif;max-width:480px;margin:0 auto;padding-bottom:40px}
.hdr{background:linear-gradient(135deg,#0D1829,#162240);border-bottom:2px solid var(--gold);padding:12px 16px;display:flex;align-items:center;gap:10px;position:sticky;top:0;z-index:99;box-shadow:0 2px 20px rgba(0,0,0,.5)}
.back-a{width:36px;height:36px;background:rgba(245,184,0,.12);border:1px solid rgba(245,184,0,.3);border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;text-decoration:none;color:var(--gold);flex-shrink:0}
.hdr-title{font-size:15px;font-weight:800;color:var(--text)}
.wrap{padding:14px}
.box{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:14px;margin-bottom:12px}
label{display:block;font-size:11px;font-weight:700;color:var(--sub);margin-bottom:5px;text-transform:uppercase;letter-spacing:.3px}
input,select,textarea{width:100%;background:#060E1C;border:1px solid var(--border);border-radius:10px;color:var(--text);padding:10px 12px;font-size:14px;outline:none;font-family:'Segoe UI',Arial,sans-serif;transition:border-color .2s}
input:focus,select:focus,textarea:focus{border-color:rgba(245,184,0,.4)}
input[readonly]{color:var(--gold);font-weight:700;background:rgba(245,184,0,.06);cursor:default}
textarea{resize:vertical}
select option{background:#0F1A30}
input::placeholder,textarea::placeholder{color:#2E4A6B}
.g2{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.g3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px}
.btn-main{width:100%;padding:14px;background:linear-gradient(135deg,#D4780A,#F5B800);color:#080F1E;border:none;border-radius:13px;font-size:16px;font-weight:800;cursor:pointer;box-shadow:0 4px 16px rgba(245,184,0,.25);transition:transform .15s}
.btn-main:active{transform:scale(.97)}
.btn-search{width:100%;padding:11px;background:rgba(245,184,0,.1);border:1px solid rgba(245,184,0,.25);color:var(--gold);border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;margin-top:8px}
.btn-search:active{transform:scale(.97)}
.quick-tabs{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:10px}
.qtab{padding:12px 10px;border-radius:11px;border:1px solid var(--border);background:#060E1C;color:var(--sub);font-size:12px;font-weight:700;cursor:pointer;text-align:center;transition:all .2s;display:flex;flex-direction:column;align-items:center;gap:4px;font-family:inherit}
.qtab .icon{font-size:18px}
.qtab .cnt{font-size:11px;color:var(--sub);font-weight:600}
.qtab.on{border-width:2px}
.qtab[data-q="risky"].on{background:rgba(239,68,68,.1);border-color:var(--red);color:var(--red)}
.qtab[data-q="risky"].on .cnt{color:var(--red)}
.qtab[data-q="over_90days"].on{background:rgba(245,184,0,.1);border-color:var(--gold);color:var(--gold)}
.qtab[data-q="over_90days"].on .cnt{color:var(--gold)}
.qtab[data-q="today"].on{background:rgba(79,142,247,.1);border-color:var(--blue);color:var(--blue)}
.qtab[data-q="today"].on .cnt{color:var(--blue)}
.qtab[data-q="this_month"].on{background:rgba(16,185,129,.1);border-color:var(--green);color:var(--green)}
.qtab[data-q="this_month"].on .cnt{color:var(--green)}
.adv-toggle{background:transparent;border:none;color:var(--sub);font-size:12px;font-weight:700;cursor:pointer;padding:6px 0;font-family:inherit;display:flex;align-items:center;gap:4px;width:100%;justify-content:space-between}
.adv-toggle .arrow{transition:transform .2s}
.adv-toggle.on .arrow{transform:rotate(180deg)}
.adv-panel{display:none;padding-top:10px;border-top:1px dashed var(--border);margin-top:8px}
.adv-panel.on{display:block}
.sbtn{width:auto;padding:8px 14px;border-radius:20px;border:1px solid var(--border);background:#060E1C;color:var(--sub);font-size:12px;font-weight:700;cursor:pointer;transition:all .2s;font-family:inherit}
.sbtn.active{background:rgba(245,184,0,.15);border-color:var(--gold);color:var(--gold)}
.kpill-row{display:flex;gap:6px;flex-wrap:wrap}
.kpill{width:auto;padding:6px 11px;border-radius:8px;border:1px solid var(--border);background:#060E1C;color:var(--sub);font-size:12px;font-weight:700;cursor:pointer;font-family:inherit}
.kpill.on{background:rgba(245,184,0,.15);border-color:var(--gold);color:var(--gold)}
.sum-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.sum{background:#060E1C;border:1px solid var(--border);border-radius:12px;padding:11px;text-align:center}
.sum .t{font-size:10px;color:var(--sub);text-transform:uppercase;letter-spacing:.4px;margin-bottom:4px}
.sum .n{font-size:17px;font-weight:900}
.pcard{background:#060E1C;border:1px solid var(--border);border-radius:13px;padding:13px;margin-bottom:8px;border-left:3px solid var(--green);position:relative}
.pcard.locker{border-left-color:var(--blue)}
.pcard.returned{border-left-color:var(--sub)}
.pcard.risky{border-left-color:var(--red)}
.pcard.over90{border-left-color:var(--gold)}
.risk-corner{position:absolute;top:8px;right:8px;display:flex;gap:4px;flex-wrap:wrap;justify-content:flex-end}
.risk-tag{font-size:9px;font-weight:800;padding:2px 7px;border-radius:10px;white-space:nowrap}
.risk-tag.r-risky{background:rgba(239,68,68,.2);color:var(--red);border:1px solid rgba(239,68,68,.3)}
.risk-tag.r-over{background:rgba(245,184,0,.2);color:var(--gold);border:1px solid rgba(245,184,0,.3)}
.badge{display:inline-block;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:800;margin-bottom:6px}
.badge.local{background:rgba(16,185,129,.15);color:var(--green);border:1px solid rgba(16,185,129,.25)}
.badge.locker{background:rgba(79,142,247,.15);color:var(--blue);border:1px solid rgba(79,142,247,.25)}
.badge.returned{background:rgba(92,125,168,.15);color:var(--sub);border:1px solid rgba(92,125,168,.25)}
.cg2{display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-top:10px}
.cell{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:8px}
.cell .k{font-size:10px;color:var(--sub);margin-bottom:2px}
.cell .v{font-size:13px;font-weight:800}
.actions{display:flex;gap:7px;margin-top:10px}
.btn-sm{width:auto;padding:8px 13px;font-size:12px;font-weight:700;border-radius:9px;cursor:pointer;border:none;font-family:inherit}
.btn-view{background:rgba(79,142,247,.15);color:var(--blue);border:1px solid rgba(79,142,247,.25)}
.btn-pay{background:linear-gradient(135deg,#D4780A,#F5B800);color:#080F1E}
mark.hl{background:rgba(245,184,0,.4);color:var(--gold);padding:0 3px;border-radius:3px;font-weight:800}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.8);z-index:999;overflow-y:auto;padding:14px}
.mbox{max-width:460px;margin:10px auto;background:var(--card);border:1px solid rgba(245,184,0,.25);border-radius:20px;overflow:hidden;position:relative}
.mbox::before{content:'';position:absolute;top:0;left:20%;right:20%;height:2px;background:linear-gradient(90deg,transparent,var(--gold),transparent)}
.mhead{background:rgba(245,184,0,.06);border-bottom:1px solid var(--border);padding:13px 16px;display:flex;justify-content:space-between;align-items:center}
.mhead span{font-size:15px;font-weight:800;color:var(--gold)}
.mclose{width:30px;height:30px;border-radius:8px;background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.2);color:var(--red);cursor:pointer;font-size:14px;padding:0;transition:background .2s;font-family:inherit}
.mclose:hover{background:var(--red);color:#fff}
.mbody{padding:16px;max-height:76vh;overflow-y:auto}
.mfoot{padding:12px 16px;border-top:1px solid var(--border);display:flex;gap:8px;justify-content:flex-end}
.msec{margin-bottom:14px}
.msec-title{font-size:11px;font-weight:800;color:var(--gold);text-transform:uppercase;letter-spacing:.6px;padding-bottom:6px;border-bottom:1px solid var(--border);margin-bottom:10px}
.mfield{display:flex;flex-direction:column;gap:4px;margin-bottom:10px}
.mfield label{font-size:11px;color:var(--sub);font-weight:600;text-transform:uppercase;letter-spacing:.3px}
.mfield input,.mfield select,.mfield textarea{background:#060E1C;border:1px solid var(--border);color:var(--text);font-size:13px;padding:9px 11px;border-radius:9px;width:100%;outline:none;font-family:'Segoe UI',Arial,sans-serif}
.mfield input:focus,.mfield select:focus{border-color:rgba(245,184,0,.4)}
.mfield input[readonly]{color:var(--gold);font-weight:700;background:rgba(245,184,0,.06)}
.mfield textarea{height:52px;resize:none}
.mfield select option{background:#0F1A30}
.party-wrap{position:relative}
.party-selected{display:flex;align-items:center;gap:8px;background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.35);border-radius:9px;padding:9px 11px}
.psel-info{flex:1;display:flex;flex-direction:column;gap:2px;overflow:hidden;min-width:0}
.psel-name{font-size:13px;font-weight:800;color:var(--green);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.psel-phone{font-size:11px;color:var(--sub)}
.psel-clear{width:26px;height:26px;border-radius:50%;background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.28);color:var(--red);cursor:pointer;font-size:12px;padding:0;flex-shrink:0;font-family:inherit}
.psel-clear:hover{background:var(--red);color:#fff}
.party-dd{position:absolute;top:100%;left:0;right:0;background:#060E1C;border:1px solid rgba(245,184,0,.25);border-radius:10px;margin-top:4px;max-height:280px;overflow:hidden;z-index:20;box-shadow:0 6px 20px rgba(0,0,0,.5);display:flex;flex-direction:column}
.party-results{overflow-y:auto;flex:1}
.party-item{padding:10px 11px;border-bottom:1px solid rgba(26,45,80,.5);cursor:pointer;transition:background .15s}
.party-item:last-child{border-bottom:none}
.party-item:hover,.party-item:active{background:rgba(245,184,0,.08)}
.party-item .pn{font-size:13px;font-weight:800;color:var(--text);margin-bottom:3px}
.party-item .pp{font-size:11px;color:var(--sub);line-height:1.4}
.party-item .pp b{color:var(--text);font-weight:600}
.party-item .pt{margin-top:4px}
.party-item .pt .tg{display:inline-block;padding:1px 7px;border-radius:10px;margin-right:4px;font-size:9px;font-weight:800;text-transform:uppercase}
.party-item .pt .tg.c{background:rgba(79,142,247,.15);color:var(--blue)}
.party-item .pt .tg.s{background:rgba(167,139,250,.15);color:var(--purple)}
.party-item .pt .tg.p{background:rgba(245,184,0,.15);color:var(--gold)}
.party-loading,.party-empty{padding:16px;text-align:center;font-size:12px;color:var(--sub)}
.party-add-new{width:100%;padding:12px;background:rgba(16,185,129,.08);border:none;border-top:1px solid var(--border);color:var(--green);font-size:13px;font-weight:800;cursor:pointer;display:block;flex-shrink:0;font-family:inherit}
.party-add-new:hover,.party-add-new:active{background:rgba(16,185,129,.18)}
#qpModal{z-index:1000}
#qpModal .mbox{max-width:400px}
.krow{display:flex;gap:6px;flex-wrap:wrap}
.kbtn{width:auto;padding:6px 11px;border-radius:8px;border:1px solid var(--border);background:#060E1C;color:var(--sub);font-size:12px;font-weight:700;cursor:pointer;transition:all .2s;font-family:inherit}
.kbtn.on{background:rgba(245,184,0,.15);border-color:var(--gold);color:var(--gold)}
.wtrow{display:flex;gap:6px;margin-bottom:8px}
.wtab{width:auto;padding:5px 12px;border-radius:7px;border:1px solid var(--border);background:#060E1C;color:var(--sub);font-size:12px;font-weight:600;cursor:pointer;transition:all .2s;font-family:inherit}
.wtab.on{background:rgba(245,184,0,.15);border-color:var(--gold);color:var(--gold)}
.hrow{display:flex;gap:8px;margin-bottom:10px}
.hbtn{flex:1;padding:10px;border-radius:10px;border:1px solid var(--border);background:#060E1C;color:var(--sub);font-size:13px;font-weight:700;cursor:pointer;text-align:center;transition:all .2s;font-family:inherit}
.hbtn.showroom.on{background:rgba(79,142,247,.15);border-color:var(--blue);color:var(--blue)}
.hbtn.locker.on{background:rgba(167,139,250,.15);border-color:var(--purple);color:var(--purple)}
.malert{padding:10px 13px;border-radius:9px;font-size:13px;margin-bottom:10px;display:none;font-weight:700}
.malert.err{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.2);color:var(--red)}
.malert.ok{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.2);color:var(--green)}
.btn-cancel{background:rgba(255,255,255,.06);color:var(--sub);border:1px solid var(--border);width:auto;font-size:14px;padding:10px 18px;border-radius:10px;cursor:pointer;font-family:inherit}
.btn-save{background:linear-gradient(135deg,#D4780A,#F5B800);color:#080F1E;border:none;width:auto;font-size:14px;font-weight:800;padding:10px 22px;border-radius:10px;cursor:pointer;box-shadow:0 4px 12px rgba(245,184,0,.25);font-family:inherit}
.btn-save:disabled{opacity:.5;cursor:not-allowed}
.item-card{background:#060E1C;border:1px solid var(--border);border-radius:11px;padding:12px;margin-bottom:10px}
.item-card-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
.item-num{font-size:13px;font-weight:800;color:var(--gold)}
.item-del{width:auto;padding:4px 10px;background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.25);color:var(--red);border-radius:7px;font-size:12px;cursor:pointer;font-family:inherit}
.item-total{background:rgba(245,184,0,.06);border:1px solid rgba(245,184,0,.15);border-radius:8px;padding:9px;margin-top:8px;font-size:12px;color:var(--sub)}
.item-total span{color:var(--gold);font-weight:800}
.btn-add-item{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.25);color:var(--green);width:100%;padding:10px;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;margin-bottom:10px;font-family:inherit}
.grand-total{background:rgba(245,184,0,.08);border:1px solid rgba(245,184,0,.2);border-radius:11px;padding:13px;margin-bottom:10px;text-align:center}
.grand-total .lbl{font-size:10px;color:var(--sub);text-transform:uppercase;margin-bottom:4px}
.grand-total .amt{font-size:24px;font-weight:900;color:var(--gold)}
.sec-title{font-size:12px;font-weight:800;color:var(--gold);text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px}
.sec-title::after{content:'';flex:1;height:1px;background:linear-gradient(90deg,var(--border),transparent)}
.empty{text-align:center;padding:28px;color:var(--sub);font-size:13px}
.sort-row{display:flex;gap:8px;align-items:center;margin-bottom:10px;font-size:12px}
.sort-row label{margin:0;font-size:11px;white-space:nowrap}
.sort-row select{padding:8px 10px;font-size:12px}
.locker-select-box{display:none;background:rgba(167,139,250,.07);border:1px solid rgba(167,139,250,.25);border-radius:10px;padding:12px;margin-bottom:10px}
.locker-select-box.show{display:block}
.locker-select-box label{color:var(--purple);font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.3px;margin-bottom:6px;display:block}
.locker-select-box select{background:#060E1C;border:1px solid rgba(167,139,250,.3);color:var(--text);border-radius:9px;padding:10px 12px;font-size:14px;outline:none}
.locker-select-box select:focus{border-color:var(--purple)}
.spin{display:inline-block;animation:spin 1s linear infinite}
@keyframes spin{from{transform:rotate(0)}to{transform:rotate(360deg)}}
.rate-bar{background:rgba(245,184,0,.06);border:1px solid rgba(245,184,0,.15);border-radius:10px;padding:8px 12px;margin-bottom:10px;display:flex;gap:10px;flex-wrap:wrap;align-items:center}
.rate-bar .rl{font-size:10px;color:var(--sub);font-weight:700;text-transform:uppercase}
.rate-bar .rv{font-size:13px;color:var(--gold);font-weight:800}
</style>
</head>
<body>

<div class="hdr">
  <a class="back-a" href="/ui/dashboard.html">←</a>
  <div class="hdr-title">🔒 বন্ধক ম্যানেজমেন্ট</div>
</div>

<div class="wrap">

<div class="rate-bar" id="rateBar">
  <div><div class="rl">২২K</div><div class="rv" id="rBar22">লোড...</div></div>
  <div><div class="rl">২১K</div><div class="rv" id="rBar21">—</div></div>
  <div><div class="rl">১৮K</div><div class="rv" id="rBar18">—</div></div>
  <div style="margin-left:auto;font-size:10px;color:var(--sub)" id="rBarDate"></div>
</div>

<div class="box">
  <button class="btn-main" onclick="openModal()">+ নতুন বন্ধক Entry</button>
</div>

<div class="box">
  <div class="sec-title">⚡ দ্রুত ফিল্টার</div>
  <div class="quick-tabs">
    <button class="qtab" data-q="today" onclick="setQuickTab(this)">
      <div class="icon">📅</div><div>আজকের বন্ধক</div><div class="cnt" id="qCnt_today">—</div>
    </button>
    <button class="qtab" data-q="this_month" onclick="setQuickTab(this)">
      <div class="icon">📆</div><div>এই মাসে</div><div class="cnt" id="qCnt_this_month">—</div>
    </button>
    <button class="qtab" data-q="over_90days" onclick="setQuickTab(this)">
      <div class="icon">⏰</div><div>৯০ দিন পার</div><div class="cnt" id="qCnt_over_90days">—</div>
    </button>
    <button class="qtab" data-q="risky" onclick="setQuickTab(this)">
      <div class="icon">⚠️</div><div>ঝুঁকিপূর্ণ</div><div class="cnt" id="qCnt_risky">—</div>
    </button>
  </div>
</div>

<div class="box">
  <div class="sec-title">🔍 সার্চ ও ফিল্টার</div>
  <div class="g2" style="margin-bottom:10px">
    <div><label>নাম / মোবাইল</label><input type="text" id="searchInput" placeholder="গ্রাহকের নাম বা মোবাইল..." oninput="liveSearch()"></div>
    <div><label>বন্ধক কোড</label><input type="text" id="pledgeCodeInput" placeholder="যেমন: PLG-2026..." oninput="liveSearch()"></div>
  </div>
  <div class="g2" style="margin-bottom:10px">
    <div><label>বারকোড / নোট</label><input type="text" id="barcodeInput" placeholder="বারকোড বা নোটে..." oninput="liveSearch()"></div>
    <div>
      <label>স্ট্যাটাস</label>
      <div style="display:flex;gap:4px;flex-wrap:wrap;margin-top:2px">
        <button class="sbtn active" data-s="OPEN"   onclick="setStatus(this)">🏪 খোলা</button>
        <button class="sbtn"        data-s="LOCKER" onclick="setStatus(this)">🔐</button>
        <button class="sbtn"        data-s="CLOSED" onclick="setStatus(this)">✅</button>
        <button class="sbtn"        data-s="ALL"    onclick="setStatus(this)">সব</button>
      </div>
    </div>
  </div>
  <button class="adv-toggle" id="advBtn" onclick="toggleAdv()">
    <span>⚙️ উন্নত ফিল্টার (তারিখ, ঋণ রেঞ্জ, ক্যারেট)</span>
    <span class="arrow">▼</span>
  </button>
  <div class="adv-panel" id="advPanel">
    <div class="g2" style="margin-bottom:10px">
      <div><label>শুরুর তারিখ</label><input type="date" id="fromDate" value="2021-01-01" onchange="liveSearch()"></div>
      <div><label>শেষ তারিখ</label><input type="date" id="toDate" value="<?php echo $date_today; ?>" onchange="liveSearch()"></div>
    </div>
    <div class="g2" style="margin-bottom:10px">
      <div><label>ঋণ সর্বনিম্ন (৳)</label><input type="number" id="loanMin" placeholder="যেমন: 5000" step="100" oninput="liveSearch()"></div>
      <div><label>ঋণ সর্বোচ্চ (৳)</label><input type="number" id="loanMax" placeholder="যেমন: 50000" step="100" oninput="liveSearch()"></div>
    </div>
    <div style="margin-bottom:10px">
      <label>ক্যারেট</label>
      <div class="kpill-row">
        <button class="kpill on" data-k=""        onclick="setKarat(this)">সব</button>
        <button class="kpill"    data-k="24K"     onclick="setKarat(this)">২৪K</button>
        <button class="kpill"    data-k="22K"     onclick="setKarat(this)">২২K</button>
        <button class="kpill"    data-k="21K"     onclick="setKarat(this)">২১K</button>
        <button class="kpill"    data-k="18K"     onclick="setKarat(this)">১৮K</button>
        <button class="kpill"    data-k="SANATAN" onclick="setKarat(this)">সনাতন</button>
      </div>
    </div>
  </div>
  <div style="display:flex;gap:8px;margin-top:8px">
    <button class="btn-search" onclick="loadList()" style="margin-top:0">🔍 খুঁজুন</button>
    <button class="btn-search" onclick="resetFilters()" style="margin-top:0;background:rgba(239,68,68,.08);border-color:rgba(239,68,68,.2);color:var(--red)">♻️ রিসেট</button>
  </div>
</div>

<div class="box">
  <div class="sec-title">📊 সারাংশ</div>
  <div class="sum-grid">
    <div class="sum"><div class="t">Entries</div><div class="n" id="sumE">০</div></div>
    <div class="sum"><div class="t">মোট ঋণ</div><div class="n" style="color:var(--red)" id="sumL">৳০</div></div>
    <div class="sum"><div class="t">বাকি আসল</div><div class="n" style="color:var(--red)" id="sumO">৳০</div></div>
    <div class="sum"><div class="t">সোনার মূল্য</div><div class="n" style="color:var(--gold)" id="sumG">৳০</div></div>
    <div class="sum"><div class="t">নেওয়া আসল</div><div class="n" style="color:var(--green)" id="sumP">৳০</div></div>
    <div class="sum"><div class="t">নেওয়া লকার ভাড়া</div><div class="n" style="color:var(--blue)" id="sumI">৳০</div></div>
  </div>
</div>

<div class="box">
  <div class="sec-title">বন্ধক লিস্ট <span id="listCount" style="font-size:11px;color:var(--sub);font-weight:600;letter-spacing:0;text-transform:none"></span></div>
  <div class="sort-row">
    <label>সর্ট:</label>
    <select id="sortBy" onchange="loadList()">
      <option value="date_desc">নতুন আগে (তারিখ ↓)</option>
      <option value="date_asc">পুরানো আগে (তারিখ ↑)</option>
      <option value="loan_desc">বড় ঋণ আগে (৳ ↓)</option>
      <option value="loan_asc">ছোট ঋণ আগে (৳ ↑)</option>
      <option value="name_asc">নাম A→Z</option>
      <option value="name_desc">নাম Z→A</option>
    </select>
  </div>
  <div id="pledgeList"><div class="empty">লোড হচ্ছে...</div></div>
</div>

</div>

<!-- MAIN PLEDGE MODAL -->
<div id="pledgeModal" class="modal">
<div class="mbox">
<div class="mhead">
  <span>🔒 নতুন বন্ধক Entry</span>
  <button class="mclose" onclick="closeModal()">✕</button>
</div>
<div class="mbody">
<div class="malert" id="mAlert"></div>

<div class="msec">
  <div class="msec-title">👤 গ্রাহক তথ্য</div>
  <div class="mfield">
    <label>গ্রাহক / পার্টি *</label>
    <div class="party-wrap" id="partyWrap">
      <div class="party-selected" id="partySelected" style="display:none">
        <div class="psel-info">
          <span class="psel-name" id="pselName"></span>
          <span class="psel-phone" id="pselPhone"></span>
        </div>
        <button type="button" class="psel-clear" onclick="clearParty()" title="পরিবর্তন করুন">✕</button>
      </div>
      <input type="text" id="partySearch" placeholder="🔍 নাম বা ফোন দিয়ে খুঁজুন..." autocomplete="off" oninput="onPartySearch()" onfocus="onPartyFocus()">
      <div class="party-dd" id="partyDD" style="display:none">
        <div class="party-results" id="partyResults"></div>
        <button type="button" class="party-add-new" onclick="openQuickAdd()">➕ নতুন পার্টি যোগ করুন</button>
      </div>
    </div>
    <input type="hidden" id="mParty" value="">
  </div>
  <div class="mfield">
    <label>তারিখ *</label>
    <input type="date" id="mDate" value="<?php echo $date_today; ?>">
  </div>
</div>

<div class="msec">
  <div class="msec-title">🪙 সোনার আইটেম</div>
  <div id="itemsContainer"></div>
  <button class="btn-add-item" type="button" onclick="addItem()">+ আরেকটি আইটেম যোগ করুন</button>
  <div class="grand-total">
    <div class="lbl">মোট সোনার মূল্য</div>
    <div class="amt" id="grandTotal">৳ ০</div>
    <div style="font-size:11px;color:var(--sub);margin-top:4px" id="grandItems">০টি আইটেম</div>
  </div>
</div>

<div class="msec">
  <div class="msec-title">💵 ঋণ তথ্য</div>
  <div class="g3">
    <div class="mfield"><label>ঋণ (৳) *</label><input type="number" id="mLoan" placeholder="0" step="1" min="0"></div>
    <div class="mfield"><label>লকার ভাড়া (% / মাস)</label><input type="number" id="mRate" value="2" step="0.1" min="0"></div>
    <div class="mfield"><label>Cash Account *</label>
      <select id="mCash"><option value="">— লোড হচ্ছে —</option></select>
    </div>
  </div>
</div>

<div class="msec">
  <div class="msec-title">📍 কোথায় রাখবেন?</div>
  <div class="hrow">
    <button class="hbtn showroom on" data-h="SHOWROOM" onclick="setHold(this)">🏪 শোরুম</button>
    <button class="hbtn locker" data-h="LOCKER" onclick="setHold(this)">🔐 লকার</button>
  </div>
  <div class="locker-select-box" id="lockerSelectBox">
    <label>🔐 লকার বেছে নিন *</label>
    <select id="mLockerId">
      <option value="">— লকার select করুন —</option>
    </select>
    <div style="font-size:11px;color:var(--sub);margin-top:6px">লকার না থাকলে প্রথমে লকার মডিউলে যোগ করুন</div>
  </div>
  <div class="mfield">
    <label>বিস্তারিত লোকেশন (ঐচ্ছিক)</label>
    <input type="text" id="mLocNote" placeholder="যেমন: সোনালী ব্যাংক মতিঝিল / শোরুম কাউন্টার-২">
  </div>
</div>

<div class="msec">
  <div class="msec-title">📝 অতিরিক্ত</div>
  <div class="g2">
    <div class="mfield"><label>Barcode (ঐচ্ছিক)</label><input type="text" id="mBarcode" placeholder="যদি থাকে"></div>
    <div class="mfield"><label>নোট (ঐচ্ছিক)</label><textarea id="mNote" placeholder="বিশেষ তথ্য..."></textarea></div>
  </div>
</div>

</div>
<div class="mfoot">
  <button class="btn-cancel" onclick="closeModal()">বাতিল</button>
  <button class="btn-save" id="mSaveBtn" onclick="savePledge()">✅ সেভ করুন</button>
</div>
</div>
</div>

<!-- QUICK ADD PARTY MODAL -->
<div id="qpModal" class="modal">
<div class="mbox">
<div class="mhead">
  <span>➕ নতুন পার্টি যোগ</span>
  <button class="mclose" onclick="closeQuickAdd()">✕</button>
</div>
<div class="mbody">
<div class="malert" id="qpAlert"></div>
<div class="mfield"><label>নাম *</label><input type="text" id="qpName" placeholder="যেমন: রহিম উদ্দিন" autocomplete="off"></div>
<div class="mfield"><label>ফোন *</label><input type="tel" id="qpPhone" placeholder="যেমন: 01712345678" autocomplete="off"></div>
<div class="mfield"><label>ঠিকানা (ঐচ্ছিক)</label><input type="text" id="qpAddress" placeholder="যেমন: ঢাকা, বাংলাদেশ" autocomplete="off"></div>
<div style="background:rgba(79,142,247,.08);border:1px solid rgba(79,142,247,.2);border-radius:9px;padding:10px;font-size:12px;color:var(--blue);line-height:1.5">
  ℹ️ পার্টি টাইপ: <b>গ্রাহক + বন্ধক পার্টি</b> (অটো)<br>
  ⚠️ একই ফোন নম্বর থাকলে যোগ হবে না
</div>
</div>
<div class="mfoot">
  <button class="btn-cancel" onclick="closeQuickAdd()">বাতিল</button>
  <button class="btn-save" id="qpSaveBtn" onclick="saveQuickParty()">+ যোগ করুন</button>
</div>
</div>
</div>

<script>
var BHARI=11.664,ANA=BHARI/16,ROTI=BHARI/96,POINT=BHARI/960;
var SEL_HOLD='SHOWROOM',RATE_G=0,CUR_STATUS='OPEN',CUR_KARAT='',CUR_QUICK='',itemCount=0;
var partyDebounce=null,listDebounce=null;

function G(id){return document.getElementById(id);}
function fmt(n){return Number(n||0).toLocaleString('en-IN');}
function tk(n){return '৳'+Number(n||0).toLocaleString('en-IN',{minimumFractionDigits:0,maximumFractionDigits:0});}
function esc(s){return String(s||'').replace(/[&<>"']/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];});}
function hl(text,term){if(!term||!text)return esc(text);var escaped=esc(String(text));var safe=term.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');try{return escaped.replace(new RegExp('('+safe+')','gi'),'<mark class="hl">$1</mark>');}catch(e){return escaped;}}
function showAlert(msg,type){var b=G('mAlert');b.textContent=msg;b.className='malert '+type;b.style.display='block';if(type==='ok')setTimeout(function(){b.style.display='none';},3000);}

/* ===== GOLD RATE ===== */
function loadGoldRate(){
  fetch('/api/gold/get_rate.php',{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    if(res&&res.ok&&res.data){
      var d=res.data;
      RATE_G=parseFloat(d.rate_22k||0);
      if(G('rBar22'))G('rBar22').textContent='৳'+fmt(Math.round(RATE_G))+'/গ্রা';
      if(G('rBar21'))G('rBar21').textContent='৳'+fmt(Math.round(parseFloat(d.rate_21k||0)))+'/গ্রা';
      if(G('rBar18'))G('rBar18').textContent='৳'+fmt(Math.round(parseFloat(d.rate_18k||0)))+'/গ্রা';
      if(G('rBarDate'))G('rBarDate').textContent='📅 '+(d.date||'');
    }
    calcGrand();
  }).catch(function(){if(G('rBar22'))G('rBar22').textContent='লোড ব্যর্থ';});
}

/* ===== CASH ACCOUNTS — FIXED ✅ ===== */
function loadCashAccounts(){
  fetch('/api/cash/get_accounts.php',{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    var sel=G('mCash');
    sel.innerHTML='<option value="">— select করুন —</option>';
    /* ✅ res.success + res.data.accounts + account_name + current_balance */
    var list=(res&&res.success&&res.data&&res.data.accounts)?res.data.accounts:[];
    if(!list.length){
      sel.innerHTML='<option value="">কোনো একাউন্ট নেই</option>';
      return;
    }
    list.forEach(function(a){
      var o=document.createElement('option');
      o.value=a.id;
      o.textContent=a.account_name+' (৳'+fmt(Math.round(a.current_balance))+')';
      sel.appendChild(o);
    });
  }).catch(function(){
    G('mCash').innerHTML='<option value="">লোড ব্যর্থ</option>';
  });
}

/* ===== PARTY SEARCH — FIXED ✅ ===== */
function onPartyFocus(){
  var q=G('partySearch').value.trim();
  if(q.length>=1)onPartySearch();
  else{G('partyDD').style.display='flex';G('partyResults').innerHTML='<div class="party-loading">⌨️ নাম বা ফোন টাইপ করুন...</div>';}
}
function onPartySearch(){
  clearTimeout(partyDebounce);
  var q=G('partySearch').value.trim();
  if(q.length<1){G('partyDD').style.display='none';return;}
  G('partyDD').style.display='flex';
  G('partyResults').innerHTML='<div class="party-loading">🔍 খুঁজছি...</div>';
  partyDebounce=setTimeout(function(){runPartySearch(q);},300);
}
function runPartySearch(q){
  fetch('/api/parties/get_parties.php?search='+encodeURIComponent(q)+'&limit=20',{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    /* ✅ res.success + res.data.parties */
    var list=(res&&res.success&&res.data&&res.data.parties)?res.data.parties:[];
    if(!list.length){
      G('partyResults').innerHTML='<div class="party-empty">😕 কোনো পার্টি পাওয়া যায়নি<br><span style="font-size:10px">নিচে থেকে নতুন যোগ করুন</span></div>';
      return;
    }
    var q2=G('partySearch').value.trim(),html='';
    list.forEach(function(p){
      var tags='';
      if(+p.is_customer)tags+='<span class="tg c">গ্রাহক</span>';
      if(+p.is_supplier)tags+='<span class="tg s">সাপ্লায়ার</span>';
      if(+p.is_pledge)tags+='<span class="tg p">বন্ধক</span>';
      var pn=esc(p.name||''),ph=esc(p.phone||''),ad=esc(p.address||'');
      var bal=+p.balance||0,balInfo='';
      if(bal>0)balInfo+=' | পাওনা: ৳'+fmt(bal);
      else if(bal<0)balInfo+=' | দেনা: ৳'+fmt(Math.abs(bal));
      html+='<div class="party-item" onclick="selectParty('+p.id+',\''+pn.replace(/\\/g,'\\\\').replace(/'/g,"\\'")+'\',\''+ph.replace(/'/g,"\\'")+'\')">'+
        '<div class="pn">'+hl(p.name,q2)+'</div>'+
        '<div class="pp">'+(ph?'📞 <b>'+ph+'</b>':'')+(ad?(ph?' | ':'')+'📍 '+ad:'')+balInfo+'</div>'+
        (tags?'<div class="pt">'+tags+'</div>':'')+
      '</div>';
    });
    G('partyResults').innerHTML=html;
  }).catch(function(){
    G('partyResults').innerHTML='<div class="party-empty" style="color:var(--red)">❌ সার্চ ব্যর্থ</div>';
  });
}
function selectParty(id,name,phone){
  G('mParty').value=id;
  G('pselName').textContent=name;
  G('pselPhone').textContent=phone?'📞 '+phone:'';
  G('partySearch').style.display='none';
  G('partyDD').style.display='none';
  G('partySelected').style.display='flex';
}
function clearParty(){
  G('mParty').value='';G('partySearch').value='';
  G('partySearch').style.display='block';
  G('partySelected').style.display='none';
  G('partyDD').style.display='none';
  setTimeout(function(){G('partySearch').focus();},50);
}
document.addEventListener('click',function(e){
  var w=G('partyWrap');if(w&&!w.contains(e.target))G('partyDD').style.display='none';
});

/* ===== STATUS / HOLD / KARAT / QUICK ===== */
function setStatus(btn){
  document.querySelectorAll('.sbtn').forEach(function(b){b.classList.remove('active');});
  btn.classList.add('active');CUR_STATUS=btn.dataset.s;liveSearch();
}
function setHold(btn){
  document.querySelectorAll('.hbtn').forEach(function(b){b.classList.remove('on');});
  btn.classList.add('on');SEL_HOLD=btn.dataset.h;
  var box=G('lockerSelectBox');
  if(SEL_HOLD==='LOCKER'){box.classList.add('show');loadLockerOptions();}
  else{box.classList.remove('show');G('mLockerId').value='';}
}
function loadLockerOptions(){
  var sel=G('mLockerId');sel.innerHTML='<option value="">লোড হচ্ছে...</option>';
  fetch('/api/lockers/get_lockers.php?status=active',{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    sel.innerHTML='<option value="">— লকার select করুন —</option>';
    var list=(res.success&&res.data&&res.data.length)?res.data:[];
    if(!list.length){sel.innerHTML='<option value="">কোনো সক্রিয় লকার নেই</option>';return;}
    list.forEach(function(l){
      var o=document.createElement('option');
      o.value=l.id;
      o.textContent=l.name+(l.phone?' | '+l.phone:'')+(l.pledge_count>0?' ('+l.pledge_count+'টি)':'');
      sel.appendChild(o);
    });
  }).catch(function(){sel.innerHTML='<option value="">লোড ব্যর্থ</option>';});
}
function setKarat(btn){
  G('advPanel').querySelectorAll('.kpill').forEach(function(b){b.classList.remove('on');});
  btn.classList.add('on');CUR_KARAT=btn.dataset.k;liveSearch();
}
function setQuickTab(btn){
  var was=btn.classList.contains('on');
  document.querySelectorAll('.qtab').forEach(function(b){b.classList.remove('on');});
  if(was){CUR_QUICK='';}else{btn.classList.add('on');CUR_QUICK=btn.dataset.q;}
  loadList();
}
function toggleAdv(){G('advBtn').classList.toggle('on');G('advPanel').classList.toggle('on');}
function liveSearch(){clearTimeout(listDebounce);listDebounce=setTimeout(loadList,400);}
function resetFilters(){
  G('searchInput').value='';G('pledgeCodeInput').value='';G('barcodeInput').value='';
  G('fromDate').value='2021-01-01';G('toDate').value='<?php echo $date_today;?>';
  G('loanMin').value='';G('loanMax').value='';G('sortBy').value='date_desc';
  document.querySelectorAll('.sbtn').forEach(function(b){b.classList.remove('active');});
  document.querySelector('.sbtn[data-s="OPEN"]').classList.add('active');CUR_STATUS='OPEN';
  document.querySelectorAll('.kpill').forEach(function(b){b.classList.remove('on');});
  document.querySelector('.kpill[data-k=""]').classList.add('on');CUR_KARAT='';
  document.querySelectorAll('.qtab').forEach(function(b){b.classList.remove('on');});
  CUR_QUICK='';loadList();
}

/* ===== QUICK ADD PARTY ===== */
function showQpAlert(msg,type){var b=G('qpAlert');b.textContent=msg;b.className='malert '+type;b.style.display='block';if(type==='ok')setTimeout(function(){b.style.display='none';},2500);}
function openQuickAdd(){
  var q=G('partySearch').value.trim();
  var isPhone=/^[0-9+\- ]+$/.test(q)&&q.replace(/[^0-9]/g,'').length>=4;
  G('qpName').value=isPhone?'':q;G('qpPhone').value=isPhone?q:'';G('qpAddress').value='';
  G('qpAlert').style.display='none';G('qpModal').style.display='block';
  setTimeout(function(){(isPhone?G('qpName'):G('qpPhone')).focus();},100);
}
function closeQuickAdd(){G('qpModal').style.display='none';}
function saveQuickParty(){
  var btn=G('qpSaveBtn');
  var name=G('qpName').value.trim(),phone=G('qpPhone').value.trim(),address=G('qpAddress').value.trim();
  if(!name)return showQpAlert('❌ নাম দিন','err');
  if(!phone)return showQpAlert('❌ ফোন নম্বর দিন','err');
  btn.disabled=true;btn.textContent='⏳ সেভ হচ্ছে...';
  fetch('/api/parties/add_party.php',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',
    body:JSON.stringify({name:name,phone:phone,address:address,is_customer:1,is_supplier:0,is_pledge:1,balance:0,gold_balance:0,opening_receivable:0,opening_payable:0})
  }).then(function(r){return r.json();}).then(function(res){
    if(res&&res.success){
      var pid=(res.data&&res.data.party_id)?res.data.party_id:0;
      showQpAlert('✅ পার্টি যোগ হয়েছে!','ok');
      setTimeout(function(){closeQuickAdd();if(pid)selectParty(pid,name,phone);},900);
    }else{showQpAlert('❌ '+(res&&res.message?res.message:'সমস্যা হয়েছে'),'err');}
    btn.disabled=false;btn.textContent='+ যোগ করুন';
  }).catch(function(){showQpAlert('❌ নেটওয়ার্ক সমস্যা','err');btn.disabled=false;btn.textContent='+ যোগ করুন';});
}

/* ===== ITEMS ===== */
function addItem(){
  itemCount++;var n=itemCount;
  var div=document.createElement('div');div.className='item-card';div.id='item-'+n;
  div.innerHTML=
    '<div class="item-card-head"><span class="item-num">📦 আইটেম '+n+'</span>'+
    (n>1?'<button class="item-del" type="button" onclick="removeItem('+n+')">✕ বাদ দিন</button>':'')+
    '</div>'+
    '<div class="g2" style="margin-bottom:8px">'+
      '<div class="mfield"><label>আইটেমের নাম *</label><input type="text" id="iName'+n+'" placeholder="আংটি, চেইন, বালা..."></div>'+
      '<div class="mfield"><label>পরিমাণ (পিস)</label><input type="number" id="iQty'+n+'" value="1" min="1" step="1"></div>'+
    '</div>'+
    '<div class="mfield" style="margin-bottom:8px"><label>ক্যারেট</label>'+
      '<div class="krow" id="krow'+n+'">'+
        '<button class="kbtn" type="button" data-k="24K" data-p="99.9" data-d="0" onclick="setIK(this,'+n+')">২৪K</button>'+
        '<button class="kbtn on" type="button" data-k="22K" data-p="91.6" data-d="0" onclick="setIK(this,'+n+')">২২K</button>'+
        '<button class="kbtn" type="button" data-k="21K" data-p="87.5" data-d="0" onclick="setIK(this,'+n+')">২১K</button>'+
        '<button class="kbtn" type="button" data-k="18K" data-p="75.0" data-d="0" onclick="setIK(this,'+n+')">১৮K</button>'+
        '<button class="kbtn" type="button" data-k="SANATAN" data-p="83.0" data-d="3" onclick="setIK(this,'+n+')">সনাতন</button>'+
      '</div>'+
    '</div>'+
    '<div class="mfield" style="margin-bottom:6px"><label>ওজন পদ্ধতি</label>'+
      '<div class="wtrow">'+
        '<button class="wtab on" type="button" onclick="setIW(this,'+n+',\'gram\')">গ্রাম</button>'+
        '<button class="wtab" type="button" onclick="setIW(this,'+n+',\'bhari\')">ভরি/আনা/রতি</button>'+
      '</div>'+
    '</div>'+
    '<div id="wG'+n+'" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:8px">'+
      '<div class="mfield"><label>Gross (গ্রাম) *</label><input type="number" id="iGross'+n+'" placeholder="0.000" step="0.001" min="0" oninput="calcI('+n+')"></div>'+
      '<div class="mfield"><label>Deduction (%)</label><input type="number" id="iDed'+n+'" value="0" step="0.01" oninput="calcI('+n+')"></div>'+
      '<div class="mfield"><label>Purity (%)</label><input type="number" id="iPur'+n+'" value="91.6" readonly></div>'+
    '</div>'+
    '<div id="wB'+n+'" style="display:none;margin-bottom:8px">'+
      '<div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:6px;margin-bottom:6px">'+
        '<div class="mfield"><label>ভরি</label><input type="number" id="iVori'+n+'" min="0" step="1" placeholder="0" oninput="onBhari('+n+')"></div>'+
        '<div class="mfield"><label>আনা</label><input type="number" id="iAna'+n+'" min="0" max="15" step="1" placeholder="0" oninput="onBhari('+n+')"></div>'+
        '<div class="mfield"><label>রতি</label><input type="number" id="iRoti'+n+'" min="0" max="5" step="1" placeholder="0" oninput="onBhari('+n+')"></div>'+
        '<div class="mfield"><label>পয়েন্ট</label><input type="number" id="iPoint'+n+'" min="0" max="9" step="1" placeholder="0" oninput="onBhari('+n+')"></div>'+
      '</div>'+
      '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px">'+
        '<div class="mfield"><label>= গ্রাম</label><input type="text" id="iBG'+n+'" readonly></div>'+
        '<div class="mfield"><label>Deduction (%)</label><input type="number" id="iDedB'+n+'" value="0" step="0.01" oninput="syncDed('+n+')"></div>'+
        '<div class="mfield"><label>Purity (%)</label><input type="number" id="iPurB'+n+'" value="91.6" readonly></div>'+
      '</div>'+
    '</div>'+
    '<div class="mfield" style="margin-bottom:8px"><label>বিশেষ নোট (ঐচ্ছিক)</label><input type="text" id="iRem'+n+'" placeholder="পাথর আছে, ভাঙা..."></div>'+
    '<div class="item-total">নিট ওজন: <span id="iNet'+n+'">—</span> &nbsp;|&nbsp; সোনার মূল্য: <span id="iVal'+n+'">—</span></div>';
  G('itemsContainer').appendChild(div);calcGrand();
}
function removeItem(n){var el=G('item-'+n);if(el)el.remove();calcGrand();}
function setIK(btn,n){
  G('krow'+n).querySelectorAll('.kbtn').forEach(function(b){b.classList.remove('on');});btn.classList.add('on');
  var p=btn.dataset.p,d=btn.dataset.d;
  if(G('iPur'+n))G('iPur'+n).value=p;if(G('iDed'+n))G('iDed'+n).value=d;
  if(G('iPurB'+n))G('iPurB'+n).value=p;if(G('iDedB'+n))G('iDedB'+n).value=d;
  calcI(n);
}
function setIW(btn,n,mode){
  btn.parentNode.querySelectorAll('.wtab').forEach(function(b){b.classList.remove('on');});btn.classList.add('on');
  G('wG'+n).style.display=mode==='gram'?'grid':'none';
  G('wB'+n).style.display=mode==='bhari'?'block':'none';
  calcI(n);
}
function onBhari(n){
  var v=parseFloat(G('iVori'+n)&&G('iVori'+n).value||0),
      a=parseFloat(G('iAna'+n)&&G('iAna'+n).value||0),
      r=parseFloat(G('iRoti'+n)&&G('iRoti'+n).value||0),
      pt=parseFloat(G('iPoint'+n)&&G('iPoint'+n).value||0);
  var g=v*BHARI+a*ANA+r*ROTI+pt*POINT;
  if(G('iBG'+n))G('iBG'+n).value=g.toFixed(3)+' গ্রা';
  if(G('iGross'+n))G('iGross'+n).value=g.toFixed(3);
  calcI(n);
}
function syncDed(n){if(G('iDed'+n))G('iDed'+n).value=G('iDedB'+n)&&G('iDedB'+n).value||0;calcI(n);}
function calcI(n){
  var gross=parseFloat(G('iGross'+n)&&G('iGross'+n).value||0),
      pur=parseFloat(G('iPur'+n)&&G('iPur'+n).value||91.6),
      ded=parseFloat(G('iDed'+n)&&G('iDed'+n).value||0);
  var aPur=Math.max(0,pur-ded),net=gross*(aPur/100),val=net*RATE_G;
  var vB=Math.floor(net/BHARI),vA=Math.floor((net%BHARI)/ANA),vR=Math.floor(((net%BHARI)%ANA)/ROTI);
  if(G('iNet'+n))G('iNet'+n).textContent=net>0?(net.toFixed(3)+' গ্রা ('+vB+'ভ '+vA+'আ '+vR+'র)'):'—';
  if(G('iVal'+n))G('iVal'+n).textContent=val>0?'৳'+fmt(Math.round(val)):'—';
  calcGrand();
}
function calcGrand(){
  var total=0;
  G('itemsContainer').querySelectorAll('.item-card').forEach(function(card){
    var n=card.id.replace('item-','');
    var gross=parseFloat(G('iGross'+n)&&G('iGross'+n).value||0),
        pur=parseFloat(G('iPur'+n)&&G('iPur'+n).value||91.6),
        ded=parseFloat(G('iDed'+n)&&G('iDed'+n).value||0);
    total+=gross*(Math.max(0,pur-ded)/100)*RATE_G;
  });
  G('grandTotal').textContent='৳ '+fmt(Math.round(total));
  G('grandItems').textContent=G('itemsContainer').querySelectorAll('.item-card').length+'টি আইটেম';
}
function getItems(){
  var items=[];
  G('itemsContainer').querySelectorAll('.item-card').forEach(function(card){
    var n=card.id.replace('item-','');
    var gross=parseFloat(G('iGross'+n)&&G('iGross'+n).value||0),
        pur=parseFloat(G('iPur'+n)&&G('iPur'+n).value||91.6),
        ded=parseFloat(G('iDed'+n)&&G('iDed'+n).value||0);
    var aPur=Math.max(0,pur-ded),net=gross*(aPur/100),val=net*RATE_G;
    var kbtn=G('krow'+n)&&G('krow'+n).querySelector('.kbtn.on');
    items.push({
      item_name:G('iName'+n)&&G('iName'+n).value.trim()||('আইটেম '+n),
      quantity:parseInt(G('iQty'+n)&&G('iQty'+n).value||1),
      karat:kbtn?kbtn.dataset.k:'22K',
      system_purity:pur,deduction:ded,
      actual_purity:Math.round(aPur*100)/100,
      gross_weight:Math.round(gross*1000)/1000,
      net_weight:Math.round(net*1000)/1000,
      estimated_value:Math.round(val*100)/100,
      remarks:G('iRem'+n)&&G('iRem'+n).value.trim()||''
    });
  });
  return items;
}

/* ===== MODAL ===== */
function openModal(){
  G('pledgeModal').style.display='block';G('mAlert').style.display='none';
  G('mDate').value='<?php echo $date_today;?>';
  G('itemsContainer').innerHTML='';itemCount=0;addItem();
  clearParty();
  G('lockerSelectBox').classList.remove('show');
  G('mLockerId').innerHTML='<option value="">— লকার select করুন —</option>';
  document.querySelectorAll('.hbtn').forEach(function(b){b.classList.remove('on');});
  document.querySelector('.hbtn.showroom').classList.add('on');
  SEL_HOLD='SHOWROOM';
  loadCashAccounts();
  loadGoldRate();
}
function closeModal(){
  G('pledgeModal').style.display='none';
  G('mLoan').value='';G('mRate').value='2';G('mNote').value='';
  G('mBarcode').value='';G('mLocNote').value='';
  G('itemsContainer').innerHTML='';itemCount=0;clearParty();
  G('lockerSelectBox').classList.remove('show');
}

/* ===== SAVE PLEDGE ===== */
function savePledge(){
  var btn=G('mSaveBtn'),items=getItems();
  if(!parseInt(G('mParty').value||'0'))return showAlert('❌ গ্রাহক select করুন','err');
  if(!G('mDate').value)return showAlert('❌ তারিখ দিন','err');
  if(!items.length)return showAlert('❌ কমপক্ষে একটি আইটেম দিন','err');
  if(items.some(function(it){return it.gross_weight<=0;}))return showAlert('❌ সব আইটেমের ওজন দিন','err');
  if(parseFloat(G('mLoan').value||'0')<=0)return showAlert('❌ ঋণের পরিমাণ দিন','err');
  if(!parseInt(G('mCash').value||'0'))return showAlert('❌ Cash account select করুন','err');
  var lockerId=0;
  if(SEL_HOLD==='LOCKER'){
    lockerId=parseInt(G('mLockerId').value||'0');
    if(!lockerId)return showAlert('❌ লকার select করুন','err');
  }
  btn.disabled=true;btn.textContent='⏳ সেভ হচ্ছে...';
  fetch('/api/pawn/pledge_add.php',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',
    body:JSON.stringify({
      party_id:parseInt(G('mParty').value),
      pledge_date:G('mDate').value,
      loan_amount:parseFloat(G('mLoan').value),
      interest_rate:parseFloat(G('mRate').value||'0'),
      cash_account_id:parseInt(G('mCash').value),
      holding_status:SEL_HOLD,
      locker_id:lockerId||null,
      note:G('mNote').value.trim(),
      manual_barcode:G('mBarcode').value.trim(),
      location_note:G('mLocNote').value.trim(),
      items:items
    })
  }).then(function(r){return r.text();}).then(function(txt){
    var res;try{res=JSON.parse(txt);}catch(e){showAlert('❌ API error: '+txt.substring(0,80),'err');btn.disabled=false;btn.textContent='✅ সেভ করুন';return;}
    if(res&&res.success){
      showAlert('✅ সেভ হয়েছে! কোড: '+(res.data&&res.data.pledge_code?res.data.pledge_code:'—'),'ok');
      loadList();setTimeout(closeModal,2500);
    }else{showAlert('❌ '+(res.message||'Error'),'err');}
    btn.disabled=false;btn.textContent='✅ সেভ করুন';
  }).catch(function(e){showAlert('❌ Network error: '+e.message,'err');btn.disabled=false;btn.textContent='✅ সেভ করুন';});
}

/* ===== LOAD LIST — FIXED ✅ ===== */
function loadList(){
  var from=G('fromDate').value||'2021-01-01',
      to=G('toDate').value||'<?php echo $date_today;?>',
      search=G('searchInput').value.trim(),
      pcode=G('pledgeCodeInput').value.trim(),
      bcode=G('barcodeInput').value.trim(),
      lmin=G('loanMin').value.trim(),
      lmax=G('loanMax').value.trim(),
      sortBy=G('sortBy').value||'date_desc';
  G('pledgeList').innerHTML='<div class="empty">🔄 লোড হচ্ছে...</div>';
  G('listCount').textContent='';
  var url='/api/pawn/pledge_list.php?limit=300'
    +'&from_date='+encodeURIComponent(from)
    +'&to_date='+encodeURIComponent(to)
    +'&search='+encodeURIComponent(search)
    +'&pledge_code='+encodeURIComponent(pcode)
    +'&barcode='+encodeURIComponent(bcode)
    +'&status='+encodeURIComponent(CUR_STATUS)
    +'&karat='+encodeURIComponent(CUR_KARAT)
    +'&quick_tab='+encodeURIComponent(CUR_QUICK)
    +'&sort_by='+encodeURIComponent(sortBy);
  if(lmin!=='')url+='&loan_min='+encodeURIComponent(lmin);
  if(lmax!=='')url+='&loan_max='+encodeURIComponent(lmax);
  fetch(url,{credentials:'same-origin'}).then(function(r){return r.text();}).then(function(txt){
    var res;try{res=JSON.parse(txt);}catch(e){G('pledgeList').innerHTML='<div class="empty" style="color:var(--red)">API parse error</div>';return;}
    if(!res||!res.success||!res.data){G('pledgeList').innerHTML='<div class="empty" style="color:var(--red)">লোড ব্যর্থ: '+(res&&res.message?res.message:'')+'</div>';return;}
    var rows=res.data.pledges||[],sum=res.data.summary||{};
    G('sumE').textContent=sum.total_entries||0;
    G('sumL').textContent=tk(sum.total_loan_amount||0);
    G('sumO').textContent=tk(sum.total_outstanding||0);
    G('sumG').textContent=tk(sum.total_gold_value||0);
    G('sumP').textContent=tk(sum.total_principal_paid||0);
    G('sumI').textContent=tk(sum.total_interest_paid||0);
    G('qCnt_over_90days').textContent=(sum.count_over_90days||0)+'টি';
    G('qCnt_risky').textContent=(sum.count_risky||0)+'টি';
    G('listCount').textContent='('+rows.length+'টি)';
    if(!rows.length){G('pledgeList').innerHTML='<div class="empty">😕 কোনো রেকর্ড নেই<br><span style="font-size:11px">ফিল্টার পরিবর্তন করে দেখুন</span></div>';return;}
    var html='';
    rows.forEach(function(p){
      var st=(p.status||'').toUpperCase(),hs=(p.holding_status||'').toUpperCase();
      var days=parseInt(p.days_elapsed||0,10),margin=parseFloat(p.safety_margin||0);
      var isOver90=(st!=='CLOSED'&&days>=90),isRisky=(st!=='CLOSED'&&margin<0);
      var cc='pcard';
      if(st==='CLOSED')cc+=' returned';
      else if(isRisky)cc+=' risky';
      else if(isOver90)cc+=' over90';
      else if(hs==='LOCKER')cc+=' locker';
      var bg=st==='CLOSED'?'<span class="badge returned">✅ ফেরত</span>':(hs==='LOCKER'?'<span class="badge locker">🔐 লকার</span>':'<span class="badge local">🏪 শোরুম</span>');
      var riskCorner='';
      if(isRisky||isOver90){
        riskCorner='<div class="risk-corner">';
        if(isRisky)riskCorner+='<span class="risk-tag r-risky">⚠️ ঝুঁকি</span>';
        if(isOver90)riskCorner+='<span class="risk-tag r-over">⏰ '+days+'দিন</span>';
        riskCorner+='</div>';
      }
      html+='<div class="'+cc+'">'+riskCorner;
      html+='<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:6px;padding-right:'+(isRisky||isOver90?'80px':'0')+'">';
      html+='<strong style="font-size:15px;color:var(--text)">'+hl(p.party_name||'—',search)+'</strong>';
      html+='<span style="color:var(--gold);font-size:12px;font-weight:800">'+hl(p.pledge_code||'—',pcode)+'</span>';
      html+='</div>'+bg;
      if(p.locker_name)html+='<div style="font-size:11px;color:var(--blue);margin-top:3px">🔐 '+esc(p.locker_name)+'</div>';
      if(p.party_phone)html+='<div style="font-size:11px;color:var(--sub);margin-top:3px">📞 '+hl(p.party_phone,search)+'</div>';
      html+='<div style="font-size:11px;color:var(--sub);margin-top:2px">📅 '+(p.pledge_date||'')+(days>0?' · '+days+' দিন আগে':'')+'</div>';
      if(p.manual_barcode)html+='<div style="font-size:11px;color:var(--gold);margin-top:2px">📦 '+hl(p.manual_barcode,bcode)+'</div>';
      if(p.note)html+='<div style="font-size:11px;color:var(--sub);margin-top:2px;font-style:italic">📝 '+hl(p.note,bcode)+'</div>';
      html+='<div class="cg2">';
      html+='<div class="cell"><div class="k">ঋণ</div><div class="v" style="color:var(--red)">'+tk(p.loan_amount)+'</div></div>';
      html+='<div class="cell"><div class="k">বাকি</div><div class="v" style="color:var(--red)">'+tk(p.outstanding_principal)+'</div></div>';
      html+='<div class="cell"><div class="k">সোনার মূল্য</div><div class="v" style="color:var(--gold)">'+tk(p.gold_value)+'</div></div>';
      html+='<div class="cell"><div class="k">নিরাপত্তা মার্জিন</div><div class="v" style="color:'+(margin>=0?'var(--green)':'var(--red)')+'">'+tk(margin)+'</div></div>';
      html+='</div><div class="actions">';
      html+='<button class="btn-sm btn-view" onclick="goView('+p.id+')">📋 Details</button>';
      if(st!=='CLOSED')html+='<button class="btn-sm btn-pay" onclick="goPay('+p.id+')">💵 Payment</button>';
      html+='</div></div>';
    });
    G('pledgeList').innerHTML=html;
  }).catch(function(e){G('pledgeList').innerHTML='<div class="empty" style="color:var(--red)">Error: '+e.message+'</div>';});
}

function goView(id){window.location.href='/pledge_view.php?pledge_id='+id;}
function goPay(id){window.location.href='/pledge_payment.php?pledge_id='+id;}

loadGoldRate();
loadList();
</script>
</body>
</html>
