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

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

$stats_query = "
    SELECT 
        COUNT(DISTINCT s.id) AS total_students,
        COUNT(f.id) AS total_fees,
        SUM(f.amount) AS total_amount,
        SUM(COALESCE(f.paid_amount, 0)) AS total_paid,
        SUM(f.amount - COALESCE(f.paid_amount, 0)) AS total_due,
        SUM(CASE WHEN f.status = 'paid' THEN 1 ELSE 0 END) AS paid_count,
        SUM(CASE WHEN f.status = 'pending' THEN 1 ELSE 0 END) AS pending_count,
        SUM(CASE WHEN f.status = 'partial' THEN 1 ELSE 0 END) AS partial_count,
        SUM(CASE WHEN f.status = 'overdue' THEN 1 ELSE 0 END) AS overdue_count
    FROM students s
    LEFT JOIN fees f ON s.id = f.student_id
    WHERE s.status = 'active'
";
$stats = $pdo->query($stats_query)->fetch();

$monthly_query = "
    SELECT 
        DATE_FORMAT(f.paid_date, '%Y-%m') AS month,
        SUM(COALESCE(f.paid_amount, 0)) AS collected
    FROM fees f
    WHERE f.paid_date IS NOT NULL 
    AND f.paid_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(f.paid_date, '%Y-%m')
    ORDER BY month
";
$monthly_data = $pdo->query($monthly_query)->fetchAll();

$defaulters_query = "
    SELECT 
        s.id AS student_id,
        s.first_name,
        s.last_name,
        s.roll_number,
        c.name AS class_name,
        c.section AS class_section,
        SUM(f.amount - COALESCE(f.paid_amount, 0)) AS total_due,
        COUNT(f.id) AS due_items
    FROM students s
    JOIN classes c ON s.class_id = c.id
    JOIN fees f ON s.id = f.student_id
    WHERE s.status = 'active' AND (f.amount - COALESCE(f.paid_amount, 0)) > 0
    GROUP BY s.id, s.first_name, s.last_name, s.roll_number, c.name, c.section
    ORDER BY total_due DESC
    LIMIT 8
";
$defaulters = $pdo->query($defaulters_query)->fetchAll();

$recent_payments_query = "
    SELECT 
        s.first_name,
        s.last_name,
        s.roll_number,
        c.name AS class_name,
        c.section AS class_section,
        f.fee_type,
        f.paid_amount,
        f.paid_date
    FROM fees f
    JOIN students s ON f.student_id = s.id
    JOIN classes c ON s.class_id = c.id
    WHERE f.paid_date IS NOT NULL AND COALESCE(f.paid_amount, 0) > 0
    ORDER BY f.paid_date DESC, f.updated_at DESC
    LIMIT 10
";
$recent_payments = $pdo->query($recent_payments_query)->fetchAll();

$class_stats_query = "
    SELECT 
        c.name AS class_name,
        c.section AS class_section,
        COUNT(DISTINCT s.id) AS student_count,
        SUM(f.amount) AS total_amount,
        SUM(COALESCE(f.paid_amount, 0)) AS total_paid,
        SUM(f.amount - COALESCE(f.paid_amount, 0)) AS total_due
    FROM classes c
    JOIN students s ON c.id = s.class_id
    LEFT JOIN fees f ON s.id = f.student_id
    WHERE c.status = 'active' AND s.status = 'active'
    GROUP BY c.id, c.name, c.section
    ORDER BY c.name, c.section
";
$class_stats = $pdo->query($class_stats_query)->fetchAll();

$fee_type_stats_query = "
    SELECT 
        f.fee_type,
        COUNT(f.id) AS total_entries,
        SUM(f.amount) AS total_amount,
        SUM(COALESCE(f.paid_amount, 0)) AS total_paid,
        SUM(f.amount - COALESCE(f.paid_amount, 0)) AS total_due,
        ROUND((SUM(COALESCE(f.paid_amount, 0)) / NULLIF(SUM(f.amount), 0)) * 100, 1) AS collection_rate
    FROM fees f
    GROUP BY f.fee_type
    ORDER BY total_amount DESC
    LIMIT 10
";
$fee_type_stats = $pdo->query($fee_type_stats_query)->fetchAll();

$collection_rate = ($stats['total_amount'] > 0)
    ? round(($stats['total_paid'] / $stats['total_amount']) * 100, 1)
    : 0;
?>
<!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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root{--indigo:#4fc3f7;--teal:#4dd0e1;--green:#66bb6a;--red:#ef5350;--orange:#ffb74d}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0;font-size:.82rem}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 20px rgba(0,0,0,.4);flex-wrap:wrap;gap:8px}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none;display:flex;align-items:center;gap:8px}
        .top-bar .nav-links{display:flex;gap:10px;flex-wrap:wrap}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.74rem;font-weight:500;padding:4px 10px;border-radius:6px;transition:.2s}
        .top-bar .nav-links a:hover{color:#fff;background:rgba(255,255,255,.08)}
        .page-head{padding:12px 0 8px}
        .page-head h4{margin:0;font-size:1rem;font-weight:800;color:#4fc3f7}
        .page-head p{margin:2px 0 0;font-size:.72rem;color:rgba(255,255,255,.45)}
        .stat-row{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:10px}
        .stat-card{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;display:flex;align-items:center;gap:8px}
        .stat-card .ic{width:34px;height:34px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:.95rem;flex-shrink:0}
        .stat-card .num{font-size:.95rem;font-weight:800;line-height:1.1;color:#fff}
        .stat-card .lbl{font-size:.68rem;color:rgba(255,255,255,.45)}
        .action-row{display:grid;grid-template-columns:repeat(6,1fr);gap:6px;margin-bottom:10px}
        .action-btn{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 6px;text-align:center;text-decoration:none!important;transition:.15s}
        .action-btn:hover{transform:translateY(-1px);border-color:rgba(79,195,247,.3);background:rgba(79,195,247,.08)}
        .action-btn .ab-ic{width:30px;height:30px;border-radius:6px;display:flex;align-items:center;justify-content:center;margin:0 auto 4px;font-size:.82rem}
        .action-btn .ab-tx{font-size:.7rem;font-weight:700;color:#e0e0e0;line-height:1.2}
        .panel{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);border-radius:10px;margin-bottom:10px;height:100%}
        .panel-hd{padding:8px 12px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;align-items:center;justify-content:space-between}
        .panel-hd h5{margin:0;font-size:.8rem;font-weight:700;color:#90caf9}
        .panel-bd{padding:10px 12px}
        .rate-ring{text-align:center;padding:4px 0}
        .rate-ring .pct{font-size:1.8rem;font-weight:800;color:#4fc3f7;line-height:1}
        .rate-ring .sub{font-size:.7rem;color:rgba(255,255,255,.45)}
        .prog-track{height:8px;background:rgba(0,0,0,.35);border-radius:8px;overflow:hidden;margin:8px 0}
        .prog-fill{height:100%;background:linear-gradient(90deg,#2e7d32,#66bb6a);border-radius:8px;transition:width .4s}
        .mini-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:8px}
        .mini-stat{text-align:center;padding:6px;background:rgba(0,0,0,.2);border-radius:6px}
        .mini-stat .n{font-size:.9rem;font-weight:800}
        .mini-stat .l{font-size:.65rem;color:rgba(255,255,255,.4)}
        .chart-box{position:relative;height:160px}
        .data-table{width:100%;border-collapse:collapse;font-size:.74rem}
        .data-table thead th{background:rgba(13,33,55,.9);color:#90caf9;font-weight:600;padding:5px 8px;border-bottom:1px solid rgba(255,255,255,.08);white-space:nowrap}
        .data-table tbody td{padding:4px 8px;border-bottom:1px solid rgba(255,255,255,.04);vertical-align:middle}
        .data-table tbody tr:hover{background:rgba(79,195,247,.06)}
        .data-table .name{font-weight:600;color:#fff}
        .data-table .muted{color:rgba(255,255,255,.45);font-size:.68rem}
        .data-table .due{color:#ff8a80;font-weight:700}
        .data-table .paid{color:#81c784;font-weight:600}
        .tbl-scroll{max-height:220px;overflow:auto}
        .tbl-scroll-lg{max-height:280px;overflow:auto}
        .badge-pill{font-size:.62rem;padding:2px 7px;border-radius:10px;font-weight:700;background:rgba(255,183,77,.15);color:#ffb74d}
        .rate-bar{height:6px;background:rgba(0,0,0,.35);border-radius:6px;overflow:hidden;min-width:60px}
        .rate-bar span{display:block;height:100%;background:linear-gradient(90deg,#1565c0,#4fc3f7);border-radius:6px}
        .rate-txt{font-size:.65rem;color:rgba(255,255,255,.5);margin-top:1px}
        .empty-mini{text-align:center;padding:20px 8px;color:rgba(255,255,255,.35);font-size:.75rem}
        .empty-mini i{display:block;font-size:1.4rem;margin-bottom:6px}
        .link-more{font-size:.68rem;color:#4fc3f7;text-decoration:none}
        .link-more:hover{color:#90caf9}
        .fee-menu{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px;padding:8px 10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);border-radius:10px}
        .fee-menu a{display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:8px;font-size:.74rem;font-weight:600;color:rgba(255,255,255,.65);text-decoration:none;border:1px solid rgba(255,255,255,.08);background:rgba(0,0,0,.2);transition:.15s;white-space:nowrap}
        .fee-menu a:hover{color:#fff;border-color:rgba(79,195,247,.35);background:rgba(79,195,247,.1)}
        .fee-menu a.active{color:#fff;border-color:rgba(79,195,247,.5);background:linear-gradient(135deg,#1565c0,#1e88e5)}
        .fee-menu a i{font-size:.72rem;opacity:.9}
        @media(max-width:992px){
            .stat-row{grid-template-columns:repeat(2,1fr)}
            .action-row{grid-template-columns:repeat(3,1fr)}
        }
        @media(max-width:576px){
            .action-row{grid-template-columns:repeat(2,1fr)}
        }
    </style>
</head>
<body>
    <div class="top-bar">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a href="manage.php"><i class="fas fa-plus-circle"></i> ফি নির্ধারণ</a>
            <a href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ</a>
            <a href="reports.php"><i class="fas fa-chart-bar"></i> রিপোর্ট</a>
            <a href="overdue.php"><i class="fas fa-exclamation-triangle"></i> বকেয়া</a>
            <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>

    <div class="container-fluid px-3 px-md-4 pb-3">
        <div class="page-head">
            <h4><i class="fas fa-chart-pie me-1"></i> ফি ড্যাশবোর্ড</h4>
            <p>সংগ্রহ, বকেয়া ও পরিসংখ্যানের এক নজরে সারসংক্ষেপ</p>
        </div>

        <nav class="fee-menu" aria-label="ফি মেনু">
            <a href="new_dashboard.php" class="active"><i class="fas fa-chart-pie"></i> ড্যাশবোর্ড</a>
            <a href="manage.php"><i class="fas fa-plus-circle"></i> ফি নির্ধারণ</a>
            <a href="custom_assign.php"><i class="fas fa-user-plus"></i> কাস্টম ফি</a>
            <a href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ</a>
            <a href="collect.php"><i class="fas fa-cash-register"></i> দ্রুত কালেক্ট</a>
            <a href="bill_submission.php"><i class="fas fa-file-invoice"></i> বিল সাবমিট</a>
            <a href="overdue.php"><i class="fas fa-exclamation-triangle"></i> বকেয়া</a>
            <a href="reports.php"><i class="fas fa-chart-bar"></i> রিপোর্ট</a>
            <a href="types.php"><i class="fas fa-tags"></i> ফি টাইপ</a>
            <a href="management_dashboard.php"><i class="fas fa-cog"></i> সেটিংস</a>
        </nav>

        <div class="stat-row">
            <div class="stat-card">
                <div class="ic" style="background:rgba(79,195,247,.12);color:#4fc3f7"><i class="fas fa-users"></i></div>
                <div><div class="num"><?php echo number_format($stats['total_students'] ?: 0); ?></div><div class="lbl">শিক্ষার্থী</div></div>
            </div>
            <div class="stat-card">
                <div class="ic" style="background:rgba(144,202,249,.1);color:#90caf9"><i class="fas fa-file-invoice"></i></div>
                <div><div class="num">৳<?php echo number_format($stats['total_amount'] ?: 0, 0); ?></div><div class="lbl">মোট ফি</div></div>
            </div>
            <div class="stat-card">
                <div class="ic" style="background:rgba(102,187,106,.12);color:#66bb6a"><i class="fas fa-check-circle"></i></div>
                <div><div class="num">৳<?php echo number_format($stats['total_paid'] ?: 0, 0); ?></div><div class="lbl">সংগৃহীত</div></div>
            </div>
            <div class="stat-card">
                <div class="ic" style="background:rgba(239,83,80,.12);color:#ef5350"><i class="fas fa-exclamation-triangle"></i></div>
                <div><div class="num">৳<?php echo number_format($stats['total_due'] ?: 0, 0); ?></div><div class="lbl">বকেয়া</div></div>
            </div>
        </div>

        <div class="action-row">
            <a href="student_fees.php" class="action-btn">
                <div class="ab-ic" style="background:linear-gradient(135deg,#667eea,#764ba2);color:#fff"><i class="fas fa-money-bill-wave"></i></div>
                <div class="ab-tx">ফি সংগ্রহ</div>
            </a>
            <a href="collect.php" class="action-btn">
                <div class="ab-ic" style="background:linear-gradient(135deg,#f093fb,#f5576c);color:#fff"><i class="fas fa-cash-register"></i></div>
                <div class="ab-tx">দ্রুত কালেক্ট</div>
            </a>
            <a href="bill_submission.php" class="action-btn">
                <div class="ab-ic" style="background:linear-gradient(135deg,#fa709a,#fee140);color:#fff"><i class="fas fa-file-invoice"></i></div>
                <div class="ab-tx">বিল সাবমিট</div>
            </a>
            <a href="overdue.php" class="action-btn">
                <div class="ab-ic" style="background:linear-gradient(135deg,#ef5350,#ff8a65);color:#fff"><i class="fas fa-user-clock"></i></div>
                <div class="ab-tx">বকেয়া তালিকা</div>
            </a>
            <a href="reports.php" class="action-btn">
                <div class="ab-ic" style="background:linear-gradient(135deg,#43e97b,#38f9d7);color:#fff"><i class="fas fa-chart-bar"></i></div>
                <div class="ab-tx">রিপোর্ট</div>
            </a>
            <a href="manage.php" class="action-btn">
                <div class="ab-ic" style="background:linear-gradient(135deg,#4facfe,#00f2fe);color:#fff"><i class="fas fa-plus-circle"></i></div>
                <div class="ab-tx">ফি নির্ধারণ</div>
            </a>
        </div>

        <div class="row g-2 mb-2">
            <div class="col-lg-4">
                <div class="panel">
                    <div class="panel-hd"><h5><i class="fas fa-percentage me-1" style="color:var(--green)"></i>সংগ্রহের হার</h5></div>
                    <div class="panel-bd">
                        <div class="rate-ring">
                            <div class="pct"><?php echo $collection_rate; ?>%</div>
                            <div class="sub">মোট ফি সংগ্রহের হার</div>
                        </div>
                        <div class="prog-track">
                            <div class="prog-fill" style="width:<?php echo min(100, $collection_rate); ?>%"></div>
                        </div>
                        <div class="mini-stats">
                            <div class="mini-stat">
                                <div class="n" style="color:#66bb6a"><?php echo number_format($stats['paid_count'] ?: 0); ?></div>
                                <div class="l">পরিশোধিত</div>
                            </div>
                            <div class="mini-stat">
                                <div class="n" style="color:#ffb74d"><?php echo number_format(($stats['pending_count'] + $stats['partial_count']) ?: 0); ?></div>
                                <div class="l">অপেক্ষমান</div>
                            </div>
                            <div class="mini-stat">
                                <div class="n" style="color:#ef5350"><?php echo number_format($stats['overdue_count'] ?: 0); ?></div>
                                <div class="l">বকেয়া</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-8">
                <div class="panel">
                    <div class="panel-hd"><h5><i class="fas fa-chart-line me-1" style="color:var(--teal)"></i>মাসিক সংগ্রহ (১২ মাস)</h5></div>
                    <div class="panel-bd">
                        <div class="chart-box">
                            <canvas id="monthlyChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-2 mb-2">
            <div class="col-lg-6">
                <div class="panel">
                    <div class="panel-hd">
                        <h5><i class="fas fa-exclamation-circle me-1" style="color:var(--red)"></i>সর্বোচ্চ বকেয়াদার</h5>
                        <a href="overdue.php" class="link-more">সব দেখুন <i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="panel-bd p-0">
                        <?php if (empty($defaulters)): ?>
                            <div class="empty-mini"><i class="fas fa-check-circle" style="color:#66bb6a"></i>কোনো বকেয়া নেই</div>
                        <?php else: ?>
                            <div class="tbl-scroll">
                                <table class="data-table">
                                    <thead>
                                        <tr><th>নাম</th><th>ক্লাস</th><th class="text-end">বকেয়া</th><th></th></tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($defaulters as $d): ?>
                                        <tr>
                                            <td>
                                                <div class="name"><?php echo htmlspecialchars($d['first_name'] . ' ' . $d['last_name']); ?></div>
                                                <div class="muted">রোল: <?php echo htmlspecialchars($d['roll_number']); ?></div>
                                            </td>
                                            <td class="muted"><?php echo htmlspecialchars($d['class_name'] . ' - ' . $d['class_section']); ?></td>
                                            <td class="text-end due">৳<?php echo number_format($d['total_due'], 0); ?></td>
                                            <td><span class="badge-pill"><?php echo (int)$d['due_items']; ?></span></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="panel">
                    <div class="panel-hd"><h5><i class="fas fa-clock me-1" style="color:var(--orange)"></i>সাম্প্রতিক পেমেন্ট</h5></div>
                    <div class="panel-bd p-0">
                        <?php if (empty($recent_payments)): ?>
                            <div class="empty-mini"><i class="fas fa-money-bill-wave"></i>কোনো সাম্প্রতিক পেমেন্ট নেই</div>
                        <?php else: ?>
                            <div class="tbl-scroll">
                                <table class="data-table">
                                    <thead>
                                        <tr><th>নাম</th><th>ফি</th><th class="text-end">টাকা</th><th>তারিখ</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_payments as $p): ?>
                                        <tr>
                                            <td>
                                                <div class="name"><?php echo htmlspecialchars($p['first_name'] . ' ' . $p['last_name']); ?></div>
                                                <div class="muted"><?php echo htmlspecialchars($p['class_name'] . ' - ' . $p['class_section']); ?></div>
                                            </td>
                                            <td class="muted"><?php echo htmlspecialchars($p['fee_type']); ?></td>
                                            <td class="text-end paid">৳<?php echo number_format($p['paid_amount'], 0); ?></td>
                                            <td class="muted"><?php echo date('d/m/y', strtotime($p['paid_date'])); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-2">
            <div class="col-lg-6">
                <div class="panel">
                    <div class="panel-hd"><h5><i class="fas fa-school me-1" style="color:var(--indigo)"></i>ক্লাস ভিত্তিক</h5></div>
                    <div class="panel-bd p-0">
                        <div class="tbl-scroll-lg">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>ক্লাস</th>
                                        <th>ছাত্র</th>
                                        <th class="text-end">মোট</th>
                                        <th class="text-end">সংগৃহীত</th>
                                        <th class="text-end">বকেয়া</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($class_stats as $class): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($class['class_name'] . ' - ' . $class['class_section']); ?></td>
                                        <td><?php echo (int)$class['student_count']; ?></td>
                                        <td class="text-end">৳<?php echo number_format($class['total_amount'] ?: 0, 0); ?></td>
                                        <td class="text-end paid">৳<?php echo number_format($class['total_paid'] ?: 0, 0); ?></td>
                                        <td class="text-end due">৳<?php echo number_format($class['total_due'] ?: 0, 0); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="panel">
                    <div class="panel-hd"><h5><i class="fas fa-tags me-1" style="color:var(--teal)"></i>ফি টাইপ ভিত্তিক</h5></div>
                    <div class="panel-bd p-0">
                        <div class="tbl-scroll-lg">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>ফি টাইপ</th>
                                        <th class="text-end">মোট</th>
                                        <th class="text-end">সংগৃহীত</th>
                                        <th>হার</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($fee_type_stats as $fs): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($fs['fee_type']); ?></td>
                                        <td class="text-end">৳<?php echo number_format($fs['total_amount'], 0); ?></td>
                                        <td class="text-end paid">৳<?php echo number_format($fs['total_paid'], 0); ?></td>
                                        <td>
                                            <div class="rate-bar"><span style="width:<?php echo min(100, $fs['collection_rate'] ?: 0); ?>%"></span></div>
                                            <div class="rate-txt"><?php echo $fs['collection_rate'] ?: 0; ?>%</div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    (function() {
        const monthlyData = <?php echo json_encode($monthly_data); ?>;
        const canvas = document.getElementById('monthlyChart');
        if (!canvas) return;

        const labels = monthlyData.map(item => {
            const [y, m] = (item.month || '').split('-');
            const months = ['জান','ফেব','মার','এপ্র','মে','জুন','জুল','আগ','সেপ','অক্ট','নভে','ডিস'];
            return (months[parseInt(m, 10) - 1] || m) + ' ' + (y || '').slice(-2);
        });
        const data = monthlyData.map(item => parseFloat(item.collected) || 0);

        new Chart(canvas.getContext('2d'), {
            type: 'line',
            data: {
                labels,
                datasets: [{
                    label: 'মাসিক সংগ্রহ',
                    data,
                    borderColor: '#4fc3f7',
                    backgroundColor: 'rgba(79,195,247,0.12)',
                    borderWidth: 2,
                    pointRadius: 3,
                    pointBackgroundColor: '#4fc3f7',
                    tension: 0.35,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        ticks: { color: 'rgba(255,255,255,0.45)', font: { size: 10 } },
                        grid: { color: 'rgba(255,255,255,0.05)' }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            color: 'rgba(255,255,255,0.45)',
                            font: { size: 10 },
                            callback: v => '৳' + Number(v).toLocaleString('bn-BD')
                        },
                        grid: { color: 'rgba(255,255,255,0.06)' }
                    }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(13,33,55,0.95)',
                        titleColor: '#90caf9',
                        bodyColor: '#e0e0e0',
                        callbacks: {
                            label: ctx => 'সংগ্রহ: ৳' + ctx.parsed.y.toLocaleString('bn-BD')
                        }
                    }
                }
            }
        });
    })();
    </script>
</body>
</html>
