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

// Display session messages
if(isset($_SESSION['success_msg'])) {
    echo '<div class="alert alert-success" style="position: fixed; top: 20px; right: 20px; z-index: 9999; background: #d4edda; color: #155724; padding: 1rem; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">' . $_SESSION['success_msg'] . '</div>';
    unset($_SESSION['success_msg']);
}
if(isset($_SESSION['error_msg'])) {
    echo '<div class="alert alert-error" style="position: fixed; top: 20px; right: 20px; z-index: 9999; background: #f8d7da; color: #721c24; padding: 1rem; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">' . $_SESSION['error_msg'] . '</div>';
    unset($_SESSION['error_msg']);
}

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

// Get total manual balance additions
$total_additions_query = $conn->query("SELECT COALESCE(SUM(amount), 0) as total FROM balance_additions");
$total_additions = $total_additions_query->fetch_assoc()['total'] ?? 0;

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

// Calculate available balance: (Total Donations + Manual Additions) - Total Distributed
$available_balance = max(0, ($total_fund + $total_additions) - $total_distributed);

$total_members = $conn->query("SELECT COUNT(*) as count FROM users WHERE role='user'")->fetch_assoc()['count'] ?? 0;
$pending_kyc_count = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_status='pending'")->fetch_assoc()['count'] ?? 0;
$pending_payments_count = $conn->query("SELECT COUNT(*) as count FROM donations WHERE status='pending'")->fetch_assoc()['count'] ?? 0;
$pending_cancellations_count = $conn->query("SELECT COUNT(*) as count FROM cancellation_requests WHERE status='pending'")->fetch_assoc()['count'] ?? 0;

// Get detailed data
$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");
$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");
$recent_distributions = $conn->query("SELECT * FROM fund_distributions ORDER BY date DESC LIMIT 5");
$rejected_kyc = $conn->query("SELECT * FROM users WHERE kyc_status='rejected' ORDER BY created_at DESC LIMIT 10");
$balance_additions = $conn->query("SELECT * FROM balance_additions ORDER BY added_at DESC LIMIT 10");

$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 getFilePreview($filePath) {
    if (empty($filePath)) return ['exists' => false, 'url' => '', 'type' => 'none'];
    $paths = [$filePath, "../" . $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, 'web_url' => $path, 'type' => $isImage ? 'image' : 'file'];
        }
    }
    return ['exists' => false];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - SHELDANG</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 Styles */
        .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; overflow-y: auto;
        }
        
        /* Custom Scrollbar */
        .sidebar::-webkit-scrollbar { width: 5px; }
        .sidebar::-webkit-scrollbar-track { background: #1a3a1a; }
        .sidebar::-webkit-scrollbar-thumb { background: #ffd700; border-radius: 5px; }
        
        .sidebar-header { 
            padding: 1.5rem; 
            text-align: center; 
            border-bottom: 1px solid rgba(255,255,255,0.1);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
        }
        
        .sidebar-logo {
            width: 60px;
            height: 60px;
            object-fit: contain;
            border-radius: 50%;
            background: rgba(255,255,255,0.1);
            padding: 8px;
        }
        
        .sidebar-header h3 { 
            font-size: 1.2rem; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 8px;
            margin-top: 5px;
        }
        
        .sidebar-header p {
            font-size: 0.7rem;
            opacity: 0.7;
            letter-spacing: 1px;
        }
        
        .sidebar-menu { padding: 1rem 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;
            border-left: 3px solid transparent;
        }
        
        .sidebar-menu a:hover, .sidebar-menu a.active { 
            background: rgba(255,215,0,0.15); 
            color: #ffd700; 
            border-left-color: #ffd700;
        }
        
        .badge-count { 
            background: #dc3545; 
            color: white; 
            border-radius: 10px; 
            padding: 2px 8px; 
            font-size: 0.65rem; 
            margin-left: auto; 
        }
        
        /* Main Content */
        .main-content { margin-left: 260px; padding: 1.5rem; }
        
        /* Top Navbar */
        .top-navbar {
            background: white; padding: 0.8rem 2rem; border-radius: 12px;
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            position: sticky;
            top: 0;
            z-index: 99;
        }
        
        /* Mobile Menu Button */
        .menu-toggle {
            display: none;
            position: fixed;
            top: 1rem;
            left: 1rem;
            z-index: 101;
            background: #1a3a1a;
            color: white;
            padding: 0.6rem;
            border-radius: 8px;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            transition: all 0.3s;
        }
        
        .menu-toggle:hover {
            background: #2c5f2d;
            transform: scale(1.05);
        }
        
        .page-title h2 { font-size: 1.3rem; color: #1a3a1a; display: flex; align-items: center; gap: 8px; }
        .logout-btn { 
            background: linear-gradient(135deg, #dc3545, #c82333); 
            color: white; 
            padding: 0.5rem 1.2rem; 
            border-radius: 8px; 
            text-decoration: none;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .logout-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(220,53,69,0.3); }
        
        /* User Info */
        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .user-info span {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #555;
            background: #f8f9fa;
            padding: 8px 15px;
            border-radius: 25px;
        }
        
        /* Stats Cards */
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 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.85rem; color: #666; margin-bottom: 0.5rem; }
        .stat-info .number { font-size: 1.8rem; font-weight: 700; color: #1a3a1a; }
        .stat-icon { width: 55px; height: 55px; background: linear-gradient(135deg, #2c5f2d, #1a3a1a); border-radius: 50%; display: flex; align-items: center; justify-content: center; }
        .stat-icon i { font-size: 1.8rem; color: #ffd700; }
        
        /* Sections */
        .section { background: white; border-radius: 15px; padding: 1.5rem; margin-bottom: 2rem; }
        .section-title { font-size: 1.2rem; color: #1a3a1a; margin-bottom: 1.2rem; display: flex; align-items: center; gap: 10px; border-bottom: 2px solid #f0f2f5; padding-bottom: 0.5rem; }
        
        /* Tables */
        .table-container { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 0.8rem; text-align: left; border-bottom: 1px solid #eee; font-size: 0.85rem; }
        th { background: #f8f9fa; color: #1a3a1a; font-weight: 600; }
        tr:hover { background: #f8f9fa; }
        
        /* Badges */
        .badge { padding: 0.2rem 0.7rem; border-radius: 20px; font-size: 0.75rem; font-weight: 500; display: inline-block; }
        .badge-pending { background: #fff3cd; color: #856404; }
        .badge-verified { background: #d4edda; color: #155724; }
        .badge-rejected { background: #f8d7da; color: #721c24; }
        .badge-success { background: #28a745; color: white; }
        
        /* Buttons */
        .btn { padding: 0.35rem 0.9rem; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; font-size: 0.8rem; display: inline-block; margin: 0.15rem; transition: all 0.3s; }
        .btn-success { background: #28a745; color: white; }
        .btn-success:hover { background: #218838; transform: translateY(-1px); }
        .btn-danger { background: #dc3545; color: white; }
        .btn-danger:hover { background: #c82333; transform: translateY(-1px); }
        .btn-primary { background: #2c5f2d; color: white; }
        .btn-primary:hover { background: #1a3a1a; transform: translateY(-1px); }
        .btn-info { background: #17a2b8; color: white; }
        .btn-info:hover { background: #138496; transform: translateY(-1px); }
        
        /* Fund Tabs */
        .fund-tabs { display: flex; gap: 0.8rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .fund-tab-btn { padding: 0.6rem 1.2rem; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.3s; font-size: 0.85rem; }
        .fund-tab-active { transform: translateY(-2px); box-shadow: 0 4px 10px rgba(0,0,0,0.15); opacity: 1 !important; }
        
        /* Forms */
        .form-group { margin-bottom: 1rem; }
        .form-group label { display: block; margin-bottom: 0.4rem; font-weight: 500; font-size: 0.85rem; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 0.6rem; border: 1px solid #ddd; border-radius: 8px; font-size: 0.85rem; }
        .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.2rem; border-radius: 12px; }
        canvas { max-height: 280px; }
        
        /* Alerts */
        .alert { padding: 0.8rem 1rem; border-radius: 8px; margin-bottom: 1rem; display: flex; align-items: center; gap: 10px; font-size: 0.85rem; }
        .alert-success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar { left: -260px; }
            .main-content { margin-left: 0; padding: 1rem; }
            .sidebar.active { left: 0; }
            .menu-toggle { display: block; }
            .top-navbar { flex-direction: column; gap: 1rem; text-align: center; padding: 1rem; }
            .user-info { justify-content: center; }
            .stats-grid { grid-template-columns: 1fr; gap: 1rem; }
            .fund-tabs { justify-content: center; }
            .charts-section { grid-template-columns: 1fr; }
            .stat-info .number { font-size: 1.5rem; }
        }
        
        @media (max-width: 480px) {
            .top-navbar { padding: 0.8rem; }
            .page-title h2 { font-size: 1.1rem; }
            .stat-card { padding: 1rem; }
            .stat-icon { width: 45px; height: 45px; }
            .stat-icon i { font-size: 1.4rem; }
            .section { padding: 1rem; }
            th, td { padding: 0.5rem; font-size: 0.75rem; }
            .fund-tab-btn { padding: 0.5rem 1rem; font-size: 0.75rem; }
        }
    </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">
            <img src="https://bmyouth.org/sheldang/assets/logo.png" alt="SHELDANG Logo" class="sidebar-logo" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3E%3Ccircle cx=%2750%27 cy=%2750%27 r=%2745%27 fill=%27%23ffd700%27/%3E%3Ctext x=%2750%27 y=%2770%27 text-anchor=%27middle%27 fill=%27%231a3a1a%27 font-size=%2730%27 font-weight=%27bold%27%3ES%3C/text%3E%3C/svg%3E'">
            <h3><i class="fas fa-dharmachakra"></i> SHELDANG</h3>
            <p>Admin Panel</p>
        </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 } ?></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 } ?></a>
            <a href="view_documents.php"><i class="fas fa-folder-open"></i> Document Management</a>
            <a href="manage_signatures.php"><i class="fas fa-signature"></i> Manage Signatures</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 } ?></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-dharmachakra"></i> SHELDANG 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 Donations</h3><div class="number" style="color: #28a745;">₹<?= number_format($total_fund, 2) ?></div><small>Online 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>Manual Additions</h3><div class="number" style="color: #17a2b8;">₹<?= number_format($total_additions, 2) ?></div><small>Offline/Cash additions</small></div>
                    <div class="stat-icon"><i class="fas fa-plus-circle"></i></div>
                </div>
                <div class="stat-card">
                    <div class="stat-info"><h3>Total Distributed</h3><div class="number" style="color: #dc3545;">₹<?= number_format($total_distributed, 2) ?></div><small>Expenses & deductions</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($available_balance, 2) ?></div><small>Ready for use</small></div>
                    <div class="stat-icon"><i class="fas fa-wallet"></i></div>
                </div>
            </div>
            <div class="charts-section">
                <div class="chart-card"><h3>Fund Overview</h3><canvas id="donationChart"></canvas></div>
                <div class="chart-card"><h3>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 Requests</div>
                <div class="table-container">
                    <table>
                        <thead><tr><th>Name</th><th>Email</th><th>Mobile</th><th>Submitted</th><th>Action</th></tr></thead>
                        <tbody><?php while($row = $pending_kyc->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['name']) ?></td>
                            <td><?= htmlspecialchars($row['email']) ?></td>
                            <td><?= $row['mobile'] ?></td>
                            <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                            <td>
                                <a href="approve_kyc.php?id=<?= $row['id'] ?>" class="btn btn-success btn-sm">Approve</a>
                                <a href="reject_kyc.php?id=<?= $row['id'] ?>" class="btn btn-danger btn-sm">Reject</a>
                            </td>
                        </tr>
                        <?php endwhile; ?></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 Payments</div>
                <div class="table-container">
                    <table>
                        <thead><tr><th>User</th><th>Amount</th><th>Proof</th><th>Date</th><th>Action</th></tr></thead>
                        <tbody><?php while($pay = $pending_payments->fetch_assoc()): $fileInfo = getFilePreview($pay['payment_proof']); ?>
                        <tr>
                            <td><?= htmlspecialchars($pay['user_name']) ?></td>
                            <td>₹<?= number_format($pay['amount'], 2) ?></td>
                            <td><?php if($fileInfo['exists']): ?><a href="<?= $fileInfo['web_url'] ?>" target="_blank">View</a><?php else: ?>No file<?php endif; ?></td>
                            <td><?= date('d M Y', 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; ?></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> Cancellation Requests</div>
                <div class="table-container">
                    <table>
                        <thead><tr><th>User</th><th>Reason</th><th>Date</th><th>Action</th></tr></thead>
                        <tbody><?php while($cancel = $cancel_reqs->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($cancel['user_name']) ?></td>
                            <td><?= substr(htmlspecialchars($cancel['reason']), 0, 50) ?>...</td>
                            <td><?= date('d M Y', 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; ?></tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Fund Management Section -->
        <div id="funds-section" style="display:none">
            <div class="stats-grid" style="margin-bottom:1.5rem">
                <div class="stat-card"><div class="stat-info"><h3>Total Donations</h3><div class="number" style="color:#28a745;">₹<?= number_format($total_fund, 2) ?></div></div><div class="stat-icon"><i class="fas fa-hand-holding-heart"></i></div></div>
                <div class="stat-card"><div class="stat-info"><h3>Manual Additions</h3><div class="number" style="color:#17a2b8;">₹<?= number_format($total_additions, 2) ?></div></div><div class="stat-icon"><i class="fas fa-plus-circle"></i></div></div>
                <div class="stat-card"><div class="stat-info"><h3>Total Distributed</h3><div class="number" style="color:#dc3545;">₹<?= number_format($total_distributed, 2) ?></div></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($available_balance, 2) ?></div></div><div class="stat-icon"><i class="fas fa-wallet"></i></div></div>
            </div>

            <div class="fund-tabs">
                <button onclick="showFundTab('add')" id="tabAddBtn" class="fund-tab-btn btn btn-success" style="background:#28a745;color:white;"><i class="fas fa-plus-circle"></i> Add Balance</button>
                <button onclick="showFundTab('deduct')" id="tabDeductBtn" class="fund-tab-btn btn btn-danger" style="background:#dc3545;color:white;"><i class="fas fa-download"></i> Deduct Funds</button>
                <button onclick="showFundTab('withdrawals')" id="tabWithdrawalsBtn" class="fund-tab-btn btn btn-info" style="background:#17a2b8;color:white;"><i class="fas fa-money-bill-wave"></i> Withdrawals</button>
                <button onclick="showFundTab('history')" id="tabHistoryBtn" class="fund-tab-btn btn btn-primary" style="background:#2c5f2d;color:white;"><i class="fas fa-history"></i> History</button>
            </div>

            <!-- Add Balance Tab -->
            <div id="addTab" class="section">
                <div class="section-title"><i class="fas fa-plus-circle"></i> Manual Balance Addition</div>
                <div class="alert alert-success"><i class="fas fa-info-circle"></i> <strong>Use this to:</strong> Add offline donations, cash contributions, bank transfers, or correct balance discrepancies.</div>
                <form action="add_balance.php" method="POST">
                    <div class="form-row">
                        <div class="form-group"><label>Amount (₹)</label><input type="number" step="0.01" name="amount" required placeholder="Enter amount"></div>
                        <div class="form-group"><label>Source Type</label>
                            <select name="source" required>
                                <option value="Offline Donation">Offline Donation</option><option value="Cash Contribution">Cash Contribution</option>
                                <option value="Bank Transfer">Bank Transfer</option><option value="Cheque">Cheque Deposit</option>
                                <option value="UPI Payment">UPI Payment</option><option value="Balance Correction">Balance Correction</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group"><label>Description / Remarks</label><textarea name="description" rows="3" required placeholder="Enter donor name, reference number, transaction ID, etc..."></textarea></div>
                    <button type="submit" class="btn btn-success" style="width:auto;padding:0.6rem 1.5rem;"><i class="fas fa-plus-circle"></i> Add to Balance</button>
                </form>
            </div>

            <!-- Deduct Funds Tab -->
            <div id="deductTab" class="section">
                <div class="section-title"><i class="fas fa-download"></i> Deduct Funds</div>
                <form action="deduct_fund.php" method="POST">
                    <div class="form-row">
                        <div class="form-group"><label>Amount (₹)</label><input type="number" step="0.01" name="amount" required placeholder="Enter amount" max="<?= $available_balance ?>"></div>
                        <div class="form-group"><label>Transaction Type</label>
                            <select name="deduction_type">
                                <option value="expense">Shrada Fund</option>
                                <option value="cow_feed">Education Fund</option>
                                <option value="medical">Medical Treatment</option>
                                <option value="shelter">Software Maintenance</option>
                                <option value="staff_salary">Server Maintenance</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group"><label>Reason</label><textarea name="reason" rows="3" required placeholder="Reason for deduction..."></textarea></div>
                    <button type="submit" class="btn btn-danger" style="width:auto;padding:0.6rem 1.5rem;"><i class="fas fa-download"></i> Confirm Deduction</button>
                </form>
            </div>

            <!-- Withdrawal Requests Tab -->
            <div id="withdrawalsTab" class="section">
                <div class="section-title"><i class="fas fa-money-bill-wave"></i> Withdrawal Requests</div>
                <div class="table-container">
                    <table>
                        <thead><tr><th>Member</th><th>Amount</th><th>Reason</th><th>Date</th><th>Action</th></tr></thead>
                        <tbody><?php while($wr = $withdrawal_requests->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($wr['user_name']) ?></td>
                            <td>₹<?= number_format($wr['amount'], 2) ?></td>
                            <td><?= substr(htmlspecialchars($wr['reason']), 0, 50) ?>...</td>
                            <td><?= date('d M Y', strtotime($wr['requested_at'])) ?></td>
                            <td>
                                <a href="process_withdrawal.php?id=<?= $wr['id'] ?>&action=approve" class="btn btn-success btn-sm">Approve</a>
                                <a href="process_withdrawal.php?id=<?= $wr['id'] ?>&action=reject" class="btn btn-danger btn-sm">Reject</a>
                            </td>
                        </tr>
                        <?php endwhile; ?></tbody>
                    </table>
                </div>
            </div>

            <!-- History Tab -->
            <div id="historyTab" class="section">
                <div class="section-title"><i class="fas fa-history"></i> Transaction History</div>
                <div style="margin-bottom:1rem"><input type="text" id="searchHistory" placeholder="Search transactions..." style="padding:0.5rem;width:100%;border:1px solid #ddd;border-radius:5px;"></div>
                <div class="table-container">
                    <table id="historyTable">
                        <thead><tr><th>Date</th><th>Type</th><th>Description</th><th>Amount</th></tr></thead>
                        <tbody>
                            <?php 
                            $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");
                            while($donation = $donations->fetch_assoc()): ?>
                            <tr class="donation-row">
                                <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>From <?= htmlspecialchars($donation['user_name']) ?></td>
                                <td style="color:#28a745;">+ ₹<?= number_format($donation['amount'], 2) ?></td>
                            </tr>
                            <?php endwhile; ?>
                            
                            <?php $additions = $conn->query("SELECT * FROM balance_additions ORDER BY added_at DESC LIMIT 20");
                            while($add = $additions->fetch_assoc()): ?>
                            <tr class="addition-row">
                                <td><?= date('d M Y', strtotime($add['added_at'])) ?></td>
                                <td><span class="badge badge-success"><i class="fas fa-plus-circle"></i> Balance Addition</span></td>
                                <td><?= htmlspecialchars($add['description']) ?> (Source: <?= htmlspecialchars($add['source']) ?>)</div>
                                <td style="color:#28a745;">+ ₹<?= number_format($add['amount'], 2) ?></td>
                            </tr>
                            <?php endwhile; ?>
                            
                            <?php $distributions = $conn->query("SELECT * FROM fund_distributions ORDER BY date DESC LIMIT 20");
                            while($dist = $distributions->fetch_assoc()): 
                                $isDeduction = strpos($dist['description'], '[DEDUCTION]') !== false;
                            ?>
                            <tr class="deduction-row">
                                <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>
                            </tr>
                            <?php endwhile; ?>
                        </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 Distribution</div>
                <form action="fund_distribution.php" method="POST">
                    <div class="form-row">
                        <div class="form-group"><label>Description</label><input type="text" name="desc" required></div>
                        <div class="form-group"><label>Amount</label><input type="number" step="0.01" name="amount" required></div>
                        <div class="form-group"><label>To</label><input type="text" name="to" required></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>
                        <thead><tr><th>Date</th><th>Description</th><th>Amount</th><th>To</th></tr></thead>
                        <tbody><?php $all_dist = $conn->query("SELECT * FROM fund_distributions ORDER BY date DESC"); while($dist = $all_dist->fetch_assoc()): ?>
                        <tr>
                            <td><?= date('d M Y', strtotime($dist['date'])) ?></td>
                            <td><?= htmlspecialchars($dist['description']) ?></td>
                            <td>₹<?= number_format($dist['amount'], 2) ?></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 Members</div>
                <div class="table-container">
                    <table>
                        <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>KYC</th><th>Membership</th><th>Donation</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><span class="badge <?= $member['kyc_status']=='approved'?'badge-verified':'badge-pending' ?>"><?= ucfirst($member['kyc_status']) ?></span></td>
                            <td><span class="badge <?= $member['membership_active']?'badge-verified':'badge-rejected' ?>"><?= $member['membership_active']?'Active':'Inactive' ?></span></td>
                            <td>₹<?= number_format($member['total_donation'], 2) ?></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</div>
                <div class="table-container">
                    <table>
                        <thead><tr><th>Name</th><th>Email</th><th>Document</th><th>Action</th></tr></thead>
                        <tbody><?php while($row = $rejected_kyc->fetch_assoc()): $fileInfo = getFilePreview($row['kyc_doc']); ?>
                        <tr>
                            <td><?= htmlspecialchars($row['name']) ?></td>
                            <td><?= htmlspecialchars($row['email']) ?></td>
                            <td><?php if($fileInfo['exists']): ?><a href="<?= $fileInfo['web_url'] ?>" target="_blank">View</a><?php else: ?>No file<?php endif; ?></td>
                            <td><a href="approve_kyc.php?id=<?= $row['id'] ?>" class="btn btn-primary btn-sm">Re-submit</a></td>
                        </tr>
                        <?php endwhile; ?></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleSidebar() { 
            document.getElementById('sidebar').classList.toggle('active'); 
        }
        
        function showSection(section) {
            const sections = ['dashboard-section', 'kyc-section', 'payments-section', 'cancellations-section', 'funds-section', 'distributions-section', 'members-section', 'rejected-kyc-section'];
            sections.forEach(s => { const el = document.getElementById(s); if(el) el.style.display = 'none'; });
            const selected = document.getElementById(section + '-section');
            if(selected) selected.style.display = 'block';
            if(section === 'funds') showFundTab('add');
            document.querySelectorAll('.sidebar-menu a').forEach(link => link.classList.remove('active'));
            if(event && event.target) event.target.classList.add('active');
            if(window.innerWidth <= 768) document.getElementById('sidebar').classList.remove('active');
        }
        
        function showFundTab(tab) {
            const tabs = ['addTab', 'deductTab', 'withdrawalsTab', 'historyTab'];
            tabs.forEach(t => { const el = document.getElementById(t); if(el) el.style.display = 'none'; });
            if(tab === 'add') { const el = document.getElementById('addTab'); if(el) el.style.display = 'block'; highlightTab('tabAddBtn'); }
            else if(tab === 'deduct') { const el = document.getElementById('deductTab'); if(el) el.style.display = 'block'; highlightTab('tabDeductBtn'); }
            else if(tab === 'withdrawals') { const el = document.getElementById('withdrawalsTab'); if(el) el.style.display = 'block'; highlightTab('tabWithdrawalsBtn'); }
            else if(tab === 'history') { const el = document.getElementById('historyTab'); if(el) el.style.display = 'block'; highlightTab('tabHistoryBtn'); filterHistory(); }
        }
        
        function highlightTab(buttonId) {
            const btns = ['tabAddBtn', 'tabDeductBtn', 'tabWithdrawalsBtn', 'tabHistoryBtn'];
            btns.forEach(id => { const btn = document.getElementById(id); if(btn) { btn.style.opacity = '0.7'; btn.classList.remove('fund-tab-active'); } });
            const selected = document.getElementById(buttonId);
            if(selected) { selected.style.opacity = '1'; selected.classList.add('fund-tab-active'); }
        }
        
        function filterHistory() {
            const searchTerm = document.getElementById('searchHistory')?.value.toLowerCase() || '';
            const rows = document.querySelectorAll('#historyTable tbody tr');
            rows.forEach(row => { row.style.display = row.innerText.toLowerCase().includes(searchTerm) ? '' : 'none'; });
        }
        
        document.getElementById('searchHistory')?.addEventListener('keyup', filterHistory);
        
        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function(event) {
            const sidebar = document.getElementById('sidebar');
            const menuToggle = document.querySelector('.menu-toggle');
            if(window.innerWidth <= 768 && sidebar && sidebar.classList.contains('active')) {
                if(!sidebar.contains(event.target) && !menuToggle.contains(event.target)) {
                    sidebar.classList.remove('active');
                }
            }
        });
        
        // Charts
        const donationCtx = document.getElementById('donationChart')?.getContext('2d');
        if(donationCtx) new Chart(donationCtx, { 
            type: 'doughnut', 
            data: { 
                labels: ['Total Donations', 'Manual Additions', 'Distributed', 'Available'], 
                datasets: [{ data: [<?= $total_fund ?>, <?= $total_additions ?>, <?= $total_distributed ?>, <?= $available_balance ?>], backgroundColor: ['#28a745', '#17a2b8', '#dc3545', '#ffc107'] }] 
            } 
        });
        
        const trendCtx = document.getElementById('trendChart')?.getContext('2d');
        if(trendCtx) new Chart(trendCtx, { 
            type: 'line', 
            data: { 
                labels: <?php $labels=[]; for($i=6;$i>=0;$i--) $labels[]=date('M',strtotime("-$i months")); echo json_encode($labels); ?>, 
                datasets: [{ label: 'Monthly Donations (₹)', data: <?php $data=[]; for($i=6;$i>=0;$i--) $data[]=$conn->query("SELECT COALESCE(SUM(amount),0) FROM donations WHERE status='verified' AND MONTH(uploaded_at)=MONTH(DATE_SUB(NOW(),INTERVAL $i MONTH))")->fetch_row()[0] ?? 0; echo json_encode($data); ?>, borderColor: '#2c5f2d', fill: true }] 
            } 
        });
    </script>
</body>
</html>