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

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$system_name = get_system_name($pdo);

// Get overall statistics
$stats_query = "
    SELECT 
        COUNT(DISTINCT s.id) as total_students,
        COUNT(f.id) as total_fees,
        SUM(f.amount) as total_amount,
        SUM(f.paid_amount) as total_paid,
        SUM(f.amount - f.paid_amount) 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();

// Get monthly collection data for chart
$monthly_query = "
    SELECT 
        DATE_FORMAT(f.paid_date, '%Y-%m') as month,
        SUM(f.paid_amount) 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();

// Get top defaulters (students with highest due amounts)
$defaulters_query = "
    SELECT 
        s.first_name,
        s.last_name,
        s.roll_number,
        c.name as class_name,
        c.section as class_section,
        SUM(f.amount - f.paid_amount) 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 - f.paid_amount) > 0
    GROUP BY s.id, s.first_name, s.last_name, s.roll_number, c.name, c.section
    ORDER BY total_due DESC
    LIMIT 10
";
$defaulters = $pdo->query($defaulters_query)->fetchAll();

// Get recent payments
$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
    ORDER BY f.paid_date DESC, f.updated_at DESC
    LIMIT 15
";
$recent_payments = $pdo->query($recent_payments_query)->fetchAll();

// Get class-wise statistics
$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(f.paid_amount) as total_paid,
        SUM(f.amount - f.paid_amount) 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();

// Get fee type wise statistics
$fee_type_stats_query = "
    SELECT 
        f.fee_type,
        COUNT(f.id) as total_entries,
        SUM(f.amount) as total_amount,
        SUM(f.paid_amount) as total_paid,
        SUM(f.amount - f.paid_amount) as total_due,
        ROUND((SUM(f.paid_amount) / SUM(f.amount)) * 100, 2) as collection_rate
    FROM fees f
    GROUP BY f.fee_type
    ORDER BY total_amount DESC
";
$fee_type_stats = $pdo->query($fee_type_stats_query)->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি ড্যাশবোর্ড - <?php echo htmlspecialchars($system_name); ?></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>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .stats-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
            overflow: hidden;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .stats-card .card-body {
            padding: 1.5rem;
        }
        .stats-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        .stats-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        .stats-icon {
            font-size: 3rem;
            opacity: 0.3;
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1rem 1.5rem;
        }
        .table-responsive {
            border-radius: 10px;
        }
        .progress {
            height: 8px;
            border-radius: 10px;
        }
        .quick-actions {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        .quick-actions .btn {
            border-radius: 25px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            margin: 0.25rem;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <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> <?php echo htmlspecialchars($system_name); ?>
            </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-cog"></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">
        <!-- Quick Actions -->
        <div class="quick-actions">
            <h4 class="text-white mb-3"><i class="fas fa-bolt"></i> দ্রুত অ্যাকশন</h4>
            <div class="text-center">
                <a href="manage.php" class="btn btn-light">
                    <i class="fas fa-plus-circle"></i> নতুন ফি নির্ধারণ
                </a>
                <a href="student_fees.php" class="btn btn-light">
                    <i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ
                </a>
                <a href="reports.php" class="btn btn-light">
                    <i class="fas fa-chart-bar"></i> বিস্তারিত রিপোর্ট
                </a>
                <a href="collect.php" class="btn btn-light">
                    <i class="fas fa-cash-register"></i> দ্রুত কালেক্ট
                </a>
                <a href="fee_payment_dashboard.php" class="btn btn-light">
                    <i class="fas fa-credit-card"></i> ফি পেমেন্ট ড্যাশবোর্ড
                </a>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stats-card bg-primary text-white">
                    <div class="card-body position-relative">
                        <div class="stats-number"><?php echo $stats['total_students'] ?: 0; ?></div>
                        <div class="stats-label">মোট শিক্ষার্থী</div>
                        <i class="fas fa-users stats-icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card bg-info text-white">
                    <div class="card-body position-relative">
                        <div class="stats-number">৳<?php echo number_format($stats['total_amount'] ?: 0, 0); ?></div>
                        <div class="stats-label">মোট পরিমাণ</div>
                        <i class="fas fa-money-bill stats-icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card bg-success text-white">
                    <div class="card-body position-relative">
                        <div class="stats-number">৳<?php echo number_format($stats['total_paid'] ?: 0, 0); ?></div>
                        <div class="stats-label">মোট সংগৃহীত</div>
                        <i class="fas fa-check-circle stats-icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card bg-danger text-white">
                    <div class="card-body position-relative">
                        <div class="stats-number">৳<?php echo number_format($stats['total_due'] ?: 0, 0); ?></div>
                        <div class="stats-label">মোট বকেয়া</div>
                        <i class="fas fa-exclamation-triangle stats-icon"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Collection Rate and Status -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-percentage"></i> সংগ্রহের হার</h5>
                    </div>
                    <div class="card-body">
                        <?php 
                        $collection_rate = ($stats['total_amount'] > 0) ? 
                            round(($stats['total_paid'] / $stats['total_amount']) * 100, 2) : 0;
                        ?>
                        <div class="text-center mb-3">
                            <h2 class="text-primary"><?php echo $collection_rate; ?>%</h2>
                            <p class="text-muted">মোট ফি সংগ্রহের হার</p>
                        </div>
                        <div class="progress mb-3" style="height: 20px;">
                            <div class="progress-bar bg-success" role="progressbar" 
                                 style="width: <?php echo $collection_rate; ?>%">
                                <?php echo $collection_rate; ?>%
                            </div>
                        </div>
                        <div class="row text-center">
                            <div class="col-4">
                                <div class="text-success">
                                    <strong><?php echo $stats['paid_count'] ?: 0; ?></strong><br>
                                    <small>পরিশোধিত</small>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="text-warning">
                                    <strong><?php echo ($stats['pending_count'] + $stats['partial_count']) ?: 0; ?></strong><br>
                                    <small>অপেক্ষমান</small>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="text-danger">
                                    <strong><?php echo $stats['overdue_count'] ?: 0; ?></strong><br>
                                    <small>বকেয়া</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-chart-line"></i> মাসিক সংগ্রহ</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="monthlyChart" height="200"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <!-- Top Defaulters -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-exclamation-circle"></i> সর্বোচ্চ বকেয়াদার</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($defaulters)): ?>
                            <div class="text-center text-success py-4">
                                <i class="fas fa-check-circle fa-3x mb-3"></i>
                                <p>কোন বকেয়া নেই!</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>নাম</th>
                                            <th>ক্লাস</th>
                                            <th>বকেয়া</th>
                                            <th>আইটেম</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($defaulters as $defaulter): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($defaulter['first_name'] . ' ' . $defaulter['last_name']); ?></strong><br>
                                                    <small class="text-muted">রোল: <?php echo $defaulter['roll_number']; ?></small>
                                                </td>
                                                <td><?php echo $defaulter['class_name'] . ' - ' . $defaulter['class_section']; ?></td>
                                                <td class="text-danger">
                                                    <strong>৳<?php echo number_format($defaulter['total_due'], 2); ?></strong>
                                                </td>
                                                <td>
                                                    <span class="badge bg-warning"><?php echo $defaulter['due_items']; ?></span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Recent Payments -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-clock"></i> সাম্প্রতিক পেমেন্ট</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recent_payments)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-money-bill-wave fa-3x mb-3"></i>
                                <p>কোন সাম্প্রতিক পেমেন্ট নেই</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>নাম</th>
                                            <th>ফি টাইপ</th>
                                            <th>পরিমাণ</th>
                                            <th>তারিখ</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_payments as $payment): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($payment['first_name'] . ' ' . $payment['last_name']); ?></strong><br>
                                                    <small class="text-muted"><?php echo $payment['class_name'] . ' - ' . $payment['class_section']; ?></small>
                                                </td>
                                                <td><?php echo htmlspecialchars($payment['fee_type']); ?></td>
                                                <td class="text-success">
                                                    <strong>৳<?php echo number_format($payment['paid_amount'], 2); ?></strong>
                                                </td>
                                                <td>
                                                    <small><?php echo date('d/m/Y', strtotime($payment['paid_date'])); ?></small>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Class-wise and Fee Type Statistics -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-school"></i> ক্লাস ভিত্তিক পরিসংখ্যান</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>ক্লাস</th>
                                        <th>শিক্ষার্থী</th>
                                        <th>মোট</th>
                                        <th>সংগৃহীত</th>
                                        <th>বকেয়া</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($class_stats as $class): ?>
                                        <tr>
                                            <td><?php echo $class['class_name'] . ' - ' . $class['class_section']; ?></td>
                                            <td><?php echo $class['student_count']; ?></td>
                                            <td>৳<?php echo number_format($class['total_amount'] ?: 0, 0); ?></td>
                                            <td class="text-success">৳<?php echo number_format($class['total_paid'] ?: 0, 0); ?></td>
                                            <td class="text-danger">৳<?php echo number_format($class['total_due'] ?: 0, 0); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-tags"></i> ফি টাইপ ভিত্তিক পরিসংখ্যান</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>ফি টাইপ</th>
                                        <th>মোট</th>
                                        <th>সংগৃহীত</th>
                                        <th>হার</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($fee_type_stats as $fee_stat): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($fee_stat['fee_type']); ?></td>
                                            <td>৳<?php echo number_format($fee_stat['total_amount'], 0); ?></td>
                                            <td class="text-success">৳<?php echo number_format($fee_stat['total_paid'], 0); ?></td>
                                            <td>
                                                <div class="progress" style="height: 15px;">
                                                    <div class="progress-bar bg-success" 
                                                         style="width: <?php echo $fee_stat['collection_rate']; ?>%">
                                                        <?php echo $fee_stat['collection_rate']; ?>%
                                                    </div>
                                                </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>
        // Monthly Collection Chart
        const monthlyData = <?php echo json_encode($monthly_data); ?>;
        const ctx = document.getElementById('monthlyChart').getContext('2d');
        
        const labels = monthlyData.map(item => {
            const date = new Date(item.month + '-01');
            return date.toLocaleDateString('bn-BD', { year: 'numeric', month: 'short' });
        });
        
        const data = monthlyData.map(item => parseFloat(item.collected) || 0);
        
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'মাসিক সংগ্রহ (৳)',
                    data: data,
                    borderColor: 'rgb(75, 192, 192)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    tension: 0.1,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '৳' + value.toLocaleString();
                            }
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'সংগ্রহ: ৳' + context.parsed.y.toLocaleString();
                            }
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>