<?php
session_start();
require_once '../config/database.php';
require_once '../includes/zashof.php';
require_once '../includes/bKashPayment.php';

// Check if user is logged in as a regular student
$is_regular_student = isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'student';

// Check if user is a pending student logged in via application system
$is_pending_student = isset($_SESSION['student_logged_in']) && $_SESSION['student_logged_in'] === true;

// Allow access if either regular student or pending student
if (!$is_regular_student && !$is_pending_student) {
    header('Location: ../login.php');
    exit();
}

// Get student information based on login type
if (isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'student') {
    // Regular student - get from students table
    $stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.user_id=? LIMIT 1");
    $stmt->execute([$_SESSION['user_id']]);
    $student = $stmt->fetch();
    if (!$student) { die('Student profile not found'); }
} elseif (isset($_SESSION['student_application_no'])) {
    // Pending student - get from admission_applications table
    $stmt = $pdo->prepare("SELECT * FROM admission_applications WHERE application_no=? LIMIT 1");
    $stmt->execute([$_SESSION['student_application_no']]);
    $application = $stmt->fetch();
    if (!$application) { die('Application not found'); }
    
    // Get class information for pending student
    $class_name = '';
    $class_section = '';
    if (!empty($application['applying_for_class_id'])) {
        $class_stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id=?");
        $class_stmt->execute([$application['applying_for_class_id']]);
        $class = $class_stmt->fetch();
        if ($class) {
            $class_name = $class['name'];
            $class_section = $class['section'];
        }
    }
    
    // Create student-like array for pending student
    $student = [
        'id' => 0, // Placeholder ID
        'first_name' => $application['first_name'],
        'last_name' => $application['last_name'],
        'student_id' => $application['application_no'],
        'class_id' => $application['applying_for_class_id'],
        'class_name' => $class_name,
        'section' => $class_section,
        'scholarship' => 'no' // Pending students don't have scholarship
    ];
} else {
    die('Invalid session');
}

// Check if student has scholarship
$has_scholarship = ($student['scholarship'] === 'yes');

// Load all fees and payments summary
if ($student['id'] > 0) {
    // Regular student - get fees by student_id
    $stmt = $pdo->prepare("SELECT f.*, (f.amount - f.paid_amount) as due_amount FROM fees f WHERE f.student_id=? ORDER BY f.due_date ASC, f.created_at ASC");
    $stmt->execute([$student['id']]);
    $fees = $stmt->fetchAll();
} else {
    // Pending student - try to find if there's a student record created from their application
    // First check if a student record exists based on their application
    $stmt = $pdo->prepare("SELECT id FROM students WHERE application_no = ? LIMIT 1");
    $stmt->execute([$student['student_id']]);
    $student_record = $stmt->fetch();
    
    if ($student_record) {
        // Student record exists, get fees for this student
        $stmt = $pdo->prepare("SELECT f.*, (f.amount - f.paid_amount) as due_amount FROM fees f WHERE f.student_id=? ORDER BY f.due_date ASC, f.created_at ASC");
        $stmt->execute([$student_record['id']]);
        $fees = $stmt->fetchAll();
    } else {
        // No student record exists yet, get class-based fees for the pending student
        $fees = [];
    }
}

// If no fees found for the student, get all fees for their class
if (empty($fees) && !empty($student['class_id'])) {
    // First, let's get all distinct fee types that have been assigned to students in this class
    $stmt = $pdo->prepare(
        "SELECT DISTINCT f.fee_type, f.amount, f.due_date, f.academic_year, f.month, f.remarks 
        FROM fees f 
        JOIN students s ON f.student_id = s.id 
        WHERE s.class_id = ? 
        ORDER BY f.due_date ASC"
    );
    $stmt->execute([$student['class_id']]);
    $distinct_class_fees = $stmt->fetchAll();
    
    // Create placeholder fee records for the current student based on class fee types
    foreach ($distinct_class_fees as $class_fee) {
        $fees[] = [
            'id' => 0, // Placeholder ID since not yet assigned to this student
            'fee_type' => $class_fee['fee_type'],
            'amount' => $class_fee['amount'],
            'due_date' => $class_fee['due_date'],
            'academic_year' => $class_fee['academic_year'],
            'month' => $class_fee['month'],
            'remarks' => $class_fee['remarks'],
            'status' => 'pending',
            'paid_amount' => 0,
            'due_amount' => $class_fee['amount'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
    }
}

$total_payable = 0; $total_paid = 0; $total_due = 0;
foreach ($fees as $f) {
  $total_payable += (float)$f['amount'];
  $total_paid += (float)$f['paid_amount'];
  $total_due += (float)($f['amount'] - $f['paid_amount']);
}

// If student has scholarship, set total_due to 0
if ($has_scholarship) {
    $total_due = 0;
}

// Payment history (transactions) - exclude rejected bKash transactions
// Group payments by transaction ID to avoid showing duplicate transactions
$payments = [];

if ($student['id'] > 0) {
    // Regular student - get payment history by student_id
    try {
        $stmt = $pdo->prepare(
            "SELECT 
                fp.transaction_id,
                COALESCE(fp.payment_date, fp.created_at) AS pay_date,
                fp.payment_method,
                SUM(fp.amount) as total_amount,
                GROUP_CONCAT(CONCAT(f.fee_type, IF(f.month IS NOT NULL AND f.month != '', CONCAT(' - ', f.month), '')) SEPARATOR ', ') as fee_details
             FROM fee_payments fp
             JOIN fees f ON f.id = fp.fee_id
             LEFT JOIN bkash_transactions bt ON fp.transaction_id = bt.transaction_id COLLATE utf8mb4_unicode_ci
             WHERE f.student_id = ?
             AND (bt.status != 'rejected' OR bt.status IS NULL OR fp.payment_method != 'bkash')
             GROUP BY fp.transaction_id, fp.payment_date, fp.created_at, fp.payment_method
             ORDER BY pay_date DESC"
        );
        $stmt->execute([$student['id']]);
        $payments = $stmt->fetchAll();
    } catch (Exception $e) {
        // If there's a collation error, try without the bkash join
        try {
            $stmt = $pdo->prepare(
                "SELECT 
                    fp.transaction_id,
                    COALESCE(fp.payment_date, fp.created_at) AS pay_date,
                    fp.payment_method,
                    SUM(fp.amount) as total_amount,
                    GROUP_CONCAT(CONCAT(f.fee_type, IF(f.month IS NOT NULL AND f.month != '', CONCAT(' - ', f.month), '')) SEPARATOR ', ') as fee_details
                 FROM fee_payments fp
                 JOIN fees f ON f.id = fp.fee_id
                 WHERE f.student_id = ?
                 GROUP BY fp.transaction_id, fp.payment_date, fp.created_at, fp.payment_method
                 ORDER BY pay_date DESC"
            );
            $stmt->execute([$student['id']]);
            $payments = $stmt->fetchAll();
        } catch (Exception $e2) {
            $payments = [];
        }
    }
} else {
    // Pending student - try to get payment history using student record from application
    try {
        $stmt = $pdo->prepare(
            "SELECT 
                fp.transaction_id,
                COALESCE(fp.payment_date, fp.created_at) AS pay_date,
                fp.payment_method,
                SUM(fp.amount) as total_amount,
                GROUP_CONCAT(CONCAT(f.fee_type, IF(f.month IS NOT NULL AND f.month != '', CONCAT(' - ', f.month), '')) SEPARATOR ', ') as fee_details
             FROM fee_payments fp
             JOIN fees f ON f.id = fp.fee_id
             LEFT JOIN bkash_transactions bt ON fp.transaction_id = bt.transaction_id COLLATE utf8mb4_unicode_ci
             WHERE f.student_id IN (
                 SELECT id FROM students WHERE application_no = ?
             )
             AND (bt.status != 'rejected' OR bt.status IS NULL OR fp.payment_method != 'bkash')
             GROUP BY fp.transaction_id, fp.payment_date, fp.created_at, fp.payment_method
             ORDER BY pay_date DESC"
        );
        $stmt->execute([$student['student_id']]);
        $payments = $stmt->fetchAll();
    } catch (Exception $e) {
        // If there's a collation error, try without the bkash join
        try {
            $stmt = $pdo->prepare(
                "SELECT 
                    fp.transaction_id,
                    COALESCE(fp.payment_date, fp.created_at) AS pay_date,
                    fp.payment_method,
                    SUM(fp.amount) as total_amount,
                    GROUP_CONCAT(CONCAT(f.fee_type, IF(f.month IS NOT NULL AND f.month != '', CONCAT(' - ', f.month), '')) SEPARATOR ', ') as fee_details
                 FROM fee_payments fp
                 JOIN fees f ON f.id = fp.fee_id
                 WHERE f.student_id IN (
                     SELECT id FROM students WHERE application_no = ?
                 )
                 GROUP BY fp.transaction_id, fp.payment_date, fp.created_at, fp.payment_method
                 ORDER BY pay_date DESC"
            );
            $stmt->execute([$student['student_id']]);
            $payments = $stmt->fetchAll();
        } catch (Exception $e2) {
            $payments = [];
        }
    }
}

// Check if payment gateways are enabled
$zashof = new ZashofPayment();
$zashof_enabled = $zashof->isEnabled();

$bKash = new bKashPayment();
$bKash_enabled = $bKash->isEnabled();

// ZiniPay enabled check
$zinipay_cfg = require '../config/zinipay.php';
$zinipay_enabled = $zinipay_cfg['enabled'] && !empty($zinipay_cfg['api_key']);

// Get bank accounts for dropdown
$bank_accounts = [];
try {
    $stmt = $pdo->query("SELECT id, bank_name, branch_name, account_number, account_name FROM bank_accounts ORDER BY bank_name, branch_name");
    $bank_accounts = $stmt->fetchAll();
} catch (Exception $e) {
    $bank_accounts = [];
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>আমার ফি</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link href="../assets/css/style.css" rel="stylesheet">
  <style>
    body {
      font-family: 'Hind Siliguri', sans-serif;
      background-color: #f8f9fa;
    }
    .card {
      box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
      border: 1px solid rgba(0, 0, 0, 0.125);
      border-radius: 0.5rem;
    }
    .card-header {
      background-color: #fff;
      border-bottom: 1px solid rgba(0, 0, 0, 0.125);
      font-weight: 600;
    }
    .table th {
      font-weight: 600;
    }
    .fee-item { 
      border: 1px solid #e9ecef; 
      border-radius: 0; 
      padding: 10px; 
      margin-bottom: 8px; 
      background: #ffffff;
      box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
    }
    .fee-item:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    .fee-item.overdue { 
      border-left: 3px solid #e74c3c; 
      background: linear-gradient(135deg, #fff5f5 0%, #ffecec 100%);
    }
    .status-pending {
      background-color: #fff3cd;
      color: #856404;
    }
    .status-verified {
      background-color: #d4edda;
      color: #155724;
    }
    .status-rejected {
      background-color: #f8d7da;
      color: #721c24;
    }
    .form-control, .form-select {
      border-radius: 0.375rem;
    }
    .btn {
      border-radius: 0.375rem;
    }
    .navbar {
      box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
    <div class="navbar-nav ms-auto">
      <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
    </div>
  </div>
</nav>
<div class="container-fluid mt-4">
  <?php if (isset($_SESSION['success_message'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
      <i class="fas fa-check-circle"></i> <?= htmlspecialchars($_SESSION['success_message']) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['success_message']); ?>
  <?php endif; ?>
  
  <?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger alert-dismissible fade show">
      <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($_SESSION['error_message']) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['error_message']); ?>
  <?php endif; ?>
  
  <?php if (isset($_SESSION['info_message'])): ?>
    <div class="alert alert-info alert-dismissible fade show">
      <i class="fas fa-info-circle"></i> <?= htmlspecialchars($_SESSION['info_message']) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['info_message']); ?>
  <?php endif; ?>
  
  <div class="card">
    <div class="card-header"><h5><i class="fas fa-money-bill-wave"></i> আমার ফি</h5></div>
    <div class="card-body">
      <div class="row mb-2">
        <div class="col-md-4"><strong>নাম:</strong> <?=htmlspecialchars($student['first_name'].' '.$student['last_name'])?></div>
        <div class="col-md-4"><strong>আইডি:</strong> <?=htmlspecialchars($student['student_id'])?></div>
        <div class="col-md-4"><strong>ক্লাস:</strong> <?=htmlspecialchars(($student['class_name']??'').' - '.($student['section']??''))?></div>
      </div>

      <div class="row g-2 mb-3">
        <div class="col-md-4">
          <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-2">
              <div class="fs-5 text-primary mb-1"><i class="fas fa-file-invoice"></i></div>
              <h6 class="card-title text-muted mb-1">মোট বিল</h6>
              <h4 class="text-primary mb-0">৳<?=number_format($total_payable,2)?></h4>
            </div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-2">
              <div class="fs-5 text-success mb-1"><i class="fas fa-check-circle"></i></div>
              <h6 class="card-title text-muted mb-1">পরিশোধিত</h6>
              <h4 class="text-success mb-0">৳<?=number_format($total_paid,2)?></h4>
            </div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="card border-0 shadow-sm h-100 <?=($total_due > 0) ? 'border-start border-3 border-danger' : ''?>">
            <div class="card-body text-center p-2">
              <div class="fs-5 text-danger mb-1"><i class="fas fa-exclamation-circle"></i></div>
              <h6 class="card-title text-muted mb-1">বকেয়া</h6>
              <h4 class="text-danger mb-0">৳<?=number_format($total_due,2)?></h4>
            </div>
          </div>
        </div>
      </div>

      <?php if (empty($fees)): ?>
        <div class="alert alert-info">কোন ফি নির্ধারিত নেই।</div>
      <?php else: ?>
        <div>
          <?php foreach ($fees as $f): $due = (float)($f['amount'] - $f['paid_amount']); $overdue = ($due>0 && !empty($f['due_date']) && strtotime($f['due_date']) < time()); ?>
            <div class="fee-item <?=$overdue?'overdue':''?>">
              <div class="row g-2 align-items-center">
                <div class="col-md-5">
                  <div><strong><?=htmlspecialchars($f['fee_type'])?></strong> <?= $f['month'] ? ' - '.htmlspecialchars($f['month']) : '' ?></div>
                  <div class="text-muted small">Due Date: <?= $f['due_date'] ? htmlspecialchars($f['due_date']) : 'N/A' ?></div>
                </div>
                <div class="col-md-7 text-md-end">
                  <div><strong>বিল:</strong> ৳<?=number_format((float)$f['amount'],2)?></div>
                  <div><strong>পরিশোধিত:</strong> ৳<?=number_format((float)$f['paid_amount'],2)?></div>
                  <div class="<?=$due>0?'text-danger':'text-success'?>"><strong>বকেয়া:</strong> ৳<?=number_format($due,2)?></div>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        
        <?php if ($total_due > 0): ?>
          <div class="card border-0 shadow-sm mt-3">
            <div class="card-header bg-success text-white py-2">
              <h5 class="mb-0 fs-6"><i class="fas fa-money-bill-wave"></i> অনলাইন পেমেন্ট</h5>
            </div>
            <div class="card-body py-2">
              <p class="mb-3">অনলাইনে পেমেন্ট করতে নিচের বাটনগুলোর যেকোন একটিতে ক্লিক করুন</p>
              
              <div class="d-grid gap-2 d-md-block mb-2">
                <?php if ($zashof_enabled): ?>
                  <a href="student_payment.php?amount=<?= $total_due ?>" class="btn payment-btn btn-success me-md-2 py-1 px-2">
                    <i class="fas fa-credit-card"></i> ক্রেডিট/ডেবিট কার্ড
                    <div class="small">৳<?= number_format($total_due, 2) ?></div>
                  </a>
                <?php endif; ?>
                <a href="bKash_payment.php?amount=<?= $total_due ?>" class="btn payment-btn btn-info py-1 px-2">
                  <i class="fas fa-mobile-alt"></i> bKash Personal
                  <div class="small">৳<?= number_format($total_due, 2) ?></div>
                  </a>
                <?php if ($zinipay_enabled): ?>
                <a href="zinipay_pay.php" class="btn payment-btn py-1 px-2 ms-md-2" style="background:linear-gradient(135deg,#e91e8c,#ff6b35);color:#fff;border:none;">
                  <i class="fas fa-mobile-alt"></i> <?= htmlspecialchars($zinipay_cfg['label']) ?>
                  <div class="small">৳<?= number_format($total_due, 2) ?></div>
                </a>
                <?php endif; ?>              </div>              
              <div class="row g-1">
                <div class="col-md-6 mb-1">
                  <a href="submit_bkash_transaction.php" class="btn btn-outline-primary w-100 payment-btn py-1 px-2">
                    <i class="fas fa-paper-plane"></i> bKash ট্রানজেকশন আইডি জমা দিন
                  </a>
                </div>
                <div class="col-md-6 mb-1">
                  <a href="submit_bank_transaction.php" class="btn btn-outline-warning w-100 payment-btn py-1 px-2">
                    <i class="fas fa-file-invoice-dollar"></i> ব্যাংক ট্রানজেকশন আইডি জমা দিন
                  </a>
                </div>
                <div class="col-md-6 mb-1">
                  <button class="btn btn-warning w-100 payment-btn py-1 px-2" data-bs-toggle="modal" data-bs-target="#bankReceiptModal">
                    <i class="fas fa-file-invoice"></i> ব্যাংক রসিদ প্রিন্ট করুন
                  </button>
                </div>
                <div class="col-md-6 mb-1">
                  <a href="select_fees.php" class="btn btn-secondary w-100 payment-btn py-1 px-2">
                    <i class="fas fa-list-check"></i> ফি নির্বাচন করুন
                  </a>
                </div>
              </div>
              
              <div class="mt-3 text-center">
                <small class="text-muted"><i class="fas fa-info-circle"></i> পেমেন্ট সম্পূর্ণ হলে অ্যাডমিন ভেরিফিকেশন করবেন</small>
              </div>
            </div>
          </div>
          
          <?php if (!$zashof_enabled): ?>
            <div class="card border-0 shadow-sm mt-3 border-start border-4 border-info">
              <div class="card-body">
                <div class="d-flex">
                  <div class="flex-shrink-0">
                    <i class="fas fa-info-circle fa-2x text-info"></i>
                  </div>
                  <div class="flex-grow-1 ms-3">
                    <h5 class="mb-1">পেমেন্ট সিস্টেম নিষ্ক্রিয়</h5>
                    <p class="mb-0">ক্রেডিট/ডেবিট কার্ড পেমেন্ট সিস্টেম এখন নিষ্ক্রিয় করা হয়েছে। bKash Personal এর মাধ্যমে পেমেন্ট করুন।</p>
                  </div>
                </div>
              </div>
            </div>
          <?php endif; ?>
        <?php elseif ($has_scholarship): ?>
          <div class="card border-0 shadow-sm mt-4 border-start border-4 border-success">
            <div class="card-body text-center">
              <div class="display-4 text-success mb-3"><i class="fas fa-graduation-cap"></i></div>
              <h4 class="text-success">অভিনন্দন!</h4>
              <p class="mb-0">আপনি উপবৃত্তি পেয়েছেন। ফি পরিশোধের দরকার নেই।</p>
            </div>
          </div>
        <?php endif; ?>
      <?php endif; ?>

      <!-- Payment History -->
      <div class="card border-0 shadow-sm mt-3">
        <div class="card-header bg-info text-white py-2">
          <h5 class="mb-0 fs-6"><i class="fas fa-receipt"></i> পেমেন্ট হিস্টোরি</h5>
        </div>
        <div class="card-body">
          <?php if (empty($payments)): ?>
            <div class="text-center py-5">
              <i class="fas fa-receipt fa-3x text-muted mb-3"></i>
              <p class="text-muted mb-0">কোন পেমেন্ট রেকর্ড পাওয়া যায়নি।</p>
            </div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-striped">
                <thead class="table-dark">
                  <tr>
                    <th>তারিখ</th>
                    <th>ট্রানজেকশন আইডি</th>
                    <th>পরিমাণ</th>
                    <th>পদ্ধতি</th>
                    <th>ফি হেড/মাস</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($payments as $p): ?>
                  <tr>
                    <td><?= $p['pay_date'] ? date('d/m/Y', strtotime($p['pay_date'])) : '-' ?></td>
                    <td><?= htmlspecialchars($p['transaction_id'] ?? '') ?></td>
                    <td class="fw-bold">৳<?= number_format((float)$p['total_amount'], 2) ?></td>
                    <td>
                      <?php if ($p['payment_method'] == 'bkash'): ?>
                        <span class="badge bg-info">bKash</span>
                      <?php elseif ($p['payment_method'] == 'bank'): ?>
                        <span class="badge bg-warning text-dark">ব্যাংক</span>
                      <?php elseif ($p['payment_method'] == 'card'): ?>
                        <span class="badge bg-success">কার্ড</span>
                      <?php else: ?>
                        <span class="badge bg-secondary"><?= htmlspecialchars(strtoupper($p['payment_method'] ?? '')) ?></span>
                      <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($p['fee_details'] ?? '') ?></td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <div class="card border-0 shadow-sm mt-3 border-start border-4 border-warning">
        <div class="card-body py-2">
          <div class="d-flex">
            <div class="flex-shrink-0">
              <i class="fas fa-info-circle fa-lg text-warning"></i>
            </div>
            <div class="flex-grow-1 ms-2">
              <h6 class="mb-1">গুরুত্বপূর্ণ তথ্য</h6>
              <p class="mb-0 small">ফি সংক্রান্ত কোন প্রশ্ন থাকলে অফিসে যোগাযোগ করুন।</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Bank Receipt Modal -->
<div class="modal fade" id="bankReceiptModal" tabindex="-1" aria-labelledby="bankReceiptModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="bankReceiptModalLabel">ব্যাংক রসিদ প্রিন্ট</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="bankReceiptForm">
          <div class="mb-3">
            <label for="bankAccount" class="form-label">ব্যাংক নির্বাচন করুন</label>
            <select class="form-select" id="bankAccount" required>
              <option value="">ব্যাংক নির্বাচন করুন</option>
              <?php foreach ($bank_accounts as $account): ?>
                <option value="<?= $account['id'] ?>" 
                        data-bank="<?= htmlspecialchars($account['bank_name']) ?>"
                        data-branch="<?= htmlspecialchars($account['branch_name']) ?>"
                        data-account="<?= htmlspecialchars($account['account_number']) ?>"
                        data-name="<?= htmlspecialchars($account['account_name']) ?>">
                  <?= htmlspecialchars($account['bank_name']) ?> - <?= htmlspecialchars($account['branch_name']) ?> (<?= htmlspecialchars($account['account_number']) ?>)
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          
          <div class="mb-3">
            <label class="form-label">ফি নির্বাচন করুন</label>
            <div id="feeSelection">
              <?php foreach ($fees as $f): $due = (float)($f['amount'] - $f['paid_amount']); ?>
                <?php if ($due > 0): ?>
                  <div class="form-check mb-2">
                    <input class="form-check-input fee-checkbox" type="checkbox" 
                           id="fee_<?= $f['id'] ?>" 
                           value="<?= $f['id'] ?>" 
                           data-description="<?= htmlspecialchars($f['fee_type'] . ($f['month'] ? ' - ' . $f['month'] : '')) ?>"
                           data-amount="<?= $due ?>">
                    <label class="form-check-label" for="fee_<?= $f['id'] ?>">
                      <?= htmlspecialchars($f['fee_type']) ?><?= $f['month'] ? ' - ' . htmlspecialchars($f['month']) : '' ?> 
                      (৳<?= number_format($due, 2) ?>)
                    </label>
                  </div>
                <?php endif; ?>
              <?php endforeach; ?>
            </div>
            <div class="mt-2">
              <button type="button" class="btn btn-sm btn-outline-primary" id="selectAllFees">সব নির্বাচন করুন</button>
              <button type="button" class="btn btn-sm btn-outline-secondary" id="clearAllFees">সব মুছুন</button>
            </div>
          </div>
          
          <div class="mb-3">
            <label for="totalAmount" class="form-label">মোট পরিমাণ (৳)</label>
            <input type="number" class="form-control" id="totalAmount" value="0.00" step="0.01" min="0" readonly>
          </div>
          
          <div class="mb-3" id="bankDetails" style="display: none;">
            <h6>ব্যাংক তথ্য:</h6>
            <div class="card">
              <div class="card-body">
                <p><strong>ব্যাংকের নাম:</strong> <span id="selectedBankName"></span></p>
                <p><strong>ব্রাঞ্চ:</strong> <span id="selectedBranch"></span></p>
                <p><strong>একাউন্ট নম্বর:</strong> <span id="selectedAccountNo"></span></p>
                <p><strong>একাউন্ট নাম:</strong> <span id="selectedAccountName"></span></p>
              </div>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
        <button type="button" class="btn btn-primary" id="previewReceiptBtn">প্রিভিউ</button>
      </div>
    </div>
  </div>
</div>

<!-- Receipt Preview Modal -->
<div class="modal fade" id="receiptPreviewModal" tabindex="-1" aria-labelledby="receiptPreviewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="receiptPreviewModalLabel">রসিদ প্রিভিউ</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="receiptPreviewContent"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
        <button type="button" class="btn btn-success" id="printReceiptBtn">
          <i class="fas fa-print"></i> প্রিন্ট করুন
        </button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Handle bank account selection
  document.getElementById('bankAccount').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    if (selectedOption.value) {
      document.getElementById('selectedBankName').textContent = selectedOption.getAttribute('data-bank');
      document.getElementById('selectedBranch').textContent = selectedOption.getAttribute('data-branch');
      document.getElementById('selectedAccountNo').textContent = selectedOption.getAttribute('data-account');
      document.getElementById('selectedAccountName').textContent = selectedOption.getAttribute('data-name');
      document.getElementById('bankDetails').style.display = 'block';
    } else {
      document.getElementById('bankDetails').style.display = 'none';
    }
  });

  // Handle fee selection
  document.querySelectorAll('.fee-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', updateTotalAmount);
  });
  
  // Select all fees
  document.getElementById('selectAllFees').addEventListener('click', function() {
    document.querySelectorAll('.fee-checkbox').forEach(checkbox => {
      checkbox.checked = true;
    });
    updateTotalAmount();
  });
  
  // Clear all fees
  document.getElementById('clearAllFees').addEventListener('click', function() {
    document.querySelectorAll('.fee-checkbox').forEach(checkbox => {
      checkbox.checked = false;
    });
    updateTotalAmount();
  });
  
  // Update total amount based on selected fees
  function updateTotalAmount() {
    let total = 0;
    document.querySelectorAll('.fee-checkbox:checked').forEach(checkbox => {
      total += parseFloat(checkbox.getAttribute('data-amount')) || 0;
    });
    document.getElementById('totalAmount').value = total.toFixed(2);
  }
  
  // Preview receipt
  document.getElementById('previewReceiptBtn').addEventListener('click', function() {
    const bankAccountSelect = document.getElementById('bankAccount');
    
    if (!bankAccountSelect.value) {
      alert('দয়া করে ব্যাংক নির্বাচন করুন');
      return;
    }
    
    // Get selected fees
    const selectedFees = [];
    const selectedFeeIds = [];
    document.querySelectorAll('.fee-checkbox:checked').forEach(checkbox => {
      selectedFees.push({
        description: checkbox.getAttribute('data-description'),
        amount: parseFloat(checkbox.getAttribute('data-amount'))
      });
      selectedFeeIds.push(checkbox.value);
    });
    
    if (selectedFees.length === 0) {
      alert('দয়া করে অন্তত একটি ফি নির্বাচন করুন');
      return;
    }
    
    // Store selected fee IDs in a hidden field for form submission
    let hiddenInput = document.getElementById('selectedFeeIds');
    if (!hiddenInput) {
      hiddenInput = document.createElement('input');
      hiddenInput.type = 'hidden';
      hiddenInput.id = 'selectedFeeIds';
      hiddenInput.name = 'selected_fee_ids';
      document.getElementById('bankReceiptForm').appendChild(hiddenInput);
    }
    hiddenInput.value = JSON.stringify(selectedFeeIds);
    
    const totalAmount = selectedFees.reduce((sum, fee) => sum + fee.amount, 0);
    
    const selectedOption = bankAccountSelect.options[bankAccountSelect.selectedIndex];
    const bankInfo = {
      bankName: selectedOption.getAttribute('data-bank'),
      branch: selectedOption.getAttribute('data-branch'),
      accountNo: selectedOption.getAttribute('data-account'),
      accountName: selectedOption.getAttribute('data-name')
    };
    
    const studentInfo = {
      name: '<?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?>',
      studentId: '<?= htmlspecialchars($student['student_id']) ?>',
      className: '<?= htmlspecialchars(($student['class_name'] ?? '') . ' - ' . ($student['section'] ?? '')) ?>'
    };
    
    // Generate receipt HTML
    const receiptHtml = generateReceipt(studentInfo, bankInfo, totalAmount, selectedFees);
    document.getElementById('receiptPreviewContent').innerHTML = receiptHtml;
    
    // Show preview modal
    const previewModal = new bootstrap.Modal(document.getElementById('receiptPreviewModal'));
    previewModal.show();
  });
  
  // Print receipt
  document.getElementById('printReceiptBtn').addEventListener('click', function() {
    const printContents = document.getElementById('receiptPreviewContent').innerHTML;
    const originalContents = document.body.innerHTML;
    
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
    location.reload();
  });
  
<?php
// Get customizable receipt settings
$receipt_settings = [
    'school_name' => '',
    'address' => '',
    'receipt_title' => '',
    'subtitle' => '',
    'watermark' => ''
];

try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'bank_receipt_%'");
    while ($row = $stmt->fetch()) {
        $key = str_replace('bank_receipt_', '', $row['setting_key']);
        $receipt_settings[$key] = $row['setting_value'];
    }
} catch (Exception $e) {
    // Use defaults if settings not found
}

// Set defaults if empty
if (empty($receipt_settings['school_name'])) {
    $receipt_settings['school_name'] = 'কার্পাসডাঙ্গা মাধ্যমিক বালিকা বিদ্যালয়';
}
if (empty($receipt_settings['address'])) {
    $receipt_settings['address'] = 'কার্পাসডাঙ্গা ভুমিহীন পাড়া, দামুড়হুদা, চুয়াডাঙ্গা';
}
if (empty($receipt_settings['receipt_title'])) {
    $receipt_settings['receipt_title'] = 'ব্যাংক ডিপোজিট রসিদ';
}
if (empty($receipt_settings['watermark'])) {
    $receipt_settings['watermark'] = 'DEPOSIT';
}
?>

  // Generate receipt HTML
  function generateReceipt(studentInfo, bankInfo, amount, feeDetails) {
    const now = new Date();
    const dateTime = now.toLocaleDateString('bn-BD') + ' ' + now.toLocaleTimeString('bn-BD');
    // Generate a simple receipt number based on timestamp
    const receiptNo = 'RCP-' + now.getFullYear() + ('0' + (now.getMonth() + 1)).slice(-2) + ('0' + now.getDate()).slice(-2) + '-' + ('0' + now.getHours()).slice(-2) + ('0' + now.getMinutes()).slice(-2) + ('0' + now.getSeconds()).slice(-2);
    // Generate a transaction ID
    const transactionId = 'TXN-' + now.getFullYear() + ('0' + (now.getMonth() + 1)).slice(-2) + ('0' + now.getDate()).slice(-2) + '-' + Math.floor(1000 + Math.random() * 9000);
    
    // Generate fee details table rows
    let feeRows = '';
    let totalAmount = 0;
    
    feeDetails.forEach(fee => {
      feeRows += `
        <tr>
          <td>${fee.description}</td>
          <td class="amount-highlight">৳${fee.amount.toFixed(2)}</td>
        </tr>`;
      totalAmount += fee.amount;
    });
    
    // Add total row
    feeRows += `
      <tr class="total-row">
        <td><strong>মোট</strong></td>
        <td class="amount-highlight"><strong>৳${totalAmount.toFixed(2)}</strong></td>
      </tr>`;
    
    return `
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap');
        
        @media print {
          @page { 
            size: A4 landscape; 
            margin: 5mm; 
          }
          body { 
            font-size: 12px; 
            margin: 0;
            padding: 0;
            font-family: 'Hind Siliguri', sans-serif;
          }
          .no-print { display: none !important; }
          .receipt-container { 
            width: 100%;
            max-width: 100%;
          }
          .receipt-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
          }
        }
        
        .receipt-container { 
          max-width: 100%;
          margin: 0 auto; 
          font-family: 'Hind Siliguri', sans-serif;
        }
        
        .receipt-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 15px;
        }
        
        .receipt-header {
          text-align: center;
          margin-bottom: 15px;
          border-bottom: 2px solid #000;
          padding-bottom: 8px;
        }
        
        .receipt-title {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 3px;
        }
        
        .copy-section {
          border: 1px solid #000;
          padding: 12px;
          position: relative;
          background: #fff;
          break-inside: avoid;
        }
        
        .copy-title {
          text-align: center;
          font-weight: bold;
          margin-bottom: 12px;
          font-size: 14px;
          padding: 5px;
        }
        
        /* Different colors for each copy */
        .office-copy .copy-title {
          background-color: #e3f2fd;
          color: #1976d2;
          font-weight: bold;
        }
        
        .customer-copy .copy-title {
          background-color: #e8f5e9;
          color: #388e3c;
          font-weight: bold;
        }
        
        .bank-copy .copy-title {
          background-color: #fff3e0;
          color: #f57c00;
          font-weight: bold;
        }
        
        .copy-label {
          position: absolute;
          top: 5px;
          right: 10px;
          font-weight: bold;
          font-size: 11px;
        }
        
        .info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 8px;
          margin-bottom: 10px;
        }
        
        .student-info-row {
          grid-column: 1 / -1;
          display: flex;
          flex-wrap: wrap;
          gap: 15px;
          padding: 10px;
          background-color: #f5f5f5;
          border-radius: 5px;
          margin-bottom: 10px;
        }
        
        .student-info-item {
          display: flex;
          align-items: center;
          gap: 5px;
        }
        
        .student-info-label {
          font-weight: bold;
          color: #333;
        }
        
        .fee-details-table {
          grid-column: 1 / -1;
          width: 100%;
          border-collapse: collapse;
          margin: 10px 0;
          background-color: #fff;
        }
        
        .fee-details-table th {
          background-color: #e3f2fd;
          padding: 8px;
          text-align: left;
          border-bottom: 2px solid #bbdefb;
        }
        
        .fee-details-table td {
          padding: 8px;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .fee-details-table tr:last-child td {
          border-bottom: none;
        }
        
        .fee-details-table tr:nth-child(even) {
          background-color: #f9f9f9;
        }
        
        .total-row {
          font-weight: bold;
          background-color: #fff3e0 !important;
        }
        
        .info-row {
          margin-bottom: 6px;
          display: flex;
          align-items: center;
        }
        
        .info-label {
          font-weight: bold;
          width: 120px;
          flex-shrink: 0;
        }
        
        .amount-words {
          margin: 12px 0;
          font-style: italic;
          font-size: 11px;
        }
        
        .signature-section {
          margin-top: 25px;
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 20px;
        }
        
        .signature-box {
          text-align: center;
        }
        
        .signature-line {
          margin-top: 40px;
          border-top: 1px solid #000;
          padding-top: 5px;
          font-size: 11px;
        }
        
        .collector-signature-seal {
          display: flex;
          justify-content: center;
          align-items: flex-end;
          margin-top: 40px;
          gap: 20px;
        }
        
        .signature-part, .seal-part {
          text-align: center;
        }
        
        .signature-line-single {
          width: 120px;
          border-top: 1px solid #000;
          padding-top: 5px;
          margin: 0 auto;
          font-size: 11px;
        }
        
        .seal-area-single {
          width: 80px;
          height: 40px;
          border: 1px dashed #999;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          color: #666;
          margin: 0 auto;
        }
        
        .seal-area {
          margin-top: 20px;
          border: 1px dashed #999;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          color: #666;
        }
        
        .watermark {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%) rotate(-45deg);
          font-size: 70px;
          font-weight: bold;
          color: rgba(0,0,0,0.05);
          pointer-events: none;
          z-index: 0;
          white-space: nowrap;
        }
        
        .receipt-no {
          text-align: right;
          font-size: 11px;
          margin-bottom: 5px;
        }
        
        .transaction-details {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 8px;
          background-color: #f0f8ff;
          padding: 8px;
          border-radius: 4px;
          margin: 8px 0;
        }
        
        .bank-details {
          background-color: #f5f5f5;
          padding: 8px;
          margin: 10px 0;
          border-radius: 4px;
        }
        
        .bank-details .info-label {
          width: 140px;
        }
      </style>
      
      <div class="receipt-container">
        <div class="receipt-grid">
          <!-- Office Copy -->
          <div class="copy-section office-copy">
            <div class="watermark"><?php echo htmlspecialchars($receipt_settings['watermark']); ?></div>
            <div class="receipt-content">
              <div class="copy-label">অফিস কপি</div>
              <div class="receipt-header">
                <div class="receipt-title"><?php echo htmlspecialchars($receipt_settings['school_name']); ?></div>
                <?php if (!empty($receipt_settings['address'])): ?>
                <div style="font-size: 12px;"><?php echo htmlspecialchars($receipt_settings['address']); ?></div>
                <?php endif; ?>
                <div style="font-size: 13px; margin-top: 5px;"><?php echo htmlspecialchars($receipt_settings['receipt_title']); ?></div>
                <?php if (!empty($receipt_settings['subtitle'])): ?>
                <div style="font-size: 12px; margin-top: 3px;"><?php echo htmlspecialchars($receipt_settings['subtitle']); ?></div>
                <?php endif; ?>
              </div>
              
              <div class="receipt-no"><strong>রসিদ নং:</strong> ${receiptNo}</div>
              
              <div class="transaction-details">
                <div class="info-row">
                  <span class="info-label">তারিখ ও সময়:</span>
                  <span>${dateTime}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">ট্রানজেকশন আইডি:</span>
                  <span>${transactionId}</span>
                </div>
              </div>
              
              <div class="copy-title">ব্যাংক ডিপোজিট রসিদ (অফিস কপি)</div>
              
              <div class="info-grid">
                <div class="student-info-row">
                  <div class="student-info-item">
                    <span class="student-info-label">নাম:</span>
                    <span>${studentInfo.name}</span>
                  </div>
                  <div class="student-info-item">
                    <span class="student-info-label">আইডি:</span>
                    <span>${studentInfo.studentId}</span>
                  </div>
                  <div class="student-info-item">
                    <span class="student-info-label">ক্লাস:</span>
                    <span>${studentInfo.className}</span>
                  </div>
                </div>
              </div>
              
              <table class="fee-details-table">
                <thead>
                  <tr>
                    <th>ফি বিবরণ</th>
                    <th>পরিমাণ</th>
                  </tr>
                </thead>
                <tbody>
                  ${feeRows}
                </tbody>
              </table>
              
              <div class="amount-words">
                টাকা (কথায়): ${numberToWordsBengali(totalAmount)} টাকা মাত্র
              </div>
              
              <div class="bank-details">
                <div style="font-weight: bold; margin-bottom: 5px;">ব্যাংক তথ্য:</div>
                <div class="info-row">
                  <span class="info-label">ব্যাংকের নাম:</span>
                  <span>${bankInfo.bankName}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">ব্রাঞ্চ:</span>
                  <span>${bankInfo.branch}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">একাউন্ট নম্বর:</span>
                  <span>${bankInfo.accountNo}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">একাউন্ট নাম:</span>
                  <span>${bankInfo.accountName}</span>
                </div>
              </div>
              
              <div class="signature-section">
                <div class="signature-box">
                  <div class="collector-signature-seal">
                    <div class="signature-part">
                      <div class="signature-line-single">জমাগ্রহনকারী স্বাক্ষর ও সীল</div>
                    </div>
                    
                  </div>
                </div>
                <div class="signature-box">
                  <div class="signature-line">ছাত্র/ছাত্রীর স্বাক্ষর</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Customer Copy -->
          <div class="copy-section customer-copy">
            <div class="watermark"><?php echo htmlspecialchars($receipt_settings['watermark']); ?></div>
            <div class="receipt-content">
              <div class="copy-label">গ্রাহক কপি</div>
              <div class="receipt-header">
                <div class="receipt-title"><?php echo htmlspecialchars($receipt_settings['school_name']); ?></div>
                <?php if (!empty($receipt_settings['address'])): ?>
                <div style="font-size: 12px;"><?php echo htmlspecialchars($receipt_settings['address']); ?></div>
                <?php endif; ?>
                <div style="font-size: 13px; margin-top: 5px;"><?php echo htmlspecialchars($receipt_settings['receipt_title']); ?></div>
                <?php if (!empty($receipt_settings['subtitle'])): ?>
                <div style="font-size: 12px; margin-top: 3px;"><?php echo htmlspecialchars($receipt_settings['subtitle']); ?></div>
                <?php endif; ?>
              </div>
              
              <div class="receipt-no"><strong>রসিদ নং:</strong> ${receiptNo}</div>
              
              <div class="transaction-details">
                <div class="info-row">
                  <span class="info-label">তারিখ ও সময়:</span>
                  <span>${dateTime}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">ট্রানজেকশন আইডি:</span>
                  <span>${transactionId}</span>
                </div>
              </div>
              
              <div class="copy-title">ব্যাংক ডিপোজিট রসিদ (গ্রাহক কপি)</div>
              
              <div class="info-grid">
                <div class="student-info-row">
                  <div class="student-info-item">
                    <span class="student-info-label">নাম:</span>
                    <span>${studentInfo.name}</span>
                  </div>
                  <div class="student-info-item">
                    <span class="student-info-label">আইডি:</span>
                    <span>${studentInfo.studentId}</span>
                  </div>
                  <div class="student-info-item">
                    <span class="student-info-label">ক্লাস:</span>
                    <span>${studentInfo.className}</span>
                  </div>
                </div>
              </div>
              
              <table class="fee-details-table">
                <thead>
                  <tr>
                    <th>ফি বিবরণ</th>
                    <th>পরিমাণ</th>
                  </tr>
                </thead>
                <tbody>
                  ${feeRows}
                </tbody>
              </table>
              
              <div class="amount-words">
                টাকা (কথায়): ${numberToWordsBengali(totalAmount)} টাকা মাত্র
              </div>
              
              <div class="bank-details">
                <div style="font-weight: bold; margin-bottom: 5px;">ব্যাংক তথ্য:</div>
                <div class="info-row">
                  <span class="info-label">ব্যাংকের নাম:</span>
                  <span>${bankInfo.bankName}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">ব্রাঞ্চ:</span>
                  <span>${bankInfo.branch}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">একাউন্ট নম্বর:</span>
                  <span>${bankInfo.accountNo}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">একাউন্ট নাম:</span>
                  <span>${bankInfo.accountName}</span>
                </div>
              </div>
              
              <div class="signature-section">
                <div class="signature-box">
                  <div class="collector-signature-seal">
                    <div class="signature-part">
                      <div class="signature-line-single">জমাগ্রহনকারী স্বাক্ষর ও সীল</div>
                    </div>
                  
                  </div>
                </div>
                <div class="signature-box">
                  <div class="signature-line">ছাত্র/ছাত্রীর স্বাক্ষর</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Bank Copy -->
          <div class="copy-section bank-copy">
            <div class="watermark"><?php echo htmlspecialchars($receipt_settings['watermark']); ?></div>
            <div class="receipt-content">
              <div class="copy-label">ব্যাংক কপি</div>
              <div class="receipt-header">
                <div class="receipt-title"><?php echo htmlspecialchars($receipt_settings['school_name']); ?></div>
                <?php if (!empty($receipt_settings['address'])): ?>
                <div style="font-size: 12px;"><?php echo htmlspecialchars($receipt_settings['address']); ?></div>
                <?php endif; ?>
                <div style="font-size: 13px; margin-top: 5px;"><?php echo htmlspecialchars($receipt_settings['receipt_title']); ?></div>
                <?php if (!empty($receipt_settings['subtitle'])): ?>
                <div style="font-size: 12px; margin-top: 3px;"><?php echo htmlspecialchars($receipt_settings['subtitle']); ?></div>
                <?php endif; ?>
              </div>
              
              <div class="receipt-no"><strong>রসিদ নং:</strong> ${receiptNo}</div>
              
              <div class="transaction-details">
                <div class="info-row">
                  <span class="info-label">তারিখ ও সময়:</span>
                  <span>${dateTime}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">ট্রানজেকশন আইডি:</span>
                  <span>${transactionId}</span>
                </div>
              </div>
              
              <div class="copy-title">ব্যাংক ডিপোজিট রসিদ (ব্যাংক কপি)</div>
              
              <div class="info-grid">
                <div class="student-info-row">
                  <div class="student-info-item">
                    <span class="student-info-label">নাম:</span>
                    <span>${studentInfo.name}</span>
                  </div>
                  <div class="student-info-item">
                    <span class="student-info-label">আইডি:</span>
                    <span>${studentInfo.studentId}</span>
                  </div>
                  <div class="student-info-item">
                    <span class="student-info-label">ক্লাস:</span>
                    <span>${studentInfo.className}</span>
                  </div>
                </div>
              </div>
              
              <table class="fee-details-table">
                <thead>
                  <tr>
                    <th>ফি বিবরণ</th>
                    <th>পরিমাণ</th>
                  </tr>
                </thead>
                <tbody>
                  ${feeRows}
                </tbody>
              </table>
              
              <div class="amount-words">
                টাকা (কথায়): ${numberToWordsBengali(totalAmount)} টাকা মাত্র
              </div>
              
              <div class="bank-details">
                <div style="font-weight: bold; margin-bottom: 5px;">ব্যাংক তথ্য:</div>
                <div class="info-row">
                  <span class="info-label">ব্যাংকের নাম:</span>
                  <span>${bankInfo.bankName}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">ব্রাঞ্চ:</span>
                  <span>${bankInfo.branch}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">একাউন্ট নম্বর:</span>
                  <span>${bankInfo.accountNo}</span>
                </div>
                
                <div class="info-row">
                  <span class="info-label">একাউন্ট নাম:</span>
                  <span>${bankInfo.accountName}</span>
                </div>
              </div>
              
              <div class="signature-section">
                <div class="signature-box">
                  <div class="collector-signature-seal">
                    <div class="signature-part">
                      <div class="signature-line-single">জমাগ্রহনকারী স্বাক্ষর ও সীল</div>
                    </div>
                  
                  </div>
                </div>
                <div class="signature-box">
                  <div class="signature-line">ছাত্র/ছাত্রীর স্বাক্ষর</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
  }
  
  // Convert number to Bengali words
  function numberToWordsBengali(num) {
    const banglaNumbers = ['শূন্য', 'এক', 'দুই', 'তিন', 'চার', 'পাঁচ', 'ছয়', 'সাত', 'আট', 'নয়'];
    const banglaTens = ['দশ', 'এগারো', 'বারো', 'তেরো', 'চৌদ্দ', 'পনেরো', 'ষোল', 'সতেরো', 'আঠারো', 'ঊনিশ'];
    const banglaDecades = ['', 'দশ', 'বিশ', 'ত্রিশ', 'চল্লিশ', 'পঞ্চাশ', 'ষাট', 'সত্তর', 'আশি', 'নব্বই'];
    const banglaHundreds = ['শত', 'হাজার', 'লক্ষ', 'কোটি'];
    
    if (num === 0) return 'শূন্য';
    
    // Simple implementation for numbers up to 99999
    const integerPart = Math.floor(num);
    const decimalPart = Math.round((num - integerPart) * 100);
    
    let result = '';
    
    if (integerPart < 10) {
      result = banglaNumbers[integerPart];
    } else if (integerPart < 20) {
      result = banglaTens[integerPart - 10];
    } else if (integerPart < 100) {
      const tens = Math.floor(integerPart / 10);
      const units = integerPart % 10;
      result = banglaDecades[tens] + (units > 0 ? ' ' + banglaNumbers[units] : '');
    } else if (integerPart < 1000) {
      const hundreds = Math.floor(integerPart / 100);
      const remainder = integerPart % 100;
      result = banglaNumbers[hundreds] + ' ' + banglaHundreds[0];
      if (remainder > 0) {
        if (remainder < 10) {
          result += ' ' + banglaNumbers[remainder];
        } else if (remainder < 20) {
          result += ' ' + banglaTens[remainder - 10];
        } else {
          const tens = Math.floor(remainder / 10);
          const units = remainder % 10;
          result += ' ' + banglaDecades[tens] + (units > 0 ? ' ' + banglaNumbers[units] : '');
        }
      }
    } else {
      result = integerPart.toString(); // Fallback to number for larger values
    }
    
    if (decimalPart > 0) {
      result += ' দশমিক ';
      if (decimalPart < 10) {
        result += 'শূন্য ' + banglaNumbers[decimalPart];
      } else {
        const decTens = Math.floor(decimalPart / 10);
        const decUnits = decimalPart % 10;
        result += banglaDecades[decTens] + (decUnits > 0 ? ' ' + banglaNumbers[decUnits] : '');
      }
    }
    
    return result;
  }
</script>
</body>
</html>