<?php
session_start();
if ($_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}
include '../config/db.php';

// Get all statistics
$total_fund_query = $conn->query("SELECT SUM(amount) as total FROM donations WHERE status='verified'");
$total_fund = $total_fund_query->fetch_assoc()['total'] ?? 0;

$total_members = $conn->query("SELECT COUNT(*) as count FROM users WHERE role='user'")->fetch_assoc()['count'];

$pending_kyc_count = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_status='pending'")->fetch_assoc()['count'];

$pending_payments_count = $conn->query("SELECT COUNT(*) as count FROM donations WHERE status='pending'")->fetch_assoc()['count'];

$pending_cancellations_count = $conn->query("SELECT COUNT(*) as count FROM cancellation_requests WHERE status='pending'")->fetch_assoc()['count'];

// Get total distributed funds (for fund management)
$total_distributed = $conn->query("SELECT COALESCE(SUM(amount), 0) as total FROM fund_distributions")->fetch_assoc()['total'];

// Get detailed data with KYC document info
$pending_kyc = $conn->query("SELECT * FROM users WHERE kyc_status='pending' ORDER BY created_at DESC");
$pending_payments = $conn->query("SELECT d.*, u.name as user_name FROM donations d JOIN users u ON d.user_id = u.id WHERE d.status='pending' ORDER BY d.uploaded_at DESC");
$cancel_reqs = $conn->query("SELECT c.*, u.name as user_name FROM cancellation_requests c JOIN users u ON c.user_id = u.id WHERE c.status='pending' ORDER BY c.requested_at DESC");

// Get recent donations
$recent_donations = $conn->query("SELECT d.*, u.name as user_name FROM donations d JOIN users u ON d.user_id = u.id WHERE d.status='verified' ORDER BY d.uploaded_at DESC LIMIT 5");

// Get recent distributions
$recent_distributions = $conn->query("SELECT * FROM fund_distributions ORDER BY date DESC LIMIT 5");

// Get recent members
$recent_members = $conn->query("SELECT * FROM users WHERE role='user' ORDER BY created_at DESC LIMIT 5");

// Get rejected KYC for management
$rejected_kyc = $conn->query("SELECT * FROM users WHERE kyc_status='rejected' ORDER BY created_at DESC LIMIT 10");

// Get withdrawal requests
$withdrawal_requests = $conn->query("
    SELECT w.*, u.name as user_name 
    FROM withdrawal_requests w 
    JOIN users u ON w.requested_by = u.id 
    WHERE w.status = 'pending' 
    ORDER BY w.requested_at DESC
");

// Function to check if file exists and return correct path
function getFilePreview($filePath) {
    if (empty($filePath)) {
        return ['exists' => false, 'url' => '', 'type' => 'none'];
    }
    
    // Try multiple possible paths
    $paths = [
        $filePath,
        "../" . $filePath,
        "../assets/uploads/payment_proof/" . basename($filePath),
        "assets/uploads/payment_proof/" . basename($filePath)
    ];
    
    foreach ($paths as $path) {
        if (file_exists($path)) {
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
            return [
                'exists' => true, 
                'url' => $path,
                'web_url' => $path,
                'type' => $isImage ? 'image' : 'file',
                'ext' => $ext
            ];
        }
    }
    
    return ['exists' => false, 'url' => '', 'type' => 'none'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Gau Seva Foundation</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: #f0f2f5;
            overflow-x: hidden;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
            height: 100%;
            background: linear-gradient(135deg, #1a3a1a 0%, #0f2a0f 100%);
            color: white;
            transition: all 0.3s;
            z-index: 100;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            overflow-y: auto;
        }

        .sidebar-header {
            padding: 1.5rem;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .sidebar-header h3 {
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .sidebar-menu {
            padding: 1.5rem 0;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0.8rem 1.5rem;
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            transition: all 0.3s;
            margin: 0.2rem 0;
            cursor: pointer;
        }

        .sidebar-menu a:hover, .sidebar-menu a.active {
            background: rgba(255,215,0,0.2);
            color: #ffd700;
            border-left: 3px solid #ffd700;
        }

        .sidebar-menu a i {
            width: 24px;
        }

        .badge-count {
            background: #dc3545;
            color: white;
            border-radius: 10px;
            padding: 2px 8px;
            font-size: 0.7rem;
            margin-left: auto;
        }

        /* Main Content */
        .main-content {
            margin-left: 260px;
            padding: 1.5rem;
        }

        /* Top Navbar */
        .top-navbar {
            background: white;
            padding: 1rem 2rem;
            border-radius: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .page-title h2 {
            font-size: 1.5rem;
            color: #1a3a1a;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .user-info span {
            color: #666;
        }

        .logout-btn {
            background: #dc3545;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.3s;
        }

        .logout-btn:hover {
            background: #c82333;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: transform 0.3s;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .stat-info h3 {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 0.5rem;
        }

        .stat-info .number {
            font-size: 2rem;
            font-weight: 700;
            color: #1a3a1a;
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .stat-icon i {
            font-size: 2rem;
            color: #ffd700;
        }

        /* Sections */
        .section {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .section-title {
            font-size: 1.3rem;
            color: #1a3a1a;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
            border-bottom: 2px solid #f0f2f5;
            padding-bottom: 0.5rem;
        }

        .section-title i {
            color: #ffd700;
        }

        /* Tables */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        th {
            background: #f8f9fa;
            color: #1a3a1a;
            font-weight: 600;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            display: inline-block;
        }

        .badge-pending {
            background: #fff3cd;
            color: #856404;
        }

        .badge-verified, .badge-approved {
            background: #d4edda;
            color: #155724;
        }

        .badge-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        .badge-info {
            background: #17a2b8;
            color: white;
        }

        .btn {
            padding: 0.4rem 1rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            font-size: 0.85rem;
            transition: all 0.3s;
            display: inline-block;
            margin: 0.2rem;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .btn-primary {
            background: #2c5f2d;
            color: white;
        }

        .btn-primary:hover {
            background: #1a3a1a;
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .btn-info:hover {
            background: #138496;
            transform: translateY(-2px);
        }

        .btn-sm {
            padding: 0.25rem 0.75rem;
            font-size: 0.8rem;
        }

        /* Document Preview */
        .doc-preview {
            display: flex;
            gap: 0.5rem;
            align-items: center;
            flex-wrap: wrap;
        }

        .proof-thumbnail {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            cursor: pointer;
            border: 2px solid #ddd;
            transition: all 0.3s;
        }

        .proof-thumbnail:hover {
            transform: scale(1.05);
            border-color: #2c5f2d;
        }

        .doc-link {
            background: #f0f2f5;
            padding: 0.3rem 0.8rem;
            border-radius: 5px;
            text-decoration: none;
            color: #2c5f2d;
            font-size: 0.8rem;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .doc-link:hover {
            background: #2c5f2d;
            color: white;
        }

        .file-missing {
            color: #dc3545;
            font-size: 0.8rem;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
        }

        .modal-content {
            position: relative;
            margin: 5% auto;
            padding: 20px;
            width: 90%;
            max-width: 900px;
            background: white;
            border-radius: 10px;
            text-align: center;
        }

        .modal-content img, .modal-content iframe {
            max-width: 100%;
            max-height: 70vh;
        }

        .close {
            position: absolute;
            right: 20px;
            top: 10px;
            font-size: 30px;
            cursor: pointer;
            color: #333;
        }

        .close:hover {
            color: #dc3545;
        }

        /* Form Styles */
        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
            font-weight: 500;
        }

        .form-group label i {
            margin-right: 5px;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 0.7rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-family: inherit;
            font-size: 0.95rem;
            transition: all 0.3s;
        }

        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            outline: none;
            border-color: #2c5f2d;
            box-shadow: 0 0 0 3px rgba(44, 95, 45, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }

        /* Charts */
        .charts-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .chart-card {
            background: white;
            padding: 1.5rem;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .chart-card h3 {
            margin-bottom: 1rem;
            color: #1a3a1a;
        }

        canvas {
            max-height: 300px;
        }

        /* Amount Highlight */
        .amount-highlight {
            font-size: 1.1rem;
            font-weight: bold;
            color: #28a745;
        }

        /* Fund Management Tab Styles */
        .fund-tabs {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .fund-tab-btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .fund-tab-btn:hover {
            transform: translateY(-2px);
        }

        .fund-tab-active {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
        }

        /* Alert Messages */
        .alert {
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideIn 0.3s ease-out;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffc107;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border-left: 4px solid #17a2b8;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Search Input */
        #searchHistory, #filterType {
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: inherit;
        }

        #searchHistory:focus, #filterType:focus {
            outline: none;
            border-color: #2c5f2d;
        }

        /* Transaction Rows */
        .transaction-row {
            transition: all 0.3s;
        }

        .transaction-row:hover {
            background: #f8f9fa;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                left: -260px;
            }
            .main-content {
                margin-left: 0;
            }
            .sidebar.active {
                left: 0;
            }
            .menu-toggle {
                display: block;
                position: fixed;
                top: 1rem;
                left: 1rem;
                z-index: 101;
                background: #1a3a1a;
                color: white;
                padding: 0.5rem;
                border-radius: 5px;
                cursor: pointer;
            }
            .charts-section {
                grid-template-columns: 1fr;
            }
            .fund-tabs {
                flex-direction: column;
            }
            .fund-tab-btn {
                justify-content: center;
            }
        }

        @media (min-width: 769px) {
            .menu-toggle {
                display: none;
            }
        }
    </style>
</head>
<body>
    <!-- Mobile Menu Toggle -->
    <div class="menu-toggle" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </div>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h3><i class="fas fa-cow"></i> Gau Seva Admin</h3>
        </div>
        <div class="sidebar-menu">
            <a onclick="showSection('dashboard')">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            <a onclick="showSection('kyc')">
                <i class="fas fa-id-card"></i> KYC Requests
                <?php if($pending_kyc_count > 0): ?>
                    <span class="badge-count"><?= $pending_kyc_count ?></span>
                <?php endif; ?>
            </a>
            <a onclick="showSection('payments')">
                <i class="fas fa-credit-card"></i> Payment Proofs
                <?php if($pending_payments_count > 0): ?>
                    <span class="badge-count"><?= $pending_payments_count ?></span>
                <?php endif; ?>
            </a>
            <a onclick="showSection('cancellations')">
                <i class="fas fa-user-times"></i> Cancellations
                <?php if($pending_cancellations_count > 0): ?>
                    <span class="badge-count"><?= $pending_cancellations_count ?></span>
                <?php endif; ?>
            </a>
            <a onclick="showSection('funds')">
                <i class="fas fa-money-bill-wave"></i> Fund Management
            </a>
            <a onclick="showSection('distributions')">
                <i class="fas fa-chart-line"></i> Distributions
            </a>
            <a onclick="showSection('members')">
                <i class="fas fa-users"></i> Members
            </a>
            <a onclick="showSection('rejected-kyc')">
                <i class="fas fa-times-circle"></i> Rejected KYC
            </a>
            <a href="../logout.php">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="top-navbar">
            <div class="page-title">
                <h2><i class="fas fa-tachometer-alt"></i> Admin Dashboard</h2>
            </div>
            <div class="user-info">
                <span><i class="fas fa-user-shield"></i> Administrator</span>
                <a href="../logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>

        <!-- Dashboard Section -->
        <div id="dashboard-section">
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Total Funds Collected</h3>
                        <div class="number">₹<?= number_format($total_fund, 2) ?></div>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-rupee-sign"></i>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Total Members</h3>
                        <div class="number"><?= $total_members ?></div>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Pending KYC</h3>
                        <div class="number"><?= $pending_kyc_count ?></div>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Pending Payments</h3>
                        <div class="number"><?= $pending_payments_count ?></div>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-hourglass-half"></i>
                    </div>
                </div>
            </div>

            <div class="charts-section">
                <div class="chart-card">
                    <h3><i class="fas fa-chart-pie"></i> Donation Overview</h3>
                    <canvas id="donationChart"></canvas>
                </div>
                <div class="chart-card">
                    <h3><i class="fas fa-chart-line"></i> Monthly Trends</h3>
                    <canvas id="trendChart"></canvas>
                </div>
            </div>
        </div>

        <!-- KYC Section -->
        <div id="kyc-section" style="display: none;">
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-id-card"></i> Pending KYC Verification Requests
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr><th>ID</th><th>Name</th><th>Email</th><th>Mobile</th><th>KYC Document</th><th>Submitted On</th><th>Action</th></tr>
                        </thead>
                        <tbody>
                            <?php if($pending_kyc && $pending_kyc->num_rows > 0): ?>
                                <?php while($row = $pending_kyc->fetch_assoc()): 
                                    $fileInfo = getFilePreview($row['kyc_doc']);
                                ?>
                                <tr>
                                    <td>#<?= $row['id'] ?></td>
                                    <td><?= htmlspecialchars($row['name']) ?></td>
                                    <td><?= htmlspecialchars($row['email']) ?></td>
                                    <td><?= htmlspecialchars($row['mobile'] ?: 'N/A') ?></td>
                                    <td>
                                        <?php if($fileInfo['exists']): ?>
                                            <div class="doc-preview">
                                                <?php if($fileInfo['type'] == 'image'): ?>
                                                    <img src="<?= $fileInfo['web_url'] ?>" class="proof-thumbnail" onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'image')">
                                                <?php else: ?>
                                                    <i class="fas fa-file-pdf" style="font-size: 2rem; color: #dc3545;"></i>
                                                <?php endif; ?>
                                                <a href="javascript:void(0)" class="doc-link" onclick="showDocument('<?= $fileInfo['web_url'] ?>', '<?= $fileInfo['type'] ?>')">
                                                    <i class="fas fa-eye"></i> View
                                                </a>
                                            </div>
                                        <?php else: ?>
                                            <span class="file-missing"><i class="fas fa-times-circle"></i> File missing</span>
                                        <?php endif; ?>
                                     </td>
                                    <td><?= date('d M Y, h:i A', strtotime($row['created_at'])) ?></td>
                                    <td>
                                        <a href="approve_kyc.php?id=<?= $row['id'] ?>" class="btn btn-success btn-sm" onclick="return confirm('Approve KYC?')">
                                            <i class="fas fa-check"></i> Approve
                                        </a>
                                        <a href="reject_kyc.php?id=<?= $row['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Reject KYC?')">
                                            <i class="fas fa-times"></i> Reject
                                        </a>
                                     </td>
                                 </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="7" style="text-align: center;">No pending KYC requests</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Payments Section -->
        <div id="payments-section" style="display: none;">
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-credit-card"></i> Pending Payment Verifications
                    <span class="badge-count" style="background: #ffc107; color: #333;"><?= $pending_payments_count ?> Pending</span>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User Name</th>
                                <th>Amount</th>
                                <th>Payment Proof</th>
                                <th>Transaction Date</th>
                                <th>Action</th>
                             </tr>
                        </thead>
                        <tbody>
                            <?php if($pending_payments && $pending_payments->num_rows > 0): ?>
                                <?php while($pay = $pending_payments->fetch_assoc()): 
                                    $fileInfo = getFilePreview($pay['payment_proof']);
                                ?>
                                <tr>
                                    <td>#<?= str_pad($pay['id'], 6, '0', STR_PAD_LEFT) ?></td>
                                    <td><?= htmlspecialchars($pay['user_name']) ?></td>
                                    <td><span class="amount-highlight">₹<?= number_format($pay['amount'], 2) ?></span></td>
                                    <td>
                                        <?php if($fileInfo['exists']): ?>
                                            <div class="doc-preview">
                                                <?php if($fileInfo['type'] == 'image'): ?>
                                                    <img src="<?= $fileInfo['web_url'] ?>" class="proof-thumbnail" 
                                                         onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'image')">
                                                    <a href="javascript:void(0)" class="doc-link" onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'image')">
                                                        <i class="fas fa-search-plus"></i> View
                                                    </a>
                                                <?php else: ?>
                                                    <i class="fas fa-file-pdf" style="font-size: 2rem; color: #dc3545;"></i>
                                                    <a href="javascript:void(0)" class="doc-link" onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'pdf')">
                                                        <i class="fas fa-file-pdf"></i> View PDF
                                                    </a>
                                                <?php endif; ?>
                                                <a href="<?= $fileInfo['web_url'] ?>" download class="doc-link">
                                                    <i class="fas fa-download"></i> Download
                                                </a>
                                            </div>
                                        <?php else: ?>
                                            <span class="file-missing"><i class="fas fa-exclamation-triangle"></i> File not found</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= date('d M Y, h:i A', strtotime($pay['uploaded_at'])) ?></td>
                                    <td>
                                        <a href="verify_payment.php?id=<?= $pay['id'] ?>&action=approve" class="btn btn-success btn-sm">Verify</a>
                                        <a href="verify_payment.php?id=<?= $pay['id'] ?>&action=reject" class="btn btn-danger btn-sm">Reject</a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="6" style="text-align: center;">No pending payment verifications</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Cancellations Section -->
        <div id="cancellations-section" style="display: none;">
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-user-times"></i> Membership Cancellation Requests
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr><th>User</th><th>Reason</th><th>Requested On</th><th>Action</th> </tr>
                        </thead>
                        <tbody>
                            <?php if($cancel_reqs && $cancel_reqs->num_rows > 0): ?>
                                <?php while($cancel = $cancel_reqs->fetch_assoc()): ?>
                                <tr>
                                    <td><?= htmlspecialchars($cancel['user_name']) ?></td>
                                    <td><?= htmlspecialchars(substr($cancel['reason'], 0, 100)) ?>...</td>
                                    <td><?= date('d M Y, h:i A', strtotime($cancel['requested_at'])) ?></td>
                                    <td>
                                        <a href="process_cancel.php?id=<?= $cancel['id'] ?>&action=approve" class="btn btn-success btn-sm">Approve</a>
                                        <a href="process_cancel.php?id=<?= $cancel['id'] ?>&action=reject" class="btn btn-danger btn-sm">Reject</a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="4" style="text-align: center;">No pending cancellation requests</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Improved Fund Management Section -->
        <div id="funds-section" style="display: none;">
            <!-- Fund Statistics Overview -->
            <div class="stats-grid" style="margin-bottom: 1.5rem;">
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Total Donations Received</h3>
                        <div class="number" style="color: #28a745;">₹<?= number_format($total_fund, 2) ?></div>
                        <small>From verified donations</small>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-hand-holding-heart"></i>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Total Distributed/Used</h3>
                        <div class="number" style="color: #17a2b8;">₹<?= number_format($total_distributed, 2) ?></div>
                        <small>For cow welfare & expenses</small>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-info">
                        <h3>Available Balance</h3>
                        <div class="number" style="color: #ffc107;">₹<?= number_format(max(0, $total_fund - $total_distributed), 2) ?></div>
                        <small>Ready for use</small>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-wallet"></i>
                    </div>
                </div>
            </div>

            <!-- Tab Navigation -->
            <div class="fund-tabs">
                <button onclick="showFundTab('deduct')" id="tabDeductBtn" class="fund-tab-btn btn btn-danger">
                    <i class="fas fa-download"></i> Deduct Funds
                </button>
                <button onclick="showFundTab('withdrawals')" id="tabWithdrawalsBtn" class="fund-tab-btn btn btn-info">
                    <i class="fas fa-money-bill-wave"></i> Withdrawal Requests
                </button>
                <button onclick="showFundTab('history')" id="tabHistoryBtn" class="fund-tab-btn btn btn-primary">
                    <i class="fas fa-history"></i> Transaction History
                </button>
            </div>

            <!-- Deduct Funds Tab -->
            <div id="deductTab" class="section">
                <div class="section-title">
                    <i class="fas fa-download"></i> Deduct / Withdraw Funds
                </div>
                
                <?php $available_balance = max(0, $total_fund - $total_distributed); ?>
                
                <form action="deduct_fund.php" method="POST" onsubmit="return validateDeduction()">
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-rupee-sign"></i> Amount to Deduct (₹)</label>
                            <input type="number" step="0.01" name="amount" id="deductAmount" required 
                                   placeholder="Enter amount" max="<?= $available_balance ?>"
                                   oninput="validateDeductAmount(this)">
                            <small id="amountHelp" style="color: #666;">Maximum available: ₹<?= number_format($available_balance, 2) ?></small>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-tag"></i> Transaction Type</label>
                            <select name="deduction_type" id="deductionType" required>
                                <option value="expense">General Expense</option>
                                <option value="cow_feed">Cow Feed Purchase</option>
                                <option value="medical">Medical Treatment</option>
                                <option value="shelter">Shelter Maintenance</option>
                                <option value="staff_salary">Staff Salary</option>
                                <option value="withdrawal">Fund Withdrawal</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-comment"></i> Reason / Description</label>
                        <textarea name="reason" id="deductReason" rows="3" required 
                                  placeholder="Provide detailed reason for this deduction..."></textarea>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-file"></i> Attachment (Optional)</label>
                        <input type="file" name="attachment" accept=".jpg,.jpeg,.png,.pdf">
                        <small>Upload bill/invoice if available</small>
                    </div>
                    <div class="alert alert-warning" style="margin-top: 1rem;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <span><strong>Warning:</strong> This action will permanently deduct funds. Please double-check the amount and reason.</span>
                    </div>
                    <button type="submit" class="btn btn-danger" style="width: auto; padding: 0.75rem 2rem;">
                        <i class="fas fa-download"></i> Confirm Deduction
                    </button>
                </form>
            </div>

            <!-- Withdrawal Requests Tab -->
            <div id="withdrawalsTab" style="display: none;" class="section">
                <div class="section-title">
                    <i class="fas fa-money-bill-wave"></i> Withdrawal Requests from Members
                </div>
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>Request ID</th>
                                <th>Member Name</th>
                                <th>Amount</th>
                                <th>Reason</th>
                                <th>Request Date</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($withdrawal_requests && $withdrawal_requests->num_rows > 0): ?>
                                <?php while($wr = $withdrawal_requests->fetch_assoc()): ?>
                                <tr>
                                    <td>#<?= str_pad($wr['id'], 6, '0', STR_PAD_LEFT) ?></td>
                                    <td><?= htmlspecialchars($wr['user_name']) ?></td>
                                    <td><span class="amount-highlight">₹<?= number_format($wr['amount'], 2) ?></span></td>
                                    <td><?= htmlspecialchars(substr($wr['reason'], 0, 50)) ?>...</td>
                                    <td><?= date('d M Y, h:i A', strtotime($wr['requested_at'])) ?></td>
                                    <td><span class="badge badge-pending">Pending</span></td>
                                    <td>
                                        <button onclick="processWithdrawal(<?= $wr['id'] ?>, <?= $wr['amount'] ?>, 'approve')" class="btn btn-success btn-sm">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                        <button onclick="processWithdrawal(<?= $wr['id'] ?>, <?= $wr['amount'] ?>, 'reject')" class="btn btn-danger btn-sm">
                                            <i class="fas fa-times"></i> Reject
                                        </button>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="7" style="text-align: center;">No pending withdrawal requests</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Transaction History Tab -->
            <div id="historyTab" style="display: none;" class="section">
                <div class="section-title">
                    <i class="fas fa-history"></i> Complete Transaction History
                </div>
                
                <!-- Filter Options -->
                <div style="margin-bottom: 1.5rem; display: flex; gap: 1rem; flex-wrap: wrap;">
                    <input type="text" id="searchHistory" placeholder="Search by description..." style="flex: 1;">
                    <select id="filterType" style="padding: 0.5rem;">
                        <option value="all">All Transactions</option>
                        <option value="donation">Donations</option>
                        <option value="deduction">Deductions</option>
                        <option value="distribution">Distributions</option>
                    </select>
                </div>
                
                <div class="table-container">
                    <table id="historyTable">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Description</th>
                                <th>Amount</th>
                                <th>Recipient/Purpose</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // Get all donations
                            $donations = $conn->query("
                                SELECT d.*, u.name as user_name 
                                FROM donations d 
                                JOIN users u ON d.user_id = u.id 
                                WHERE d.status='verified' 
                                ORDER BY d.uploaded_at DESC 
                                LIMIT 20
                            ");
                            
                            // Get all distributions
                            $distributions = $conn->query("
                                SELECT *, 'distribution' as trans_type 
                                FROM fund_distributions 
                                ORDER BY date DESC 
                                LIMIT 20
                            ");
                            
                            if($donations && $donations->num_rows > 0):
                                while($donation = $donations->fetch_assoc()):
                            ?>
                            <tr class="transaction-row donation">
                                <td><?= date('d M Y', strtotime($donation['uploaded_at'])) ?></td>
                                <td><span class="badge badge-verified"><i class="fas fa-plus-circle"></i> Donation</span></td>
                                <td>Donation from <?= htmlspecialchars($donation['user_name']) ?></td>
                                <td style="color: #28a745;">+ ₹<?= number_format($donation['amount'], 2) ?> </td>
                                <td><?= htmlspecialchars($donation['user_name']) ?></td>
                            </tr>
                            <?php endwhile; endif; ?>
                            
                            <?php if($distributions && $distributions->num_rows > 0):
                                while($dist = $distributions->fetch_assoc()):
                                    $isDeduction = strpos($dist['description'], '[DEDUCTION]') !== false;
                            ?>
                            <tr class="transaction-row <?= $isDeduction ? 'deduction' : 'distribution' ?>">
                                <td><?= date('d M Y', strtotime($dist['date'])) ?></td>
                                <td>
                                    <span class="badge <?= $isDeduction ? 'badge-rejected' : 'badge-info' ?>">
                                        <i class="fas <?= $isDeduction ? 'fa-minus-circle' : 'fa-chart-line' ?>"></i>
                                        <?= $isDeduction ? 'Deduction' : 'Distribution' ?>
                                    </span>
                                 </td>
                                <td><?= htmlspecialchars(str_replace('[DEDUCTION] ', '', $dist['description'])) ?> </td>
                                <td style="color: #dc3545;">- ₹<?= number_format($dist['amount'], 2) ?> </td>
                                <td><?= htmlspecialchars($dist['distributed_to']) ?> </td>
                            </tr>
                            <?php endwhile; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Distributions Section -->
        <div id="distributions-section" style="display: none;">
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-chart-line"></i> Add Fund Distribution
                </div>
                <form action="fund_distribution.php" method="POST">
                    <div class="form-group">
                        <label>Description</label>
                        <input type="text" name="desc" required placeholder="e.g., Cow Feed Purchase">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Amount (₹)</label>
                            <input type="number" step="0.01" name="amount" required>
                        </div>
                        <div class="form-group">
                            <label>Distributed To</label>
                            <input type="text" name="to" required placeholder="Recipient name">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Add Distribution</button>
                </form>
            </div>
            
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-history"></i> Distribution History
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead><tr><th>Date</th><th>Description</th><th>Amount</th><th>Distributed To</th> </thead>
                        <tbody>
                            <?php 
                            $all_distributions = $conn->query("SELECT * FROM fund_distributions ORDER BY date DESC");
                            while($dist = $all_distributions->fetch_assoc()): 
                            ?>
                            <tr>
                                <td><?= date('d M Y', strtotime($dist['date'])) ?> </td>
                                <td><?= htmlspecialchars($dist['description']) ?> </td>
                                <td><strong>₹<?= number_format($dist['amount'], 2) ?></strong> </td>
                                <td><?= htmlspecialchars($dist['distributed_to']) ?> </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Members Section -->
        <div id="members-section" style="display: none;">
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-users"></i> All Registered Members
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr><th>ID</th><th>Name</th><th>Email</th><th>Mobile</th><th>KYC</th><th>Membership</th><th>Donation</th><th>Joined</th> </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $all_members = $conn->query("SELECT * FROM users WHERE role='user' ORDER BY created_at DESC");
                            while($member = $all_members->fetch_assoc()): 
                            ?>
                            <tr>
                                <td>#<?= $member['id'] ?> </td>
                                <td><?= htmlspecialchars($member['name']) ?> </td>
                                <td><?= htmlspecialchars($member['email']) ?> </td>
                                <td><?= htmlspecialchars($member['mobile'] ?: 'N/A') ?> </td>
                                <td><span class="badge <?= $member['kyc_status'] == 'approved' ? 'badge-verified' : ($member['kyc_status'] == 'pending' ? 'badge-pending' : 'badge-rejected') ?>"><?= ucfirst($member['kyc_status']) ?></span> </td>
                                <td><span class="badge <?= $member['membership_active'] ? 'badge-verified' : 'badge-rejected' ?>"><?= $member['membership_active'] ? 'Active' : 'Cancelled' ?></span> </td>
                                <td>₹<?= number_format($member['total_donation'], 2) ?> </td>
                                <td><?= date('d M Y', strtotime($member['created_at'])) ?> </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Rejected KYC Section -->
        <div id="rejected-kyc-section" style="display: none;">
            <div class="section">
                <div class="section-title">
                    <i class="fas fa-times-circle"></i> Rejected KYC Documents
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>KYC Document</th><th>Action</th> </tr>
                        </thead>
                        <tbody>
                            <?php if($rejected_kyc && $rejected_kyc->num_rows > 0): ?>
                                <?php while($row = $rejected_kyc->fetch_assoc()): 
                                    $fileInfo = getFilePreview($row['kyc_doc']);
                                ?>
                                <tr>
                                    <td>#<?= $row['id'] ?> </td>
                                    <td><?= htmlspecialchars($row['name']) ?> </td>
                                    <td><?= htmlspecialchars($row['email']) ?> </td>
                                    <td>
                                        <?php if($fileInfo['exists']): ?>
                                            <div class="doc-preview">
                                                <?php if($fileInfo['type'] == 'image'): ?>
                                                    <img src="<?= $fileInfo['web_url'] ?>" class="proof-thumbnail" onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'image')">
                                                <?php else: ?>
                                                    <i class="fas fa-file-pdf" style="font-size: 2rem;"></i>
                                                <?php endif; ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="file-missing">No Document</span>
                                        <?php endif; ?>
                                     </td>
                                    <td>
                                        <a href="approve_kyc.php?id=<?= $row['id'] ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-undo"></i> Re-submit Request
                                        </a>
                                     </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="5" style="text-align: center;">No rejected KYC documents</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Document View Modal -->
    <div id="docModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeDocModal()">&times;</span>
            <div id="docContent"></div>
        </div>
    </div>

    <script>
        // Sidebar Toggle
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
        }

        // Section Navigation
        function showSection(section) {
            // Hide all sections
            const sections = ['dashboard-section', 'kyc-section', 'payments-section', 'cancellations-section', 
                             'funds-section', 'distributions-section', 'members-section', 'rejected-kyc-section'];
            sections.forEach(sectionId => {
                const element = document.getElementById(sectionId);
                if(element) element.style.display = 'none';
            });
            
            // Show selected section
            const sectionId = section + '-section';
            const selectedSection = document.getElementById(sectionId);
            if(selectedSection) selectedSection.style.display = 'block';
            
            // Reset fund tab to deduct if funds section is shown
            if(section === 'funds') {
                showFundTab('deduct');
            }
            
            // Update active class in sidebar
            document.querySelectorAll('.sidebar-menu a').forEach(link => {
                link.classList.remove('active');
            });
            if(event && event.target) {
                event.target.classList.add('active');
            }
            
            // Close sidebar on mobile
            if(window.innerWidth <= 768) {
                document.getElementById('sidebar').classList.remove('active');
            }
        }

        // Fund Management Tab Functions
        function showFundTab(tab) {
            // Hide all tabs
            const deductTab = document.getElementById('deductTab');
            const withdrawalsTab = document.getElementById('withdrawalsTab');
            const historyTab = document.getElementById('historyTab');
            
            if(deductTab) deductTab.style.display = 'none';
            if(withdrawalsTab) withdrawalsTab.style.display = 'none';
            if(historyTab) historyTab.style.display = 'none';
            
            // Show selected tab
            if(tab === 'deduct') {
                if(deductTab) deductTab.style.display = 'block';
                highlightTabButton('tabDeductBtn');
            } else if(tab === 'withdrawals') {
                if(withdrawalsTab) withdrawalsTab.style.display = 'block';
                highlightTabButton('tabWithdrawalsBtn');
            } else if(tab === 'history') {
                if(historyTab) historyTab.style.display = 'block';
                highlightTabButton('tabHistoryBtn');
                filterHistory();
            }
        }
        
        function highlightTabButton(buttonId) {
            // Reset all tab buttons
            const buttons = ['tabDeductBtn', 'tabWithdrawalsBtn', 'tabHistoryBtn'];
            buttons.forEach(id => {
                const btn = document.getElementById(id);
                if(btn) {
                    btn.style.opacity = '0.7';
                    btn.classList.remove('fund-tab-active');
                }
            });
            
            // Highlight selected button
            const selectedBtn = document.getElementById(buttonId);
            if(selectedBtn) {
                selectedBtn.style.opacity = '1';
                selectedBtn.classList.add('fund-tab-active');
            }
        }
        
        // Validate deduction amount
        function validateDeductAmount(input) {
            const value = parseFloat(input.value);
            const max = <?= $available_balance ?>;
            const helpText = document.getElementById('amountHelp');
            
            if(isNaN(value)) {
                input.setCustomValidity('Please enter a valid amount');
                if(helpText) helpText.style.color = '#dc3545';
            } else if(value <= 0) {
                input.setCustomValidity('Amount must be greater than 0');
                if(helpText) helpText.style.color = '#dc3545';
            } else if(value > max) {
                input.setCustomValidity(`Amount cannot exceed available balance of ₹${max.toFixed(2)}`);
                if(helpText) {
                    helpText.style.color = '#dc3545';
                    helpText.innerHTML = `⚠️ Maximum available: ₹${max.toFixed(2)}`;
                }
            } else {
                input.setCustomValidity('');
                if(helpText) {
                    helpText.style.color = '#28a745';
                    helpText.innerHTML = `✓ Available balance: ₹${max.toFixed(2)}`;
                }
            }
        }
        
        function validateDeduction() {
            const amountInput = document.getElementById('deductAmount');
            const amount = parseFloat(amountInput ? amountInput.value : 0);
            const reason = document.getElementById('deductReason');
            const max = <?= $available_balance ?>;
            
            if(isNaN(amount) || amount <= 0) {
                alert('Please enter a valid amount');
                return false;
            }
            
            if(amount > max) {
                alert(`Amount cannot exceed available balance of ₹${max.toFixed(2)}`);
                return false;
            }
            
            if(reason && reason.value.trim() === '') {
                alert('Please provide a reason for deduction');
                return false;
            }
            
            return confirm(`Are you sure you want to deduct ₹${amount.toFixed(2)}?\n\nThis action cannot be undone.`);
        }
        
        // Process withdrawal request
        function processWithdrawal(requestId, amount, action) {
            const confirmMsg = action === 'approve' 
                ? `Approve withdrawal of ₹${amount.toFixed(2)}? This will deduct from the total fund.`
                : `Reject withdrawal request of ₹${amount.toFixed(2)}?`;
            
            if(confirm(confirmMsg)) {
                window.location.href = `process_withdrawal.php?id=${requestId}&action=${action}`;
            }
        }
        
        // Document View Functions
        function showDocument(filePath, type) {
            const modal = document.getElementById('docModal');
            const docContent = document.getElementById('docContent');
            
            if(type === 'image') {
                docContent.innerHTML = `<img src="${filePath}?t=${Date.now()}" alt="Document" style="max-width: 100%; max-height: 70vh;" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%22 height=%22100%22 viewBox=%220 0 24 24%22 fill=%22%23dc3545%22%3E%3Cpath d=%22M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z%22/%3E%3C/svg%3E'">`;
            } else if(type === 'pdf') {
                docContent.innerHTML = `<iframe src="${filePath}" style="width: 100%; height: 70vh;" frameborder="0"></iframe>`;
            } else {
                docContent.innerHTML = `<div style="padding: 2rem; text-align: center;">
                    <i class="fas fa-file" style="font-size: 4rem; color: #666;"></i>
                    <p><a href="${filePath}" download class="btn btn-primary" style="margin-top: 1rem;">Download File</a></p>
                </div>`;
            }
            
            if(modal) modal.style.display = 'block';
        }
        
        function closeDocModal() {
            const modal = document.getElementById('docModal');
            const docContent = document.getElementById('docContent');
            if(modal) modal.style.display = 'none';
            if(docContent) docContent.innerHTML = '';
        }
        
        // Close modal on click outside
        window.onclick = function(event) {
            const modal = document.getElementById('docModal');
            if (event.target == modal) {
                closeDocModal();
            }
        }

        // Search and filter transaction history
        function filterHistory() {
            const searchInput = document.getElementById('searchHistory');
            const filterSelect = document.getElementById('filterType');
            const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
            const filterType = filterSelect ? filterSelect.value : 'all';
            const rows = document.querySelectorAll('#historyTable tbody tr');
            
            rows.forEach(row => {
                let show = true;
                
                // Filter by type
                if(filterType !== 'all') {
                    const rowType = row.classList.contains('donation') ? 'donation' : 
                                   (row.classList.contains('deduction') ? 'deduction' : 'distribution');
                    if(rowType !== filterType) {
                        show = false;
                    }
                }
                
                // Filter by search term
                if(show && searchTerm !== '') {
                    const text = row.innerText.toLowerCase();
                    if(!text.includes(searchTerm)) {
                        show = false;
                    }
                }
                
                row.style.display = show ? '' : 'none';
            });
        }

        // Set up event listeners for search and filter
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchHistory');
            const filterSelect = document.getElementById('filterType');
            
            if(searchInput) {
                searchInput.addEventListener('keyup', filterHistory);
            }
            
            if(filterSelect) {
                filterSelect.addEventListener('change', filterHistory);
            }
        });

        // Charts Data
        <?php
        // Get monthly donation data
        $monthly_data = [];
        $monthly_labels = [];
        for($i = 6; $i >= 0; $i--) {
            $month = date('M', strtotime("-$i months"));
            $monthly_labels[] = $month;
            $amount = $conn->query("SELECT COALESCE(SUM(amount), 0) as total FROM donations WHERE status='verified' AND MONTH(uploaded_at) = MONTH(DATE_SUB(NOW(), INTERVAL $i MONTH)) AND YEAR(uploaded_at) = YEAR(DATE_SUB(NOW(), INTERVAL $i MONTH))")->fetch_assoc()['total'];
            $monthly_data[] = $amount;
        }
        ?>
        
        // Donation Chart
        const donationCtx = document.getElementById('donationChart');
        if(donationCtx) {
            new Chart(donationCtx.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: ['Total Donations', 'Distributed Funds', 'Pending'],
                    datasets: [{
                        data: [<?= $total_fund ?>, <?= $total_distributed ?>, <?= $pending_payments_count * 500 ?>],
                        backgroundColor: ['#28a745', '#17a2b8', '#ffc107'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { position: 'bottom' }
                    }
                }
            });
        }
        
        // Trend Chart
        const trendCtx = document.getElementById('trendChart');
        if(trendCtx) {
            new Chart(trendCtx.getContext('2d'), {
                type: 'line',
                data: {
                    labels: <?= json_encode($monthly_labels) ?>,
                    datasets: [{
                        label: 'Monthly Donations (₹)',
                        data: <?= json_encode($monthly_data) ?>,
                        borderColor: '#2c5f2d',
                        backgroundColor: 'rgba(44, 95, 45, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { position: 'bottom' }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return '₹' + value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
        }
    </script>
</body>
</html>