<?php
/**
 * pledge_interest.php  (root page)
 * Upload: /home/jewellersbd/public_html/erp.jewellersbd.com/pledge_interest.php
 * সব OPEN বন্ধকের সুদ due list
 */
require_once __DIR__ . '/config/session.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['user_id'])) { header('Location: ui/login.html'); exit; }
$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">
<title>বন্ধক সুদ হিসাব</title>
<style>
:root{--navy:#1e2a3b;--navy2:#243447;--gold:#d4a843;--gold-lt:#fef3c7;--gold-dk:#92710c;--green:#22c55e;--green-lt:#dcfce7;--red:#ef4444;--red-lt:#fee2e2;--orange:#f97316;--orange-lt:#fff7ed;--blue:#3b82f6;--blue-lt:#eff6ff;--text:#1e293b;--muted:#64748b;--border:#e2e8f0;--surface:#f8fafc;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--surface);color:var(--text);font-size:14px;}
.topbar{background:var(--navy);padding:0 16px;height:52px;display:flex;align-items:center;gap:10px;position:sticky;top:0;z-index:100;border-bottom:2px solid var(--gold);}
.topbar h1{font-size:15px;font-weight:700;color:#fff;flex:1;}
.topbar a{color:var(--gold);text-decoration:none;font-size:12px;font-weight:600;padding:5px 10px;border:1px solid rgba(212,168,67,.4);border-radius:6px;}
.container{max-width:720px;margin:0 auto;padding:14px 12px 40px;}

/* Summary top */
.summary-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:14px;}
.sum-card{background:#fff;border:1px solid var(--border);border-radius:10px;padding:12px 14px;text-align:center;}
.sum-card.full{grid-column:1/-1;}
.sum-label{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.5px;}
.sum-val{font-size:20px;font-weight:800;margin-top:3px;}
.sum-card.danger .sum-val{color:var(--red);}
.sum-card.gold   .sum-val{color:var(--gold-dk);}
.sum-card.blue   .sum-val{color:var(--blue);}
.sum-card.purple .sum-val{color:#7c3aed;}

/* Filter bar */
.filter-bar{display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;align-items:center;}
.filter-bar select,.filter-bar input{padding:8px 10px;border:1.5px solid var(--border);border-radius:7px;font-size:13px;color:var(--text);background:#fff;outline:none;}
.filter-bar input{flex:1;min-width:120px;}
.filter-bar select:focus,.filter-bar input:focus{border-color:var(--gold);}

/* Pledge cards */
.pledge-card{background:#fff;border:1px solid var(--border);border-radius:10px;margin-bottom:10px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.05);}
.pledge-card.overdue{border-left:4px solid var(--red);}
.pledge-card.normal{border-left:4px solid var(--green);}
.pc-header{padding:10px 14px;display:flex;justify-content:space-between;align-items:flex-start;gap:8px;}
.pc-name{font-size:15px;font-weight:700;color:var(--text);}
.pc-code{font-size:11px;color:var(--muted);}
.pc-phone{font-size:12px;color:var(--muted);margin-top:1px;}
.pc-badge{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700;white-space:nowrap;}
.badge-overdue{background:var(--red-lt);color:#b91c1c;}
.badge-ok{background:var(--green-lt);color:#15803d;}
.badge-warn{background:var(--orange-lt);color:#c2410c;}

.pc-body{padding:0 14px 12px;}
.pc-grid{display:grid;grid-template-columns:1fr 1fr;gap:6px 10px;margin-bottom:10px;}
.pc-item label{font-size:10px;color:var(--muted);display:block;text-transform:uppercase;letter-spacing:.3px;}
.pc-item .v{font-size:13px;font-weight:600;}
.v-red{color:var(--red);}
.v-gold{color:var(--gold-dk);}
.v-green{color:#15803d;}
.v-purple{color:#7c3aed;}

/* Interest highlight */
.interest-row{background:var(--gold-lt);border:1px solid #fcd34d;border-radius:8px;padding:10px 12px;display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;}
.ir-label{font-size:11px;color:var(--gold-dk);font-weight:700;}
.ir-amount{font-size:18px;font-weight:800;color:var(--gold-dk);}

/* Actions */
.pc-actions{display:flex;gap:8px;}
.btn-pay{flex:1;padding:8px;background:var(--navy);color:#fff;border:none;border-radius:7px;font-size:13px;font-weight:700;cursor:pointer;border-bottom:2px solid var(--gold);text-decoration:none;text-align:center;display:block;}
.btn-close-sm{padding:8px 12px;background:var(--red);color:#fff;border:none;border-radius:7px;font-size:13px;font-weight:700;cursor:pointer;text-decoration:none;text-align:center;display:block;}

/* Loading/empty */
.loading{text-align:center;padding:40px;color:var(--muted);}
.empty{text-align:center;padding:40px;color:var(--muted);font-size:13px;}

/* Overdue alert */
.overdue-alert{background:var(--red-lt);border:1px solid #fca5a5;border-left:4px solid var(--red);border-radius:8px;padding:11px 14px;margin-bottom:12px;font-size:13px;color:#b91c1c;font-weight:600;}
</style>
</head>
<body>
<div class="topbar">
  <span style="font-size:18px">📈</span>
  <h1>বন্ধক সুদ হিসাব</h1>
  <a href="ui/pledges.html">তালিকা</a>
</div>

<div class="container">

  <!-- Summary -->
  <div class="summary-grid" id="summary-grid">
    <div class="sum-card blue"><div class="sum-label">মোট OPEN বন্ধক</div><div class="sum-val" id="s-count">—</div></div>
    <div class="sum-card danger"><div class="sum-label">মোট বকেয়া মূল</div><div class="sum-val" id="s-principal">—</div></div>
    <div class="sum-card gold"><div class="sum-label">মোট হিসাব করা সুদ</div><div class="sum-val" id="s-interest">—</div></div>
    <div class="sum-card purple full"><div class="sum-label">সর্বমোট আদায়যোগ্য</div><div class="sum-val" id="s-total">—</div></div>
  </div>

  <!-- Filters -->
  <div class="filter-bar">
    <input type="text" id="search" placeholder="🔍 গ্রাহক বা কোড খুঁজুন">
    <select id="sort-select">
      <option value="days_desc">পুরনো আগে</option>
      <option value="interest_desc">বেশি সুদ আগে</option>
      <option value="amount_desc">বেশি মূল আগে</option>
      <option value="days_asc">নতুন আগে</option>
    </select>
    <select id="filter-overdue">
      <option value="">সব</option>
      <option value="overdue">শুধু overdue</option>
      <option value="ok">সময়মতো</option>
    </select>
  </div>

  <div id="overdue-alert" class="overdue-alert" style="display:none"></div>
  <div id="pledge-list"><div class="loading">⏳ লোড হচ্ছে…</div></div>

</div>

<script>
const BASE = '<?= $base_url ?>';
let allPledges = [];

function fmt(n) {
    return '৳' + parseFloat(n).toLocaleString('en-BD', {minimumFractionDigits:0, maximumFractionDigits:0});
}
function fmt2(n) {
    return '৳' + parseFloat(n).toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2});
}

function toVori(g) {
    const V=11.664, v=Math.floor(g/V); const r=g-(v*V);
    const a=Math.floor(r/(V/16)); const r2=r-(a*(V/16));
    const ro=Math.floor(r2/(V/96));
    let s=''; if(v>0)s+=v+' ভরি '; if(a>0)s+=a+' আনা '; if(ro>0)s+=ro+' রতি';
    return s.trim()||'০';
}

function loadData() {
    const sort = document.getElementById('sort-select').value;
    fetch(BASE + '/api/pawn/pledge_interest.php?sort=' + sort)
        .then(r=>r.json())
        .then(data => {
            if (!data.success) { document.getElementById('pledge-list').innerHTML='<div class="empty">ডেটা লোড হয়নি।</div>'; return; }
            allPledges = data.pledges;

            // Summary
            document.getElementById('s-count').textContent     = data.count + ' টি';
            document.getElementById('s-principal').textContent = fmt(data.grand_total_principal);
            document.getElementById('s-interest').textContent  = fmt(data.grand_total_interest);
            document.getElementById('s-total').textContent     = fmt(data.grand_total_due);

            // Overdue alert
            const overdue = allPledges.filter(p=>p.is_overdue);
            const oa = document.getElementById('overdue-alert');
            if (overdue.length > 0) {
                oa.style.display='block';
                oa.textContent = '⚠️ ' + overdue.length + ' টি বন্ধকের ৩০ দিনের বেশি সুদ দেওয়া হয়নি! দ্রুত যোগাযোগ করুন।';
            } else { oa.style.display='none'; }

            renderList();
        })
        .catch(()=>{ document.getElementById('pledge-list').innerHTML='<div class="empty">নেটওয়ার্ক সমস্যা।</div>'; });
}

function renderList() {
    const q      = document.getElementById('search').value.toLowerCase().trim();
    const filter = document.getElementById('filter-overdue').value;

    let list = allPledges.filter(p => {
        if (q && !p.party_name.toLowerCase().includes(q) && !p.pledge_code.toLowerCase().includes(q) && !p.party_phone.includes(q)) return false;
        if (filter === 'overdue' && !p.is_overdue) return false;
        if (filter === 'ok'      &&  p.is_overdue) return false;
        return true;
    });

    if (list.length === 0) {
        document.getElementById('pledge-list').innerHTML = '<div class="empty">কোনো বন্ধক পাওয়া যায়নি।</div>';
        return;
    }

    let html = '';
    list.forEach(p => {
        const overdueCls = p.is_overdue ? 'overdue' : 'normal';
        let badgeHtml = '';
        if (p.is_overdue) {
            badgeHtml = `<span class="pc-badge badge-overdue">⚠️ ${p.days_since_payment} দিন বাকি</span>`;
        } else if (p.days_since_payment > 20) {
            badgeHtml = `<span class="pc-badge badge-warn">🔔 ${p.days_since_payment} দিন</span>`;
        } else {
            badgeHtml = `<span class="pc-badge badge-ok">✓ ঠিকঠাক</span>`;
        }

        const lastPay = p.last_payment_date
            ? new Date(p.last_payment_date).toLocaleDateString('bn-BD')
            : 'কোনো payment নেই';

        html += `
        <div class="pledge-card ${overdueCls}">
          <div class="pc-header">
            <div>
              <div class="pc-name">${p.party_name}</div>
              <div class="pc-code">${p.pledge_code} &nbsp;·&nbsp; ${p.karat}</div>
              <div class="pc-phone">${p.party_phone}</div>
            </div>
            ${badgeHtml}
          </div>
          <div class="pc-body">
            <div class="pc-grid">
              <div class="pc-item"><label>মূল ঋণ</label><span class="v">${fmt(p.loan_amount)}</span></div>
              <div class="pc-item"><label>বকেয়া মূল</label><span class="v v-red">${fmt(p.outstanding_principal)}</span></div>
              <div class="pc-item"><label>বন্ধক তারিখ</label><span class="v">${p.pledge_date}</span></div>
              <div class="pc-item"><label>মেয়াদ</label><span class="v">${p.days_elapsed} দিন (${p.months_elapsed} মাস)</span></div>
              <div class="pc-item"><label>ওজন</label><span class="v">${p.gross_weight.toFixed(3)}g / ${toVori(p.gross_weight)}</span></div>
              <div class="pc-item"><label>সুদের হার</label><span class="v">${p.interest_rate}% / মাস</span></div>
              <div class="pc-item"><label>শেষ payment</label><span class="v">${lastPay}</span></div>
              <div class="pc-item"><label>মোট payment</label><span class="v v-green">${fmt(p.total_interest_paid + p.total_principal_paid)}</span></div>
            </div>

            <div class="interest-row">
              <div>
                <div class="ir-label">📈 আজ পর্যন্ত সুদ</div>
                <div style="font-size:11px;color:var(--gold-dk)">${p.days_elapsed} দিন × ${p.interest_rate}% / মাস × ${fmt(p.outstanding_principal)}</div>
              </div>
              <div class="ir-amount">${fmt2(p.calc_interest)}</div>
            </div>

            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;background:var(--blue-lt);border-radius:7px;padding:8px 12px;">
              <span style="font-size:12px;font-weight:700;color:#1e40af">সর্বমোট বাকি</span>
              <span style="font-size:17px;font-weight:800;color:var(--blue)">${fmt2(p.total_due)}</span>
            </div>

            <div class="pc-actions">
              <a href="${BASE}/pledge_payment.php?pledge_id=${p.id}" class="btn-pay">💳 পেমেন্ট নিন</a>
              <a href="${BASE}/pledge_close.php?pledge_id=${p.id}" class="btn-close-sm">🔒 বন্ধ</a>
            </div>
          </div>
        </div>`;
    });
    document.getElementById('pledge-list').innerHTML = html;
}

// Event delegation
document.addEventListener('input', function(e) {
    if (e.target.id === 'search') renderList();
});
document.addEventListener('change', function(e) {
    if (e.target.id === 'sort-select')     loadData();
    if (e.target.id === 'filter-overdue')  renderList();
});

loadData();
</script>
</body>
</html>