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

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="color:red;padding:20px">pledge_id দেওয়া হয়নি।</p>');

$stmt = $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
");
$stmt->execute([$pledge_id]);
$pledge = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$pledge) die('<p style="color:red;padding:20px">বন্ধক পাওয়া যায়নি (ID: '.$pledge_id.')</p>');

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

$payments_stmt = $pdo->prepare("
    SELECT pp.*, ca.account_name
    FROM pawn_payments pp
    LEFT JOIN cash_accounts ca ON ca.id=pp.cash_account_id
    WHERE pp.pledge_id=?
    ORDER BY pp.payment_date DESC, pp.id DESC
");
$payments_stmt->execute([$pledge_id]);
$payment_history = $payments_stmt->fetchAll(PDO::FETCH_ASSOC);

function toVori(float $g): string {
    $VORI = 11.664;
    $v = floor($g / $VORI);
    $r = $g - ($v * $VORI);
    $a = floor($r / ($VORI / 16));
    $r2 = $r - ($a * ($VORI / 16));
    $ro = floor($r2 / ($VORI / 96));
    $p = [];
    if ($v > 0) $p[] = $v.' ভরি';
    if ($a > 0) $p[] = $a.' আনা';
    if ($ro > 0) $p[] = $ro.' রতি';
    return $p ? implode(' ', $p) : '০';
}

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

$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>লকার ভাড়া পেমেন্ট — <?= 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;
  --card:#111f35;
  --card2:#0a1525;
  --field:#081322;
  --border:#223858;
  --border2:#2d4a73;
  --gold:#f2c230;
  --gold2:#d4a843;
  --green:#22c55e;
  --red:#ef4444;
  --blue:#3b82f6;
  --cyan:#38bdf8;
  --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 20% 0%, rgba(242,194,48,.10), transparent 30%),
    radial-gradient(circle at 80% 20%, rgba(59,130,246,.12), transparent 30%),
    var(--bg);
  color:var(--text);
  font-size:14px;
  min-height:100vh;
  padding-bottom:30px;
}

.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-icon { font-size:22px; }

.topbar h1 {
  font-size:18px;
  font-weight:700;
  color:#fff;
  flex:1;
  letter-spacing:.2px;
}

.topbar a {
  color:var(--gold);
  text-decoration:none;
  font-size:13px;
  font-weight:700;
  padding:8px 12px;
  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;
}

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

.info-item {
  background:var(--card2);
  border:1px solid var(--border);
  border-radius:12px;
  padding:11px;
}

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

.info-item .val {
  font-size:16px;
  font-weight:700;
  color:var(--text);
}

.info-item .val-danger { color:#ff7b7b; }

.badge {
  display:inline-flex;
  align-items:center;
  gap:4px;
  padding:5px 12px;
  border-radius:999px;
  font-size:13px;
  font-weight:700;
}

.badge-open {
  background:rgba(34,197,94,.18);
  color:#86efac;
  border:1px solid rgba(34,197,94,.30);
}

.badge-closed {
  background:rgba(239,68,68,.18);
  color:#fca5a5;
  border:1px solid rgba(239,68,68,.35);
}

.summary-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);
}

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

.pill .p-val {
  font-size:21px;
  font-weight:800;
}

.pill-gold .p-val { color:var(--gold); }
.pill-blue .p-val { color:#60a5fa; }
.pill-green .p-val { color:#34d399; }
.pill-red .p-val { color:#fb7185; }

.interest-box {
  background:linear-gradient(135deg,rgba(242,194,48,.18),rgba(212,168,67,.08));
  border:1px solid rgba(242,194,48,.45);
  border-left:5px solid var(--gold);
  border-radius:18px;
  padding:18px;
  margin-bottom:14px;
  box-shadow:0 10px 30px rgba(0,0,0,.20);
}

.interest-label {
  font-size:14px;
  color:var(--gold);
  font-weight:700;
  margin-bottom:8px;
}

.interest-amount {
  font-size:34px;
  font-weight:900;
  color:#ffe082;
  line-height:1;
}

.interest-sub {
  font-size:13px;
  color:#e6cf8f;
  margin-top:8px;
}

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

.form-group { margin-bottom:13px; }

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

.form-group input,
.form-group 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;
}

.form-group input::placeholder { color:#58708f; }

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

.total-row {
  display:flex;
  justify-content:space-between;
  align-items:center;
  background:rgba(59,130,246,.12);
  border:1px solid rgba(59,130,246,.35);
  border-radius:14px;
  padding:14px;
  margin-bottom:14px;
}

.total-label {
  font-size:14px;
  font-weight:700;
  color:#bfdbfe;
}

.total-amount {
  font-size:24px;
  font-weight:900;
  color:#60a5fa;
}

.btn-submit {
  width:100%;
  padding:15px;
  background:linear-gradient(135deg,#16a34a,#22c55e);
  color:#fff;
  border:none;
  border-radius:14px;
  font-size:17px;
  font-weight:800;
  cursor:pointer;
  box-shadow:0 8px 22px rgba(34,197,94,.22);
}

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

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

.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);
}

.hist-wrap {
  overflow-x:auto;
  -webkit-overflow-scrolling:touch;
}

.hist-table {
  width:100%;
  border-collapse:separate;
  border-spacing:0;
  font-size:13px;
  min-width:480px;
}

.hist-table th {
  background:#0a1525;
  color:var(--gold);
  padding:10px;
  text-align:left;
  font-size:12px;
  font-weight:700;
  border-bottom:1px solid var(--border);
}

.hist-table td {
  padding:10px;
  border-bottom:1px solid var(--border);
  color:var(--text);
}

.hist-table tr:hover td { background:rgba(255,255,255,.03); }

.hist-total {
  font-weight:800;
  color:var(--gold);
}

.empty-hist {
  text-align:center;
  color:var(--muted);
  padding:28px;
  font-size:14px;
}

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

@media(max-width:520px) {
  .container { padding:12px 10px 36px; }
  .topbar h1 { font-size:16px; }
  .topbar a { font-size:12px; padding:7px 9px; }
  .summary-pills { grid-template-columns:1fr 1fr; }
  .info-grid { grid-template-columns:1fr 1fr; gap:9px; }
  .info-item { padding:10px; }
  .info-item .val { font-size:14px; }
  .form-row { grid-template-columns:1fr; gap:0; }
}
</style>
</head>

<body>

<div class="topbar">
  <span class="topbar-icon">💳</span>
  <h1>লকার ভাড়া পেমেন্ট</h1>
  <a href="pledge_view.php?pledge_id=<?= $pledge_id ?>">বিস্তারিত</a>
  <a href="ui/pledges.html">তালিকা</a>
</div>

<div class="container">

  <div class="summary-pills">
    <div class="pill pill-blue">
      <div class="p-label">মূল ঋণ</div>
      <div class="p-val">৳<?= number_format($pledge['loan_amount'], 0) ?></div>
    </div>
    <div class="pill pill-red">
      <div class="p-label">বকেয়া মূল</div>
      <div class="p-val">৳<?= number_format($outstanding, 0) ?></div>
    </div>
    <div class="pill pill-gold">
      <div class="p-label">হিসাব করা লকার ভাড়া</div>
      <div class="p-val">৳<?= number_format($calc_interest, 0) ?></div>
    </div>
    <div class="pill pill-green">
      <div class="p-label">লকার ভাড়ার হার</div>
      <div class="p-val"><?= $interest_rate ?>%</div>
    </div>
  </div>

  <div class="card">
    <div class="card-title">🔖 বন্ধক তথ্য</div>
    <div class="info-grid">
      <div class="info-item">
        <label>কোড</label>
        <span class="val"><?= htmlspecialchars($pledge['pledge_code']) ?></span>
      </div>
      <div class="info-item">
        <label>স্ট্যাটাস</label>
        <span class="badge <?= $pledge['status']==='OPEN' ? 'badge-open':'badge-closed' ?>">
          <?= $pledge['status']==='OPEN' ? '● খোলা':'● বন্ধ' ?>
        </span>
      </div>
      <div class="info-item">
        <label>গ্রাহক</label>
        <span class="val"><?= htmlspecialchars($pledge['party_name'] ?? '—') ?></span>
      </div>
      <div class="info-item">
        <label>ফোন</label>
        <span class="val"><?= htmlspecialchars($pledge['party_phone'] ?? '—') ?></span>
      </div>
      <div class="info-item">
        <label>বন্ধক তারিখ</label>
        <span class="val"><?= date('d M Y', strtotime($pledge['pledge_date'])) ?></span>
      </div>
      <div class="info-item">
        <label>মেয়াদ</label>
        <span class="val"><?= $days ?> দিন (<?= $months ?> মাস)</span>
      </div>
      <div class="info-item">
        <label>ওজন</label>
        <span class="val"><?= number_format($gross_g, 3) ?> g</span>
      </div>
      <div class="info-item">
        <label>ভরি / আনা / রতি</label>
        <span class="val"><?= toVori($gross_g) ?></span>
      </div>
      <div class="info-item">
        <label>বিশুদ্ধ ওজন</label>
        <span class="val"><?= number_format($pure_g,3) ?>g / <?= toVori($pure_g) ?></span>
      </div>
      <div class="info-item">
        <label>কারাট / বিশুদ্ধতা</label>
        <span class="val"><?= htmlspecialchars($pledge['karat']) ?> / <?= $pledge['actual_purity'] ?>%</span>
      </div>
      <div class="info-item">
        <label>রাখার জায়গা</label>
        <span class="val"><?= htmlspecialchars($pledge['holding_status']) ?></span>
      </div>
      <div class="info-item">
        <label>বকেয়া মূল</label>
        <span class="val val-danger">৳ <?= number_format($outstanding, 2) ?></span>
      </div>
    </div>
  </div>

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

  <div class="interest-box">
    <div class="interest-label">📈 আজ পর্যন্ত লকার ভাড়া হিসাব</div>
    <div class="interest-amount">৳ <?= number_format($calc_interest, 2) ?></div>
    <div class="interest-sub">
      <?= $days ?> দিন × <?= $interest_rate ?>% / মাস × ৳<?= number_format($outstanding, 0) ?> বকেয়া
    </div>
  </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="form-row">
      <div class="form-group">
        <label>লকার ভাড়া টাকা</label>
        <input type="number" id="interest_paid" min="0" step="0.01"
               value="<?= $calc_interest ?>" placeholder="০.০০" inputmode="decimal">
      </div>
      <div class="form-group">
        <label>মূল টাকা — বকেয়া ৳<?= number_format($outstanding,0) ?></label>
        <input type="number" id="principal_paid" min="0" step="0.01"
               max="<?= $outstanding ?>" value="0" placeholder="০.০০" inputmode="decimal">
      </div>
    </div>

    <div class="total-row">
      <span class="total-label">মোট পেমেন্ট</span>
      <span class="total-amount" id="total_display">৳ <?= number_format($calc_interest, 2) ?></span>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>তারিখ</label>
        <input type="date" id="payment_date" value="<?= date('Y-m-d') ?>">
      </div>
      <div class="form-group">
        <label>Cash Account</label>
        <select id="cash_account_id">
          <?php foreach ($accounts as $acc): ?>
          <option value="<?= $acc['id'] ?>"><?= htmlspecialchars($acc['account_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="form-group">
      <label>মন্তব্য</label>
      <input type="text" id="note" placeholder="নোট লিখুন">
    </div>

    <button class="btn-submit" id="btn-pay">
      <span id="btn-text">💾 পেমেন্ট সংরক্ষণ করুন</span>
    </button>
  </div>

  <?php else: ?>
  <div class="closed-banner">⛔ এই বন্ধক বন্ধ হয়ে গেছে। নতুন পেমেন্ট নেওয়া যাবে না।</div>
  <?php endif; ?>

  <div class="card">
    <div class="card-title">
      📋 পেমেন্ট ইতিহাস
      <span style="margin-left:auto;font-size:12px;color:var(--muted);font-weight:400">
        মোট <?= count($payment_history) ?> টি
      </span>
    </div>

    <?php if (empty($payment_history)): ?>
      <div class="empty-hist">এখনো কোনো পেমেন্ট নেওয়া হয়নি।</div>
    <?php else: ?>
    <div class="hist-wrap">
    <table class="hist-table">
      <thead>
        <tr>
          <th>তারিখ</th>
          <th>লকার ভাড়া</th>
          <th>মূল</th>
          <th>মোট</th>
          <th>Account</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $total_int = 0; $total_prin = 0; $total_all = 0;
        foreach ($payment_history as $pay):
          $total_int  += $pay['interest_paid'];
          $total_prin += $pay['principal_paid'];
          $total_all  += $pay['amount'];
        ?>
        <tr>
          <td><?= date('d M Y', strtotime($pay['payment_date'])) ?></td>
          <td style="color:#34d399">৳<?= number_format($pay['interest_paid'], 2) ?></td>
          <td style="color:#60a5fa">৳<?= number_format($pay['principal_paid'], 2) ?></td>
          <td class="hist-total">৳<?= number_format($pay['amount'], 2) ?></td>
          <td style="color:var(--muted);font-size:12px"><?= htmlspecialchars($pay['account_name'] ?? '—') ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr style="background:#0a1525">
          <td style="font-weight:700;color:var(--muted)">মোট</td>
          <td style="color:#34d399;font-weight:800">৳<?= number_format($total_int, 2) ?></td>
          <td style="color:#60a5fa;font-weight:800">৳<?= number_format($total_prin, 2) ?></td>
          <td class="hist-total">৳<?= number_format($total_all, 2) ?></td>
          <td></td>
        </tr>
      </tfoot>
    </table>
    </div>
    <?php endif; ?>
  </div>

</div>

<script>
const PLEDGE_ID   = <?= $pledge_id ?>;
const OUTSTANDING = <?= $outstanding ?>;
const API_URL = '<?= $base_url ?>/api/pawn/pledge_payment_add.php';

document.addEventListener('input', function(e) {
    if (e.target.id === 'interest_paid' || e.target.id === 'principal_paid') {
        const i = parseFloat(document.getElementById('interest_paid').value)  || 0;
        const p = parseFloat(document.getElementById('principal_paid').value) || 0;
        document.getElementById('total_display').textContent =
            '৳ ' + (i + p).toLocaleString('en-BD', {minimumFractionDigits:2, maximumFractionDigits:2});
    }
});

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

function submitPayment() {
    const interest  = parseFloat(document.getElementById('interest_paid').value)  || 0;
    const principal = parseFloat(document.getElementById('principal_paid').value) || 0;
    const date      = document.getElementById('payment_date').value;
    const account   = document.getElementById('cash_account_id').value;
    const note      = document.getElementById('note').value.trim();

    hideAlerts();

    if (interest + principal <= 0) {
        showError('লকার ভাড়া অথবা মূল — অন্তত একটি দিন।');
        return;
    }

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

    const btn = document.getElementById('btn-pay');
    btn.disabled = true;
    document.getElementById('btn-text').textContent = '⏳ সংরক্ষণ হচ্ছে…';

    const fd = new FormData();
    fd.append('pledge_id',       PLEDGE_ID);
    fd.append('payment_date',    date);
    fd.append('cash_account_id', account);
    fd.append('interest_paid',   interest);
    fd.append('principal_paid',  principal);
    fd.append('note',            note);

    fetch(API_URL, { method: 'POST', body: fd })
        .then(r => {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(data => {
            if (data.success) {
                showSuccess('✅ সফল! মোট: ৳' +
                    parseFloat(data.total_paid).toLocaleString('en-BD', {minimumFractionDigits:2}) +
                    ' | নতুন বকেয়া: ৳' +
                    parseFloat(data.new_outstanding).toLocaleString('en-BD', {minimumFractionDigits:2}));
                setTimeout(() => location.reload(), 1800);
            } else {
                showError(data.message || 'অজানা ত্রুটি।');
                btn.disabled = false;
                document.getElementById('btn-text').textContent = '💾 পেমেন্ট সংরক্ষণ করুন';
            }
        })
        .catch(err => {
            showError('API error: ' + err.message + ' | URL: ' + API_URL);
            btn.disabled = false;
            document.getElementById('btn-text').textContent = '💾 পেমেন্ট সংরক্ষণ করুন';
        });
}

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

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

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

</body>
</html>