<?php
require_once __DIR__ . '/config/db.php';

$pid        = (int)($_GET['pledge_id'] ?? 0);
$type       = trim($_GET['type'] ?? 'pledge'); // pledge / payment / return / locker
$payment_id = (int)($_GET['payment_id'] ?? 0);

if(!function_exists('tk2')){function tk2($n){return '৳'.number_format((float)$n,2);}}
if(!function_exists('e3')){function e3($s){return htmlspecialchars((string)$s,ENT_QUOTES,'UTF-8');}}

function toVori2($g){
 $B=11.664;$A=$B/16;$R=$B/96;
 $v=floor($g/$B);$r=$g-$v*$B;
 $a=floor($r/$A);$ro=floor(($r-$a*$A)/$R);
 return $v.'ভ '.$a.'আ '.$ro.'র';
}
$pledge = null; $payment = null; $err = '';

if($pid <= 0){ $err = 'Pledge ID নেই'; }
else {
    try {
        $st = $pdo->prepare("
            SELECT p.*, COALESCE(pa.name,'') AS party_name, COALESCE(pa.phone,'') AS party_phone,
            COALESCE(pa.address,'') AS party_address
            FROM pawn_pledges p
            LEFT JOIN parties pa ON pa.id = p.party_id
            WHERE p.id = ? LIMIT 1
        ");
        $st->execute([$pid]);
        $pledge = $st->fetch(PDO::FETCH_ASSOC);
        if(!$pledge) $err = 'Pledge পাওয়া যায়নি';

        if($payment_id > 0){
            $ps = $pdo->prepare("SELECT pp.*, COALESCE(ca.account_name,'') AS account_name FROM pawn_payments pp LEFT JOIN cash_accounts ca ON ca.id = pp.cash_account_id WHERE pp.id = ? LIMIT 1");
            $ps->execute([$payment_id]);
            $payment = $ps->fetch(PDO::FETCH_ASSOC);
        }
    } catch(Throwable $ex){ $err = $ex->getMessage(); }
}

$receipt_titles = [
    'pledge'  => ['bn'=>'বন্ধক গ্রহণের রশিদ',   'en'=>'PLEDGE RECEIPT'],
    'payment' => ['bn'=>'পেমেন্ট রশিদ',           'en'=>'PAYMENT RECEIPT'],
    'return'  => ['bn'=>'বন্ধক ফেরতের রশিদ',      'en'=>'PLEDGE RETURN RECEIPT'],
    'locker'  => ['bn'=>'লকার ভাড়ার রশিদ',        'en'=>'LOCKER RENT RECEIPT'],
];
$title = $receipt_titles[$type] ?? $receipt_titles['pledge'];
$today = date('d/m/Y');
$now   = date('h:i A');

// লকার ভাড়া হিসাব
$locker_months = 0; $due_rent = 0; $monthly_rent = 0;
if($pledge && $type === 'locker'){
    $locker_since = $pledge['pledge_date'];
    $rate = (float)($pledge['interest_rate'] ?? 0);
    $outstanding = (float)($pledge['outstanding_principal'] ?? 0);
    $d1 = new DateTime($locker_since);
    $d2 = new DateTime(date('Y-m-d'));
    $yd = (int)$d2->format('Y') - (int)$d1->format('Y');
    $md = (int)$d2->format('m') - (int)$d1->format('m');
    $locker_months = $yd*12 + $md + 1;
    if($locker_months < 1) $locker_months = 1;
    $monthly_rent = round($outstanding * $rate / 100, 2);
    $due_rent = round($monthly_rent * $locker_months, 2);
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo e3($title['en']); ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#f5f5f5;font-family:'Segoe UI',Arial,sans-serif;font-size:14px;color:#111}
.page{max-width:380px;margin:0 auto;background:#fff;padding:0}
.receipt{padding:18px 20px}

/* হেডার */
.shop-name{font-size:22px;font-weight:800;color:#1a237e;text-align:center;letter-spacing:.5px}
.shop-sub{font-size:12px;color:#555;text-align:center;margin-top:3px}
.shop-contact{font-size:11px;color:#666;text-align:center;margin-top:2px}
.divider{border:none;border-top:2px dashed #1a237e;margin:10px 0}
.divider-thin{border:none;border-top:1px dashed #ccc;margin:8px 0}

/* রশিদ টাইটেল */
.receipt-type{text-align:center;background:#1a237e;color:#fff;padding:8px;border-radius:6px;margin-bottom:12px}
.receipt-type .bn{font-size:16px;font-weight:700}
.receipt-type .en{font-size:11px;color:rgba(255,255,255,.8);margin-top:2px}

/* তথ্য রো */
.info-row{display:flex;justify-content:space-between;align-items:flex-start;padding:5px 0;border-bottom:1px solid #f0f0f0}
.info-row:last-child{border-bottom:none}
.ir-label{font-size:12px;color:#666;min-width:120px}
.ir-value{font-size:13px;font-weight:600;text-align:right;flex:1}

/* হাইলাইট বক্স */
.highlight-box{background:#f0f4ff;border:1px solid #1a237e;border-radius:8px;padding:12px;margin:12px 0;text-align:center}
.hl-label{font-size:11px;color:#555;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.hl-amount{font-size:28px;font-weight:800;color:#1a237e}
.hl-sub{font-size:11px;color:#666;margin-top:3px}

/* সতর্কতা বক্স */
.warning-box{background:#fff8e1;border:1px solid #f9a825;border-radius:6px;padding:10px;margin:12px 0;font-size:11px;line-height:1.6;color:#555}
.warning-box strong{color:#e65100;font-size:12px}

/* স্বাক্ষর */
.sign-area{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:20px;padding-top:12px;border-top:1px dashed #ccc}
.sign-box{text-align:center}
.sign-line{border-top:1px solid #333;margin-bottom:5px;height:30px}
.sign-label{font-size:10px;color:#666}

/* ফুটার */
.footer{text-align:center;font-size:10px;color:#888;padding:10px 0;border-top:1px dashed #ccc;margin-top:14px}

/* প্রিন্ট */
@media print {
  body{background:#fff}
  .no-print{display:none!important}
  .page{max-width:100%}
}
@media screen {
  .print-btn{display:block;width:calc(100% - 40px);margin:15px 20px;padding:12px;background:#1a237e;color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:700;cursor:pointer;text-align:center}
}
</style>
</head>
<body>

<?php if($err): ?>
<div style="padding:20px;color:red"><?php echo e3($err); ?></div>
<?php else: ?>

<div class="page">
<div class="receipt">

  <!-- শপ হেডার -->
  <div class="shop-name">বধূবরণ জুয়েলার্স</div>
  <div class="shop-sub">স্বর্ণালঙ্কার বন্ধক ও বিক্রয় | Gold Jewellery Pledge & Sales</div>
  <div class="shop-contact">📞 যোগাযোগ: [আপনার নম্বর] | তারিখ: <?php echo $today; ?> | সময়: <?php echo $now; ?></div>

  <hr class="divider">

  <!-- রশিদ টাইটেল -->
  <div class="receipt-type">
    <div class="bn"><?php echo e3($title['bn']); ?></div>
    <div class="en"><?php echo e3($title['en']); ?></div>
  </div>

  <!-- রশিদ নম্বর ও কোড -->
  <div class="info-row"><span class="ir-label">বন্ধক কোড / Code</span><span class="ir-value" style="color:#1a237e;font-weight:800"><?php echo e3($pledge['pledge_code']); ?></span></div>
  <div class="info-row"><span class="ir-label">তারিখ / Date</span><span class="ir-value"><?php echo e3($pledge['pledge_date']); ?></span></div>

  <hr class="divider-thin">

  <!-- গ্রাহক তথ্য -->
  <div style="font-size:11px;color:#1a237e;font-weight:700;text-transform:uppercase;margin-bottom:5px">গ্রাহক তথ্য / Customer Info</div>
  <div class="info-row"><span class="ir-label">নাম / Name</span><span class="ir-value"><?php echo e3($pledge['party_name']); ?></span></div>
  <div class="info-row"><span class="ir-label">মোবাইল / Mobile</span><span class="ir-value"><?php echo e3($pledge['party_phone']?:'-'); ?></span></div>
  <?php if($pledge['party_address']): ?>
  <div class="info-row"><span class="ir-label">ঠিকানা</span><span class="ir-value"><?php echo e3($pledge['party_address']); ?></span></div>
  <?php endif; ?>

  <hr class="divider-thin">

  <?php if($type === 'pledge'): ?>
  <!-- বন্ধক গ্রহণ -->
  <div style="font-size:11px;color:#1a237e;font-weight:700;text-transform:uppercase;margin-bottom:5px">সোনার বিবরণ / Gold Details</div>
  <div class="info-row"><span class="ir-label">ক্যারেট / Karat</span><span class="ir-value"><?php echo e3($pledge['karat']); ?></span></div>
  <div class="info-row"><span class="ir-label">Gross ওজন</span><span class="ir-value"><?php echo number_format((float)$pledge['gross_weight'],3); ?> গ্রাম (<?php echo toVori2((float)$pledge['gross_weight']); ?>)</span></div>
  <div class="info-row"><span class="ir-label">নিট ওজন</span><span class="ir-value"><?php echo number_format((float)$pledge['pure_weight'],3); ?> গ্রাম (<?php echo toVori2((float)$pledge['pure_weight']); ?>)</span></div>
  <div class="info-row"><span class="ir-label">বিশুদ্ধতা</span><span class="ir-value"><?php echo number_format((float)$pledge['actual_purity'],2); ?>%</span></div>
  <div class="info-row"><span class="ir-label">সোনার মূল্য</span><span class="ir-value"><?php echo tk2($pledge['gold_value']); ?></span></div>
  <?php if($pledge['manual_barcode']): ?>
  <div class="info-row"><span class="ir-label">বারকোড</span><span class="ir-value"><?php echo e3($pledge['manual_barcode']); ?></span></div>
  <?php endif; ?>
  <hr class="divider-thin">
  <div style="font-size:11px;color:#1a237e;font-weight:700;text-transform:uppercase;margin-bottom:5px">ঋণের তথ্য / Loan Details</div>
  <div class="info-row"><span class="ir-label">লকার ভাড়ার হার</span><span class="ir-value"><?php echo number_format((float)$pledge['interest_rate'],2); ?>% / মাস</span></div>
  <div class="highlight-box">
    <div class="hl-label">প্রদত্ত ঋণ / Loan Amount</div>
    <div class="hl-amount"><?php echo tk2($pledge['loan_amount']); ?></div>
    <div class="hl-sub">বাংলাদেশী টাকা / BDT</div>
  </div>

  <?php elseif($type === 'payment' && $payment): ?>
  <!-- পেমেন্ট রশিদ -->
  <div style="font-size:11px;color:#1a237e;font-weight:700;text-transform:uppercase;margin-bottom:5px">পেমেন্ট তথ্য / Payment Details</div>
  <div class="info-row"><span class="ir-label">পেমেন্টের তারিখ</span><span class="ir-value"><?php echo e3($payment['payment_date']); ?></span></div>
  <div class="info-row"><span class="ir-label">বাকি আসল</span><span class="ir-value" style="color:#c62828"><?php echo tk2($pledge['outstanding_principal']); ?></span></div>
  <div class="info-row"><span class="ir-label">আসল পরিশোধ</span><span class="ir-value" style="color:#2e7d32"><?php echo tk2($payment['principal_paid']); ?></span></div>
  <div class="info-row"><span class="ir-label">লকার ভাড়া পরিশোধ</span><span class="ir-value" style="color:#e65100"><?php echo tk2($payment['interest_paid']); ?></span></div>
  <div class="info-row"><span class="ir-label">একাউন্ট</span><span class="ir-value"><?php echo e3($payment['account_name']); ?></span></div>
  <?php if($payment['note']): ?>
  <div class="info-row"><span class="ir-label">নোট</span><span class="ir-value"><?php echo e3($payment['note']); ?></span></div>
  <?php endif; ?>
  <div class="highlight-box">
    <div class="hl-label">গৃহীত মোট টাকা / Total Received</div>
    <div class="hl-amount"><?php echo tk2($payment['amount']); ?></div>
    <div class="hl-sub">ধন্যবাদ পেমেন্টের জন্য</div>
  </div>

  <?php elseif($type === 'return'): ?>
  <!-- বন্ধক ফেরত -->
  <div style="font-size:11px;color:#1a237e;font-weight:700;text-transform:uppercase;margin-bottom:5px">ফেরতের তথ্য / Return Details</div>
  <div class="info-row"><span class="ir-label">ফেরতের তারিখ</span><span class="ir-value"><?php echo $today; ?></span></div>
  <div class="info-row"><span class="ir-label">মোট ঋণ ছিল</span><span class="ir-value"><?php echo tk2($pledge['loan_amount']); ?></span></div>
  <div class="info-row"><span class="ir-label">ক্যারেট</span><span class="ir-value"><?php echo e3($pledge['karat']); ?></span></div>
  <div class="info-row"><span class="ir-label">Gross ওজন</span><span class="ir-value"><?php echo number_format((float)$pledge['gross_weight'],3); ?> গ্রাম</span></div>
  <div class="info-row"><span class="ir-label">নিট ওজন</span><span class="ir-value"><?php echo number_format((float)$pledge['pure_weight'],3); ?> গ্রাম</span></div>
  <?php if($pledge['manual_barcode']): ?>
  <div class="info-row"><span class="ir-label">বারকোড</span><span class="ir-value"><?php echo e3($pledge['manual_barcode']); ?></span></div>
  <?php endif; ?>
  <div class="highlight-box" style="background:#f1f8e9;border-color:#388e3c">
    <div class="hl-label" style="color:#2e7d32">সোনা ফেরত দেওয়া হয়েছে</div>
    <div class="hl-amount" style="color:#2e7d32">✅ সম্পন্ন</div>
    <div class="hl-sub">Gold Successfully Returned</div>
  </div>

  <?php elseif($type === 'locker'): ?>
  <!-- লকার ভাড়া -->
  <div style="font-size:11px;color:#1a237e;font-weight:700;text-transform:uppercase;margin-bottom:5px">লকার তথ্য / Locker Details</div>
  <div class="info-row"><span class="ir-label">বাকি আসল</span><span class="ir-value" style="color:#c62828"><?php echo tk2($pledge['outstanding_principal']); ?></span></div>
  <div class="info-row"><span class="ir-label">ভাড়ার হার</span><span class="ir-value"><?php echo number_format((float)$pledge['interest_rate'],2); ?>% / মাস</span></div>
  <div class="info-row"><span class="ir-label">লকারে আছে</span><span class="ir-value"><?php echo $locker_months; ?> মাস</span></div>
  <div class="info-row"><span class="ir-label">মাসিক ভাড়া</span><span class="ir-value"><?php echo tk2($monthly_rent); ?></span></div>
  <div class="highlight-box">
    <div class="hl-label">মোট বকেয়া লকার ভাড়া</div>
    <div class="hl-amount"><?php echo tk2($due_rent); ?></div>
    <div class="hl-sub"><?php echo $locker_months; ?> মাস × <?php echo tk2($monthly_rent); ?>/মাস</div>
  </div>
  <?php endif; ?>

  <!-- ৯০ দিনের সতর্কতা -->
  <div class="warning-box">
    <strong>⚠️ গুরুত্বপূর্ণ নোটিশ / Important Notice</strong><br>
    বন্ধক রাখার <strong>৯০ (নব্বই) দিনের মধ্যে</strong> লকার ভাড়া পরিশোধ করিয়া নতুন রশিদ গ্রহণ করুন।<br>
    <em>Please renew your receipt within <strong>90 days</strong> by paying the locker rent.</em><br><br>
    ৯০ দিনের মধ্যে রশিদ নবায়ন না করিলে বন্ধকৃত জিনিসের উপর কোনো দাবি করা যাইবে না।<br>
    <em>Failure to renew within 90 days forfeits all claims to the pledged item.</em><br><br>
    <strong>অযথা হয়রানি করিলে আইনগত ব্যবস্থা নেওয়া হইবে।</strong><br>
    <em>Legal action will be taken against harassment.</em>
  </div>

  <!-- স্বাক্ষর -->
  <div class="sign-area">
    <div class="sign-box">
      <div class="sign-line"></div>
      <div class="sign-label">গ্রাহকের স্বাক্ষর<br>Customer Signature</div>
    </div>
    <div class="sign-box">
      <div class="sign-line"></div>
      <div class="sign-label">কর্তৃপক্ষের স্বাক্ষর<br>Authorized Signature</div>
    </div>
  </div>

  <!-- ফুটার -->
  <div class="footer">
    বধূবরণ জুয়েলার্স | এই রশিদটি সংরক্ষণ করুন<br>
    Please keep this receipt safe | <?php echo $today; ?>
  </div>

</div>
</div>

<!-- প্রিন্ট বাটন -->
<button class="print-btn no-print" onclick="window.print()">🖨️ রশিদ প্রিন্ট করুন</button>

<?php endif; ?>
</body>
</html>