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

// Auth check
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Load dropdown data
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$groups  = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();

// AJAX endpoints
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json; charset=UTF-8');

    try {
        $action = $_POST['action'] ?? '';

        if ($action === 'get_students_with_fees') {
            $session     = $_POST['session'] ?? '';
            $class_id    = $_POST['class_id'] ?? '';
            $group_name  = $_POST['group_name'] ?? '';
            $fee_status  = $_POST['fee_status'] ?? 'due_only'; // due_only|all
            $year        = trim($_POST['academic_year'] ?? '');
            $month       = trim($_POST['month'] ?? '');
            $fee_type    = trim($_POST['fee_type'] ?? '');

            // Build WHERE for student filters
            $whereS = ["s.status='active'"];
            $params = [];
            if (!empty($session))   { $whereS[] = 's.session = ?'; $params[] = $session; }
            if (!empty($class_id))  { $whereS[] = 's.class_id = ?'; $params[] = $class_id; }
            if ($group_name !== '') { $whereS[] = 'COALESCE(s.group_name, "") = ?'; $params[] = $group_name; }
            $whereS = implode(' AND ', $whereS);

            // Build extra filter for fees
            $feeFilter = ['1=1'];
            if (!empty($year))     { $feeFilter[] = 'f.academic_year = ?'; $params[] = $year; }
            if (!empty($month))    { $feeFilter[] = 'f.month = ?';         $params[] = $month; }
            if (!empty($fee_type)) { $feeFilter[] = 'f.fee_type = ?';      $params[] = $fee_type; }
            $feeFilter = implode(' AND ', $feeFilter);

            // Aggregate due per student
            $sql = "
                SELECT 
                    s.id,
                    s.student_id,
                    s.first_name,
                    s.last_name,
                    s.roll_number,
                    s.session,
                    c.name AS class_name,
                    c.section AS class_section,
                    COALESCE(s.group_name,'') AS group_name,
                    COALESCE(SUM(CASE WHEN f.id IS NOT NULL THEN (f.amount - COALESCE(f.paid_amount,0)) ELSE 0 END), 0) AS total_due,
                    COUNT(CASE WHEN f.id IS NOT NULL AND (f.amount - COALESCE(f.paid_amount,0)) > 0 THEN 1 END) AS due_items
                FROM students s
                JOIN classes c ON s.class_id = c.id
                LEFT JOIN fees f ON (
                    f.student_id = s.id 
                    AND $feeFilter
                )
                WHERE $whereS
                GROUP BY s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, c.name, c.section, s.group_name
                ORDER BY s.roll_number
            ";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $rows = $stmt->fetchAll();

            // If due_only, filter out zero due
            if ($fee_status === 'due_only') {
                $rows = array_values(array_filter($rows, function($r){ return floatval($r['total_due']) > 0; }));
            }

            echo json_encode(['success'=>true, 'students'=>$rows]);
            exit();
        }

        if ($action === 'get_student_fees') {
            $student_id = intval($_POST['student_id'] ?? 0);
            $year  = trim($_POST['academic_year'] ?? '');
            $month = trim($_POST['month'] ?? '');
            $fee_type = trim($_POST['fee_type'] ?? '');

            if ($student_id <= 0) {
                echo json_encode(['success'=>false, 'message'=>'Invalid student']);
                exit();
            }

            $where = ['f.student_id = ?'];
            $params = [$student_id];
            if (!empty($year))     { $where[] = 'f.academic_year = ?'; $params[] = $year; }
            if (!empty($month))    { $where[] = 'f.month = ?';         $params[] = $month; }
            if (!empty($fee_type)) { $where[] = 'f.fee_type = ?';      $params[] = $fee_type; }
            $where = implode(' AND ', $where);

            $stmt = $pdo->prepare("SELECT f.id, f.fee_type, f.amount, COALESCE(f.paid_amount,0) AS paid_amount, (f.amount-COALESCE(f.paid_amount,0)) AS due, f.academic_year, f.month, f.due_date, f.status FROM fees f WHERE $where ORDER BY f.due_date ASC, f.id ASC");
            $stmt->execute($params);
            $fees = array_values(array_filter($stmt->fetchAll(), function($r){ return floatval($r['due']) > 0.0001; }));

            echo json_encode(['success'=>true, 'fees'=>$fees]);
            exit();
        }

        if ($action === 'collect_payment') {
            $student_id = intval($_POST['student_id'] ?? 0);
            $payments_json = $_POST['payments'] ?? '[]';
            $payment_method = trim($_POST['payment_method'] ?? 'Cash');
            $note = trim($_POST['note'] ?? '');
            $payments = json_decode($payments_json, true);
            if (!is_array($payments)) $payments = [];

            if ($student_id <= 0 || empty($payments)) {
                echo json_encode(['success'=>false, 'message'=>'ডাটা সঠিক নয়']);
                exit();
            }

            try {
                $pdo->beginTransaction();
                $total_paid = 0.0;
                $receipt_items = [];

                // Lock rows to avoid race (best effort)
                foreach ($payments as $p) {
                    $fee_id = intval($p['fee_id'] ?? 0);
                    $pay_amount = floatval($p['pay_amount'] ?? 0);
                    if ($fee_id <= 0 || $pay_amount <= 0) continue;

                    // Get current fee row
                    $stmt = $pdo->prepare("SELECT id, student_id, fee_type, amount, COALESCE(paid_amount,0) AS paid_amount, academic_year, month, due_date, status FROM fees WHERE id=? AND student_id=? FOR UPDATE");
                    $stmt->execute([$fee_id, $student_id]);
                    $fee = $stmt->fetch();
                    if (!$fee) continue;

                    $due = floatval($fee['amount']) - floatval($fee['paid_amount']);
                    if ($due <= 0) continue;

                    $apply = min($due, $pay_amount);
                    if ($apply <= 0) continue;

                    // Update fee row
                    $new_paid = floatval($fee['paid_amount']) + $apply;
                    $new_status = ($new_paid + 0.0001 >= floatval($fee['amount'])) ? 'paid' : 'pending';
                    $upd = $pdo->prepare("UPDATE fees SET paid_amount = ?, status = ? WHERE id = ?");
                    $upd->execute([$new_paid, $new_status, $fee_id]);

                    // Record payment into fee_payments for unified ledger
                    $ins = $pdo->prepare("INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by) VALUES (?, ?, NOW(), ?, NULL, ?, ?)");
                    $ins->execute([$fee_id, $apply, $payment_method, $note, $_SESSION['user_id'] ?? null]);

                    $total_paid += $apply;
                    $receipt_items[] = [
                        'fee_type' => $fee['fee_type'],
                        'academic_year' => $fee['academic_year'],
                        'month' => $fee['month'],
                        'amount' => floatval($fee['amount']),
                        'paid_now' => $apply,
                    ];
                }

                // Fetch student info for receipt
                $sStmt = $pdo->prepare("SELECT s.student_id, s.first_name, s.last_name, s.roll_number, s.session, COALESCE(s.group_name,'') AS group_name, c.name AS class_name, c.section AS class_section FROM students s JOIN classes c ON s.class_id=c.id WHERE s.id=?");
                $sStmt->execute([$student_id]);
                $stu = $sStmt->fetch();

                $pdo->commit();

                // SMS: payment receipt to student/guardian
                try {
                    require_once __DIR__ . '/../includes/sms_helper.php';
                    
                    // Check if non-musking SMS service is enabled
                    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
                    $stmt->execute();
                    $result = $stmt->fetch();
                    $nonMuskingEnabled = $result && $result['setting_value'] === '1';
                    
                    // Check if fee payment notifications are enabled
                    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_fee_notifications'");
                    $stmt->execute();
                    $result = $stmt->fetch();
                    $feeNotificationsEnabled = $result && $result['setting_value'] === '1';
                    
                    if ($nonMuskingEnabled && $feeNotificationsEnabled) {
                        $cfg = sms_config();
                        $numbers = [];
                        // Fetch phones
                        $pStmt = $pdo->prepare('SELECT phone, guardian_phone, first_name, last_name FROM students WHERE id=?');
                        $pStmt->execute([$student_id]);
                        $p = $pStmt->fetch();
                        if (!empty($p['phone'])) $numbers[] = $p['phone'];
                        if (($cfg['send_to_guardian_also'] ?? true) && !empty($p['guardian_phone'])) $numbers[] = $p['guardian_phone'];

                        if (!empty($numbers)) {
                            // Compute due after this payment
                            $dueStmt = $pdo->prepare('SELECT COALESCE(SUM(amount-COALESCE(paid_amount,0)),0) AS due FROM fees WHERE student_id=?');
                            $dueStmt->execute([$student_id]);
                            $due = (float)($dueStmt->fetch()['due'] ?? 0);
                            $vars = [
                                'name' => trim(($p['first_name'] ?? '').' '.($p['last_name'] ?? '')),
                                'paid_amount' => number_format((float)$total_paid, 2),
                                'due_amount' => number_format($due, 2),
                            ];
                            
                            // Try to use non-musking template, fallback to hardcoded message
                            $result = non_musking_send_template($pdo, 'fee_payment', $vars, $numbers);
                            
                            // If template doesn't exist, use hardcoded message
                            if (!$result['success'] && strpos($result['message'], 'Template not found') !== false) {
                                $feeMessage = "প্রিয় {$vars['name']}, আপনার ফি {$vars['paid_amount']} টাকা গৃহীত হয়েছে। বর্তমান বকেয়া: {$vars['due_amount']} টাকা। ধন্যবাদ।";
                                non_musking_send($pdo, $numbers, $feeMessage, ['template'=>'fee_payment']);
                            }
                        } else {
                            // Log that no phone numbers were found for the student
                            if (function_exists('sms_log')) sms_log('No phone numbers found for student ID: ' . $student_id);
                        }
                    } else {
                        // Show why notifications were not sent
                        $reasons = [];
                        if (!$nonMuskingEnabled) {
                            $reasons[] = 'নন-মাস্কিং এসএমএস সার্ভিস নিষ্ক্রিয়';
                        }
                        if (!$feeNotificationsEnabled) {
                            $reasons[] = 'ফি নোটিফিকেশন নিষ্ক্রিয়';
                        }
                        if (function_exists('sms_log')) sms_log('SMS not sent to student ID: ' . $student_id . '. Reasons: ' . implode(', ', $reasons));
                    }
                } catch (Throwable $e) {
                    if (function_exists('sms_log')) sms_log('FEE SMS error: '.$e->getMessage());
                }

                // Store payment info in session for success page
                $_SESSION['payment_student_id'] = $student_id;
                $_SESSION['payment_amount'] = $total_paid;
                $_SESSION['payment_method'] = $payment_method;
                $_SESSION['payment_tran_id'] = 'CASH_' . time();

                // Prepare notification status information
                $notification_status = [
                    'sent' => false,
                    'reasons' => []
                ];
                
                if ($nonMuskingEnabled && $feeNotificationsEnabled) {
                    if (!empty($numbers)) {
                        $notification_status['sent'] = true;
                        $notification_status['message'] = 'নোটিফিকেশন পাঠানো হয়েছে';
                    } else {
                        $notification_status['reasons'][] = 'ফোন নম্বর পাওয়া যায়নি';
                    }
                } else {
                    if (!$nonMuskingEnabled) {
                        $notification_status['reasons'][] = 'নন-মাস্কিং এসএমএস সার্ভিস নিষ্ক্রিয়';
                    }
                    if (!$feeNotificationsEnabled) {
                        $notification_status['reasons'][] = 'ফি নোটিফিকেশন নিষ্ক্রিয়';
                    }
                }
                
                echo json_encode([
                    'success'=>true,
                    'message'=>'পেমেন্ট সফলভাবে সংরক্ষণ হয়েছে',
                    'total_paid'=>$total_paid,
                    'redirect_url'=>'payment_success_message.php',
                    'notification_status'=>$notification_status,
                    'receipt'=>[
                        'student'=>$stu,
                        'items'=>$receipt_items,
                        'payment_method'=>$payment_method,
                        'note'=>$note,
                        'datetime'=>date('Y-m-d H:i:s')
                    ]
                ]);
                exit();
            } catch (Exception $e) {
                $pdo->rollBack();
                echo json_encode(['success'=>false, 'message'=>'পেমেন্টে সমস্যা হয়েছে: '.$e->getMessage()]);
                exit();
            }
        }

        echo json_encode(['success'=>false, 'message'=>'Invalid action']);
        exit();

    } catch (Exception $e) {
        echo json_encode(['success'=>false, 'message'=>'সিস্টেম ত্রুটি: '.$e->getMessage()]);
        exit();
    }
}

?>
<!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">
    <style>
        html, body { font-family: 'Hind Siliguri', system-ui, -apple-system, 'Segoe UI', Roboto, Arial, sans-serif; }
        .filter-section { background-color: #f8f9fa; border-radius: 10px; padding: 16px; }
        .table-fixed { max-height: 520px; overflow-y: auto; }
        .student-row.due-zero { opacity: 0.6; }
        :root { --receipt-cols: 2; }
        @media print {
            @page { size: A4; margin: 8mm; }
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            .receipt-card { break-inside: avoid; page-break-inside: avoid; }
        }
        @media print and (orientation: landscape) {
            @page { size: A4 landscape; margin: 5mm; }
            .receipt-grid { grid-template-columns: repeat(4, 1fr) !important; }
        }
        .print-only { display: none; }
        .receipt-grid { display: grid; grid-template-columns: repeat(var(--receipt-cols), 1fr); gap: 6mm; }
        .receipt-card { border: 1.4px solid #000; border-radius: 8px; padding: 6mm; background: #fff; }
        .receipt-card.compact { padding: 4mm; }
        .receipt-title { font-weight: 700; font-size: 16px; text-align: center; margin-bottom: 6px; }
        .receipt-meta { font-size: 12px; color: #333; text-align: center; }
        .receipt-table td, .receipt-table th { font-size: 12px; padding: 3px 6px; }
        .controls { gap: 8px; }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <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="../index.php"><i class="fas fa-home"></i> হোম</a>
                <a class="nav-link" href="manage.php"><i class="fas fa-gear"></i> ফি ম্যানেজ</a>
                <a class="nav-link" href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি কালেক্ট</a>
                <a class="nav-link" href="reports.php"><i class="fas fa-chart-bar"></i> রিপোর্ট</a>
                <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">
        <div class="card no-print">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div><i class="fas fa-cash-register"></i> ফি কালেকশন</div>
                <div class="d-flex align-items-center controls">
                    <label class="me-2 small">প্রতি সারিতে রসিদ</label>
                    <select id="receiptCols" class="form-select form-select-sm" style="width:auto">
                        <option value="2" selected>2</option>
                        <option value="4">4</option>
                    </select>
                    <div class="form-check form-switch ms-2">
                        <input class="form-check-input" type="checkbox" id="receiptCompact">
                        <label class="form-check-label" for="receiptCompact">কমপ্যাক্ট</label>
                    </div>
                    <button class="btn btn-success btn-sm ms-2" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button>
                    <button class="btn btn-primary btn-sm ms-2" onclick="printLandscape()"><i class="fas fa-print"></i> ল্যান্ডস্কেপ প্রিন্ট</button>
                </div>
            </div>
            <div class="card-body">
                <div id="alertContainer"></div>

                <div class="filter-section mb-3">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-2">
                            <label class="form-label">সেশন</label>
                            <select class="form-select" id="filter_session">
                                <option value="">সব</option>
                                <?php foreach($sessions as $s): ?>
                                <option value="<?php echo htmlspecialchars($s['session_name']); ?>"><?php echo htmlspecialchars($s['session_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">ক্লাস</label>
                            <select class="form-select" id="filter_class">
                                <option value="">সব</option>
                                <?php foreach($classes as $c): ?>
                                <option value="<?php echo (int)$c['id']; ?>"><?php echo htmlspecialchars($c['name'].' - '.$c['section']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">গ্রুপ</label>
                            <select class="form-select" id="filter_group">
                                <option value="">সব</option>
                                <?php foreach($groups as $g): ?>
                                <option value="<?php echo htmlspecialchars($g['group_name']); ?>"><?php echo htmlspecialchars($g['group_name'].' ('.$g['group_code'].')'); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">শিক্ষাবর্ষ</label>
                            <input type="text" class="form-control" id="filter_year" placeholder="যেমন: ২০২৪">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">মাস</label>
                            <select class="form-select" id="filter_month">
                                <option value="">সব</option>
                                <option value="জানুয়ারি">জানুয়ারি</option>
                                <option value="ফেব্রুয়ারি">ফেব্রুয়ারি</option>
                                <option value="মার্চ">মার্চ</option>
                                <option value="এপ্রিল">এপ্রিল</option>
                                <option value="মে">মে</option>
                                <option value="জুন">জুন</option>
                                <option value="জুলাই">জুলাই</option>
                                <option value="আগস্ট">আগস্ট</option>
                                <option value="সেপ্টেম্বর">সেপ্টেম্বর</option>
                                <option value="অক্টোবর">অক্টোবর</option>
                                <option value="নভেম্বর">নভেম্বর</option>
                                <option value="ডিসেম্বর">ডিসেম্বর</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">ফি টাইপ</label>
                            <select class="form-select" id="filter_type">
                                <option value="">সব</option>
                                <option value="মাসিক বেতন">মাসিক বেতন</option>
                                <option value="ভর্তি ফি">ভর্তি ফি</option>
                                <option value="পরীক্ষা ফি">পরীক্ষা ফি</option>
                                <option value="বার্ষিক ফি">বার্ষিক ফি</option>
                                <option value="খেলাধুলা ফি">খেলাধুলা ফি</option>
                                <option value="লাইব্রেরি ফি">লাইব্রেরি ফি</option>
                                <option value="অন্যান্য">অন্যান্য</option>
                            </select>
                        </div>
                    </div>
                    <div class="mt-3 d-flex gap-2">
                        <button class="btn btn-primary" onclick="loadStudents()"><i class="fas fa-search"></i> শিক্ষার্থী খুঁজুন</button>
                        <div class="form-check ms-2">
                            <input class="form-check-input" type="checkbox" id="showAll">
                            <label class="form-check-label" for="showAll">সব (শূন্য বকেয়াসহ)</label>
                        </div>
                    </div>
                </div>

                <div class="table-responsive table-fixed">
                    <table class="table table-bordered table-striped align-middle" id="studentsTable">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 70px">রোল</th>
                                <th style="width: 140px">স্টুডেন্ট আইডি</th>
                                <th>নাম</th>
                                <th>সেশন</th>
                                <th>ক্লাস</th>
                                <th>গ্রুপ</th>
                                <th class="text-end" style="width: 120px">মোট বকেয়া</th>
                                <th style="width: 140px" class="text-end">অ্যাকশন</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td colspan="8" class="text-center text-muted">ফিল্টার বেছে নিয়ে সার্চ করুন</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Receipts Area (Printable) -->
        <div id="receiptsArea" class="mt-3 print-only">
            <div id="receiptsGrid" class="receipt-grid"></div>
        </div>

        <!-- Collect Modal -->
        <div class="modal fade" id="collectModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-money-check-alt"></i> ফি কালেক্ট - <span id="collectStudentName"></span></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered align-middle" id="feesItemsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>টাইপ</th>
                                        <th>শিক্ষাবর্ষ</th>
                                        <th>মাস</th>
                                        <th class="text-end">ডিউ</th>
                                        <th style="width:140px">এখন পরিশোধ</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" class="text-end">মোট</th>
                                        <th class="text-end" id="totalDueCell">0</th>
                                        <th>
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text">৳</span>
                                                <input type="number" step="0.01" min="0" id="quickPay" class="form-control" placeholder="মোট" />
                                                <button class="btn btn-outline-secondary" onclick="applyQuickPay()">Apply</button>
                                            </div>
                                        </th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        <div class="row g-2">
                            <div class="col-md-4">
                                <label class="form-label">পেমেন্ট মেথড</label>
                                <select class="form-select form-select-sm" id="paymentMethod">
                                    <option>Cash</option>
                                    <option>Bank</option>
                                    <option>Mobile</option>
                                </select>
                            </div>
                            <div class="col-md-8">
                                <label class="form-label">নোট</label>
                                <input type="text" class="form-control form-control-sm" id="paymentNote" />
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="me-auto fw-bold">এই ট্রানজেকশনে মোট: ৳ <span id="totalPayNow">0.00</span></div>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="button" class="btn btn-primary" onclick="saveCollection()"><i class="fas fa-save"></i> সেভ</button>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentStudentId = null;
        let currentStudentName = '';
        let currentFees = [];

        const receiptsGrid = document.getElementById('receiptsGrid');
        const receiptCols = document.getElementById('receiptCols');
        const receiptCompact = document.getElementById('receiptCompact');

        function showAlert(type, msg) {
            const container = document.getElementById('alertContainer');
            const cls = type === 'success' ? 'alert-success' : type === 'warning' ? 'alert-warning' : 'alert-danger';
            container.innerHTML = `<div class="alert ${cls} alert-dismissible fade show" role="alert">
                <i class="fas ${type==='success'?'fa-check-circle':'fa-exclamation-triangle'}"></i> ${msg}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>`;
            setTimeout(()=>{ const a=container.querySelector('.alert'); if (a) bootstrap.Alert.getOrCreateInstance(a).close(); }, 5000);
        }

        function setReceiptCols(v) { document.documentElement.style.setProperty('--receipt-cols', v); }
        receiptCols?.addEventListener('change', e=> setReceiptCols(e.target.value));
        setReceiptCols(receiptCols?.value || 2);

        receiptCompact?.addEventListener('change', ()=>{
            if (!receiptsGrid) return;
            if (receiptCompact.checked) receiptsGrid.classList.add('compact'); else receiptsGrid.classList.remove('compact');
        });

        function loadStudents() {
            const session = document.getElementById('filter_session').value;
            const class_id = document.getElementById('filter_class').value;
            const group_name = document.getElementById('filter_group').value;
            const academic_year = document.getElementById('filter_year').value.trim();
            const month = document.getElementById('filter_month').value;
            const fee_type = document.getElementById('filter_type').value;
            const fee_status = document.getElementById('showAll').checked ? 'all' : 'due_only';

            const tbody = document.querySelector('#studentsTable tbody');
            tbody.innerHTML = `<tr><td colspan="8" class="text-center text-muted">লোড হচ্ছে...</td></tr>`;

            const body = new URLSearchParams({
                ajax: '1', action:'get_students_with_fees', session, class_id, group_name, academic_year, month, fee_type, fee_status
            }).toString();

            fetch('collect.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body })
            .then(r=>r.json())
            .then(d=>{
                if (!d.success) { showAlert('danger', d.message||'লোড করতে সমস্যা'); tbody.innerHTML=''; return; }
                const rows = d.students || [];
                if (rows.length === 0) { tbody.innerHTML = `<tr><td colspan="8" class="text-center text-muted">কোন ডাটা পাওয়া যায়নি</td></tr>`; return; }
                tbody.innerHTML = rows.map(s=>`
                    <tr class="student-row ${parseFloat(s.total_due)>0?'':'due-zero'}">
                        <td>${s.roll_number||''}</td>
                        <td>${s.student_id||''}</td>
                        <td>${s.first_name} ${s.last_name}</td>
                        <td>${s.session||''}</td>
                        <td>${s.class_name||''} - ${s.class_section||''}</td>
                        <td>${s.group_name||''}</td>
                        <td class="text-end">${Number(s.total_due).toFixed(2)}</td>
                        <td class="text-end">
                            <button class="btn btn-sm btn-primary" onclick="openCollect(${s.id}, '${(s.first_name||'').replace(/'/g, "\'")} ${(s.last_name||'').replace(/'/g, "\'")}')">
                                <i class="fas fa-cash-register"></i> Collect
                            </button>
                        </td>
                    </tr>
                `).join('');
            })
            .catch(err=>{ showAlert('danger', 'নেটওয়ার্ক সমস্যা'); tbody.innerHTML=''; });
        }

        function openCollect(studentId, studentName) {
            currentStudentId = studentId;
            currentStudentName = studentName;
            document.getElementById('collectStudentName').textContent = studentName;

            const year  = document.getElementById('filter_year').value.trim();
            const month = document.getElementById('filter_month').value;
            const fee_type = document.getElementById('filter_type').value;

            const body = new URLSearchParams({ ajax:'1', action:'get_student_fees', student_id: studentId, academic_year: year, month, fee_type }).toString();
            const tbody = document.querySelector('#feesItemsTable tbody');
            tbody.innerHTML = `<tr><td colspan="5" class="text-center text-muted">লোড হচ্ছে...</td></tr>`;

            fetch('collect.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body })
            .then(r=>r.json())
            .then(d=>{
                if (!d.success) { showAlert('danger', d.message||'লোড করতে সমস্যা'); return; }
                currentFees = d.fees || [];
                if (currentFees.length === 0) {
                    tbody.innerHTML = `<tr><td colspan="5" class="text-center text-success">কোন বকেয়া নেই</td></tr>`;
                } else {
                    tbody.innerHTML = currentFees.map(f=>`
                        <tr>
                            <td>${f.fee_type}</td>
                            <td>${f.academic_year||''}</td>
                            <td>${f.month||''}</td>
                            <td class="text-end">${Number(f.due).toFixed(2)}</td>
                            <td>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text">৳</span>
                                    <input type="number" step="0.01" min="0" max="${Number(f.due).toFixed(2)}" class="form-control pay-input" data-fee-id="${f.id}" value="${Number(f.due).toFixed(2)}">
                                </div>
                            </td>
                        </tr>
                    `).join('');
                }
                updateTotals();
                new bootstrap.Modal(document.getElementById('collectModal')).show();
            })
            .catch(()=> showAlert('danger','নেটওয়ার্ক সমস্যা'));
        }

        function applyQuickPay() {
            const quick = parseFloat(document.getElementById('quickPay').value||'0');
            const inputs = Array.from(document.querySelectorAll('#feesItemsTable .pay-input'));
            if (!inputs.length) return;
            if (!(quick>0)) { inputs.forEach(i=> i.value = '0'); updateTotals(); return; }
            // Distribute to rows top-down
            let remaining = quick;
            inputs.forEach(i=>{
                const max = parseFloat(i.getAttribute('max'))||0;
                const take = Math.min(max, remaining);
                i.value = take.toFixed(2);
                remaining -= take;
            });
            updateTotals();
        }

        function updateTotals() {
            const inputs = Array.from(document.querySelectorAll('#feesItemsTable .pay-input'));
            let sum = 0, dueSum = 0;
            inputs.forEach(i=>{ sum += parseFloat(i.value||'0'); dueSum += parseFloat(i.getAttribute('max')||'0'); });
            document.getElementById('totalPayNow').textContent = sum.toFixed(2);
            document.getElementById('totalDueCell').textContent = dueSum.toFixed(2);
        }
        document.addEventListener('input', (e)=>{ if (e.target.classList?.contains('pay-input')) updateTotals(); });

        function saveCollection() {
            const inputs = Array.from(document.querySelectorAll('#feesItemsTable .pay-input'));
            const payments = inputs
                .map(i=>({ fee_id: parseInt(i.getAttribute('data-fee-id')), pay_amount: parseFloat(i.value||'0') }))
                .filter(p=> p.fee_id>0 && p.pay_amount>0);
            if (!payments.length) { showAlert('warning','কোন পরিমাণ সেট করা নেই'); return; }

            const payment_method = document.getElementById('paymentMethod').value;
            const note = document.getElementById('paymentNote').value.trim();

            const body = new URLSearchParams({
                ajax:'1', action:'collect_payment', student_id: currentStudentId,
                payments: JSON.stringify(payments), payment_method, note
            }).toString();

            fetch('collect.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body })
            .then(r=>r.json())
            .then(d=>{
                if (!d.success) { showAlert('danger', d.message||'সেভ ব্যর্থ'); return; }
                
                // Build success message with notification status
                let successMsg = 'পেমেন্ট সেভ হয়েছে: ৳ '+Number(d.total_paid).toFixed(2);
                
                // Check notification status
                if (d.notification_status) {
                    if (d.notification_status.sent) {
                        successMsg += ' | নোটিফিকেশন: পাঠানো হয়েছে';
                    } else {
                        if (d.notification_status.reasons && d.notification_status.reasons.length > 0) {
                            successMsg += ' | নোটিফিকেশন: ' + d.notification_status.reasons.join(', ');
                        } else {
                            successMsg += ' | নোটিফিকেশন: পাঠানো হয়নি';
                        }
                    }
                }
                
                showAlert('success', successMsg);
                bootstrap.Modal.getInstance(document.getElementById('collectModal'))?.hide();
                
                // Redirect to success message page
                if (d.redirect_url) {
                    setTimeout(() => {
                        window.location.href = d.redirect_url;
                    }, 1500);
                } else {
                    loadStudents(); // refresh list
                    buildReceipts([d.receipt]);
                    window.print();
                }
            })
            .catch(()=> showAlert('danger','নেটওয়ার্ক সমস্যা'));
        }

        function buildReceipts(receipts) {
            if (!receiptsGrid) return;
            receiptsGrid.innerHTML = receipts.map(rc=>{
                const s = rc.student||{};
                const items = (rc.items||[]).map(it=>`
                    <tr>
                        <td>${it.fee_type}${it.month? ' - '+it.month: ''}${it.academic_year? ' ('+it.academic_year+')':''}</td>
                        <td class="text-end">${Number(it.paid_now).toFixed(2)}</td>
                    </tr>
                `).join('');
                const total = (rc.items||[]).reduce((a,b)=> a+Number(b.paid_now||0), 0);
                return `
                    <div class="receipt-card ${receiptCompact.checked ? 'compact':''}">
                        <div class="receipt-title">পেমেন্ট রসিদ</div>
                        <div class="receipt-meta">তারিখ: ${rc.datetime} | পদ্ধতি: ${rc.payment_method||''}</div>
                        <div class="receipt-meta">নাম: ${s.first_name||''} ${s.last_name||''} | রোল: ${s.roll_number||''}</div>
                        <div class="receipt-meta">ক্লাস: ${s.class_name||''} - ${s.class_section||''} ${s.group_name? '| গ্রুপ: '+s.group_name:''}</div>
                        <hr>
                        <table class="table table-borderless receipt-table">
                            <thead>
                                <tr>
                                    <th>বিবরণ</th>
                                    <th class="text-end">টাকা</th>
                                </tr>
                            </thead>
                            <tbody>${items}</tbody>
                            <tfoot>
                                <tr>
                                    <th>মোট</th>
                                    <th class="text-end">${total.toFixed(2)}</th>
                                </tr>
                            </tfoot>
                        </table>
                        ${rc.note? `<div class="receipt-meta text-start"><strong>নোট:</strong> ${rc.note}</div>`:''}
                    </div>
                `;
            }).join('');
        }
        
        // Landscape print function
        function printLandscape() {
            // Temporarily set the receipt columns to 4 for landscape
            const originalCols = receiptCols.value;
            receiptCols.value = '4';
            setReceiptCols('4');
            
            // Trigger print with landscape orientation
            const style = document.createElement('style');
            style.innerHTML = '@page { size: A4 landscape; margin: 5mm; } @media print { .receipt-grid { grid-template-columns: repeat(4, 1fr) !important; } }';
            document.head.appendChild(style);
            
            window.print();
            
            // Clean up
            setTimeout(() => {
                document.head.removeChild(style);
                receiptCols.value = originalCols;
                setReceiptCols(originalCols);
            }, 1000);
        }
    </script>
</body>
</html>