<?php
include '../includes/auth.php';
include '../config/db.php';
$user_id = $_SESSION['user_id'];

// Get user details
$user = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();

// Get total donation
$total_donation_query = $conn->query("SELECT SUM(amount) as total FROM donations WHERE user_id=$user_id AND status='verified'");
$total_donation = $total_donation_query->fetch_assoc()['total'] ?? 0;

// Get donation count
$donation_count = $conn->query("SELECT COUNT(*) as count FROM donations WHERE user_id=$user_id AND status='verified'")->fetch_assoc()['count'];

// Get recent donations
$recent_donations = $conn->query("SELECT * FROM donations WHERE user_id=$user_id AND status='verified' ORDER BY uploaded_at DESC LIMIT 5");

// Get fund distribution history
$distributions = $conn->query("SELECT * FROM fund_distributions ORDER BY date DESC LIMIT 10");

// Get total crowd fund collected (all verified donations)
$total_crowd_fund_query = $conn->query("SELECT SUM(amount) as total FROM donations WHERE status='verified'");
$total_crowd_fund = $total_crowd_fund_query->fetch_assoc()['total'] ?? 0;

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

// Get total donors count
$total_donors = $conn->query("SELECT COUNT(DISTINCT user_id) as count FROM donations WHERE status='verified'")->fetch_assoc()['count'];

// Get top 5 donors
$top_donors = $conn->query("
    SELECT u.name, SUM(d.amount) as total 
    FROM donations d 
    JOIN users u ON d.user_id = u.id 
    WHERE d.status='verified' 
    GROUP BY u.id 
    ORDER BY total DESC 
    LIMIT 5
");

// Get pending requests
$pending_kyc = ($user['kyc_status'] == 'pending');
$kyc_approved = ($user['kyc_status'] == 'approved');
$kyc_rejected = ($user['kyc_status'] == 'rejected');
$pending_cancellation = $conn->query("SELECT * FROM cancellation_requests WHERE user_id=$user_id AND status='pending'")->num_rows > 0;

// =============================================
// KYC Audio Reminder - Play audio until KYC is completed
// =============================================
$show_kyc_audio = $pending_kyc;

// =============================================
// NEW FUNCTION: KYC Completion Celebration Audio
// When KYC is completed, play sheldang.mp3 and show popup
// =============================================
$show_kyc_completion = false;
$kyc_completion_played = false;

// Check if KYC is approved and celebration hasn't been played yet
if ($kyc_approved) {
    // Check session if celebration has been played
    if (!isset($_SESSION['kyc_celebration_played'])) {
        $show_kyc_completion = true;
        $_SESSION['kyc_celebration_played'] = true;
    }
}

// Show popup for pending KYC
$show_kyc_popup = $pending_kyc;

// Show payment reminder popup for KYC approved users
$show_payment_popup = $kyc_approved;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User 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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        /* Dashboard Container */
        .dashboard-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        /* Header */
        .dashboard-header {
            background: white;
            border-radius: 20px;
            padding: 25px 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .header-title h1 {
            color: #2c5f2d;
            font-size: 1.8rem;
            margin-bottom: 5px;
        }

        .header-title p {
            color: #666;
            font-size: 0.9rem;
        }

        .header-actions {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .profile-btn {
            background: linear-gradient(135deg, #4a90e2, #357abd);
            color: white;
            padding: 10px 20px;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .profile-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(74,144,226,0.3);
        }

        .logout-btn {
            background: linear-gradient(135deg, #f56565, #e53e3e);
            color: white;
            padding: 10px 20px;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(229,62,62,0.3);
        }

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

        .stat-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            transition: all 0.3s;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, #2c5f2d, #ffd700);
        }

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

        .stat-icon {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #2c5f2d20, #ffd70020);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
        }

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

        .stat-info h3 {
            font-size: 2rem;
            color: #2c5f2d;
            margin-bottom: 5px;
        }

        .stat-info p {
            color: #666;
            font-size: 0.9rem;
        }

        .stat-badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            margin-top: 10px;
        }

        .badge-approved {
            background: #48bb7820;
            color: #2f855a;
        }

        .badge-pending {
            background: #f6e05e20;
            color: #975a16;
        }

        .badge-active {
            background: #4299e120;
            color: #2c5282;
        }

        .badge-info {
            background: #4299e120;
            color: #2c5282;
        }

        /* Quick Actions */
        .actions-section {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }

        .section-title {
            font-size: 1.5rem;
            color: #2c5f2d;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-title i {
            font-size: 1.8rem;
        }

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

        .action-card {
            background: linear-gradient(135deg, #f5f7fa, #fff);
            border: 2px solid #e0e0e0;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            text-decoration: none;
            color: #333;
            transition: all 0.3s;
            display: block;
        }

        .action-card:hover {
            transform: translateY(-5px);
            border-color: #2c5f2d;
            box-shadow: 0 10px 25px rgba(44,95,45,0.2);
        }

        .action-icon {
            width: 70px;
            height: 70px;
            background: linear-gradient(135deg, #2c5f2d, #3a7a3b);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
        }

        .action-icon i {
            font-size: 2rem;
            color: white;
        }

        .action-card h3 {
            font-size: 1.1rem;
            margin-bottom: 8px;
            color: #2c5f2d;
        }

        .action-card p {
            font-size: 0.85rem;
            color: #666;
        }

        /* Recent Donations */
        .recent-section {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }

        .donation-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
            transition: all 0.3s;
        }

        .donation-item:hover {
            background: #f7fafc;
            transform: translateX(5px);
        }

        .donation-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .donation-icon {
            width: 45px;
            height: 45px;
            background: #48bb7820;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .donation-icon i {
            font-size: 1.3rem;
            color: #2c5f2d;
        }

        .donation-details h4 {
            font-size: 1rem;
            margin-bottom: 5px;
        }

        .donation-details p {
            font-size: 0.85rem;
            color: #666;
        }

        .donation-amount {
            font-size: 1.3rem;
            font-weight: bold;
            color: #2c5f2d;
        }

        .donation-status {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            background: #48bb7820;
            color: #2f855a;
        }

        /* Top Donors Section */
        .top-donors-section {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }

        .donor-list {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }

        .donor-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            background: #f7fafc;
            border-radius: 15px;
            transition: all 0.3s;
        }

        .donor-item:hover {
            transform: translateX(5px);
            background: #edf2f7;
        }

        .donor-rank {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #ffd700, #f59e0b);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
        }

        .donor-rank.gold {
            background: linear-gradient(135deg, #ffd700, #f59e0b);
        }

        .donor-rank.silver {
            background: linear-gradient(135deg, #a0aec0, #718096);
        }

        .donor-rank.bronze {
            background: linear-gradient(135deg, #cd7f32, #b87333);
        }

        .donor-info {
            flex: 1;
        }

        .donor-name {
            font-weight: 600;
            color: #333;
        }

        .donor-amount {
            font-size: 0.85rem;
            color: #2c5f2d;
            font-weight: 500;
        }

        .donor-crown {
            font-size: 1.2rem;
        }

        /* Fund Distribution Table */
        .distribution-section {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            overflow-x: auto;
        }

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

        .distribution-table th {
            background: #f7fafc;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #2c5f2d;
            border-bottom: 2px solid #e0e0e0;
        }

        .distribution-table td {
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
            color: #555;
        }

        .distribution-table tr:hover {
            background: #f7fafc;
        }

        .amount-cell {
            font-weight: 600;
            color: #2c5f2d;
        }

        /* Progress Bar */
        .fund-progress {
            margin-top: 15px;
        }

        .progress-bar-container {
            background: #e0e0e0;
            border-radius: 10px;
            height: 8px;
            overflow: hidden;
            margin-top: 10px;
        }

        .progress-bar {
            background: linear-gradient(90deg, #2c5f2d, #48bb78);
            height: 100%;
            border-radius: 10px;
            transition: width 0.5s ease;
        }

        .progress-stats {
            display: flex;
            justify-content: space-between;
            margin-top: 8px;
            font-size: 0.75rem;
            color: #666;
        }

        /* Alert Messages */
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-warning {
            background: #fef5e7;
            border-left: 4px solid #f39c12;
            color: #e67e22;
        }

        .alert-info {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            color: #1976d2;
        }

        .alert-success {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            color: #2e7d32;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
        }

        /* ========== POPUP MODAL STYLES ========== */
        .popup-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 9999;
            justify-content: center;
            align-items: center;
            animation: fadeIn 0.2s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .popup-container {
            background: white;
            border-radius: 10px;
            max-width: 340px;
            width: 90%;
            overflow: hidden;
            animation: slideIn 0.3s ease;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }

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

        .popup-header {
            padding: 10px 15px;
            text-align: center;
            position: relative;
        }

        .popup-header.kyc-header {
            background: linear-gradient(135deg, #ff9800, #f57c00);
        }

        .popup-header.payment-header {
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
        }

        .popup-header.celebration-header {
            background: linear-gradient(135deg, #ffd700, #f59e0b);
        }

        .popup-header i {
            font-size: 1.5rem;
            color: white;
            margin-bottom: 5px;
        }

        .popup-header h3 {
            color: white;
            font-size: 1rem;
            font-weight: 600;
        }

        .popup-header p {
            color: rgba(255,255,255,0.9);
            font-size: 0.65rem;
        }

        .popup-body {
            padding: 12px 15px;
        }

        .payment-amount-box {
            background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
            padding: 8px 12px;
            border-radius: 8px;
            text-align: center;
            margin-bottom: 10px;
        }

        .payment-amount-box .label {
            font-size: 0.65rem;
            color: #2e7d32;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .payment-amount-box .amount {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2c5f2d;
        }

        .thank-you-box {
            background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
            padding: 10px;
            border-radius: 8px;
            text-align: center;
            margin-bottom: 10px;
        }

        .thank-you-box i {
            font-size: 1.5rem;
            color: #28a745;
            margin-bottom: 5px;
        }

        .thank-you-box h4 {
            color: #2e7d32;
            font-size: 0.85rem;
            margin-bottom: 3px;
        }

        .popup-message p {
            color: #555;
            line-height: 1.4;
            font-size: 0.75rem;
            margin-bottom: 8px;
        }

        .payment-steps {
            background: #f8f9fa;
            padding: 8px 10px;
            border-radius: 6px;
            margin: 10px 0;
        }

        .payment-steps h4 {
            color: #2c5f2d;
            margin-bottom: 5px;
            font-size: 0.7rem;
        }

        .payment-steps ul {
            list-style: none;
            padding-left: 0;
        }

        .payment-steps li {
            padding: 3px 0;
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.65rem;
            color: #555;
        }

        .payment-steps li i {
            color: #2c5f2d;
            width: 16px;
            font-size: 0.65rem;
        }

        .popup-buttons {
            display: flex;
            gap: 8px;
            margin-top: 10px;
        }

        .popup-btn {
            flex: 1;
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 0.7rem;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }

        .popup-btn-primary {
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            color: white;
        }

        .popup-btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(44,95,45,0.3);
        }

        .popup-btn-secondary {
            background: #f0f0f0;
            color: #666;
        }

        .popup-btn-secondary:hover {
            background: #e0e0e0;
        }

        .close-popup {
            position: absolute;
            top: 8px;
            right: 12px;
            color: white;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s;
        }

        .close-popup:hover {
            opacity: 0.8;
            transform: scale(1.1);
        }

        /* ========== KYC AUDIO REMINDER BAR ========== */
        .kyc-audio-reminder {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: linear-gradient(135deg, #ff9800, #f57c00);
            border-radius: 50px;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
            z-index: 10000;
            animation: bounceIn 0.5s ease;
            cursor: pointer;
            transition: all 0.3s;
        }

        .kyc-audio-reminder:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 25px rgba(0,0,0,0.3);
        }

        @keyframes bounceIn {
            0% {
                opacity: 0;
                transform: scale(0.3);
            }
            50% {
                opacity: 1;
                transform: scale(1.05);
            }
            70% {
                transform: scale(0.9);
            }
            100% {
                transform: scale(1);
            }
        }

        .audio-icon {
            width: 40px;
            height: 40px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: pulse 1.5s infinite;
        }

        .audio-icon i {
            font-size: 1.2rem;
            color: #ff9800;
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(255,255,255,0.7);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(255,255,255,0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(255,255,255,0);
            }
        }

        .audio-text {
            color: white;
            font-weight: 600;
            font-size: 0.85rem;
        }

        .audio-text small {
            font-size: 0.65rem;
            opacity: 0.9;
            display: block;
        }

        .stop-audio-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }

        .stop-audio-btn:hover {
            background: rgba(255,255,255,0.4);
            transform: scale(1.1);
        }

        /* Celebration Toast */
        .celebration-toast {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: linear-gradient(135deg, #ffd700, #f59e0b);
            color: #333;
            padding: 20px 30px;
            border-radius: 60px;
            font-weight: bold;
            font-size: 1rem;
            z-index: 10001;
            animation: celebrationBounce 0.5s ease-out;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            display: flex;
            align-items: center;
            gap: 15px;
            white-space: nowrap;
        }

        @keyframes celebrationBounce {
            0% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0.3);
            }
            50% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1.1);
            }
            100% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
        }

        .celebration-toast i {
            font-size: 1.8rem;
            animation: rotate 1s ease;
        }

        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* Hidden Audio Element */
        #kycAudio, #sheldangAudio {
            display: none;
        }

        @media (max-width: 768px) {
            .dashboard-header {
                flex-direction: column;
                text-align: center;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .actions-grid {
                grid-template-columns: 1fr;
            }

            .donation-item {
                flex-direction: column;
                text-align: center;
                gap: 10px;
            }

            .donation-info {
                flex-direction: column;
            }

            .donor-list {
                grid-template-columns: 1fr;
            }

            .distribution-table th,
            .distribution-table td {
                padding: 10px;
                font-size: 0.85rem;
            }

            .popup-buttons {
                flex-direction: column;
            }
            
            .header-actions {
                justify-content: center;
            }

            .kyc-audio-reminder {
                bottom: 10px;
                right: 10px;
                padding: 8px 15px;
            }

            .audio-icon {
                width: 35px;
                height: 35px;
            }

            .audio-text {
                font-size: 0.7rem;
            }

            .celebration-toast {
                padding: 12px 20px;
                font-size: 0.8rem;
                white-space: normal;
                text-align: center;
                width: 80%;
            }
        }

        @media (max-width: 480px) {
            .dashboard-container {
                padding: 15px;
            }

            .section-title {
                font-size: 1.2rem;
            }

            .stat-card h3 {
                font-size: 1.5rem;
            }
            
            .profile-btn, .logout-btn {
                padding: 8px 15px;
                font-size: 0.85rem;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <!-- Header -->
        <div class="dashboard-header">
            <div class="header-title">
                <h1><i class="fas fa-tachometer-alt"></i> Welcome, <?= htmlspecialchars($user['name']) ?>!</h1>
                <p>Member since <?= date('F j, Y', strtotime($user['created_at'])) ?></p>
            </div>
            <div class="header-actions">
                <a href="profile.php" class="profile-btn">
                    <i class="fas fa-user-circle"></i> My Profile
                </a>
                <a href="view_id_card.php" class="profile-btn" style="background: linear-gradient(135deg, #2c5f2d, #1a3a1a);">
                    <i class="fas fa-id-card"></i> My ID Card
                </a>
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-info">
                    <h3>₹<?= number_format($total_crowd_fund, 2) ?></h3>
                    <p>Total Crowd Fund Collected</p>
                    <span class="stat-badge badge-info">
                        <i class="fas fa-users"></i> From <?= $total_donors ?> Donors
                    </span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-donate"></i>
                </div>
                <div class="stat-info">
                    <h3>₹<?= number_format($total_donation, 2) ?></h3>
                    <p>Your Total Donation</p>
                    <?php if($donation_count > 0): ?>
                        <span class="stat-badge badge-approved">
                            <i class="fas fa-check-circle"></i> <?= $donation_count ?> Donations
                        </span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-pie"></i>
                </div>
                <div class="stat-info">
                    <h3>₹<?= number_format($total_distributed, 2) ?></h3>
                    <p>Total Distributed</p>
                    <span class="stat-badge badge-info">
                        <i class="fas fa-cow"></i> For Cow Welfare
                    </span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-id-card"></i>
                </div>
                <div class="stat-info">
                    <h3><?= ucfirst($user['kyc_status']) ?></h3>
                    <p>KYC Status</p>
                    <?php if($user['kyc_status'] == 'approved'): ?>
                        <span class="stat-badge badge-approved">
                            <i class="fas fa-check-circle"></i> Verified
                        </span>
                    <?php elseif($user['kyc_status'] == 'pending'): ?>
                        <span class="stat-badge badge-pending">
                            <i class="fas fa-clock"></i> Under Review
                        </span>
                    <?php elseif($user['kyc_status'] == 'rejected'): ?>
                        <span class="stat-badge badge-pending" style="background: #f8d7da20; color: #721c24;">
                            <i class="fas fa-times-circle"></i> Rejected
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Fund Progress Section -->
        <div class="actions-section">
            <h2 class="section-title">
                <i class="fas fa-chart-line"></i>
                Crowd Fund Progress
            </h2>
            <?php 
            $fund_goal = 5000000;
            $progress_percentage = min(100, ($total_crowd_fund / $fund_goal) * 100);
            ?>
            <div class="fund-progress">
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <span><strong>₹<?= number_format($total_crowd_fund, 2) ?></strong> Raised</span>
                    <span><strong>₹<?= number_format($fund_goal, 2) ?></strong> Goal</span>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar" style="width: <?= $progress_percentage ?>%;"></div>
                </div>
                <div class="progress-stats">
                    <span><i class="fas fa-percent"></i> <?= round($progress_percentage, 1) ?>% Complete</span>
                    <span><i class="fas fa-rupee-sign"></i> Need ₹<?= number_format(max(0, $fund_goal - $total_crowd_fund), 2) ?> more</span>
                </div>
            </div>
        </div>

        <!-- Alerts -->
        <?php if($kyc_rejected): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <div>
                <strong>KYC Rejected!</strong> Please submit valid documents.
                <a href="submit_kyc.php" style="color: #e67e22; margin-left: 10px;">Submit Again →</a>
            </div>
        </div>
        <?php endif; ?>

        <?php if($pending_cancellation): ?>
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i>
            <div>
                <strong>Membership Cancellation Requested!</strong> Under review by admin.
            </div>
        </div>
        <?php endif; ?>

        <!-- Quick Actions -->
        <div class="actions-section">
            <h2 class="section-title">
                <i class="fas fa-bolt"></i>
                Quick Actions
            </h2>
            <div class="actions-grid">
                <a href="submit_kyc.php" class="action-card">
                    <div class="action-icon">
                        <i class="fas fa-id-card"></i>
                    </div>
                    <h3>Submit KYC</h3>
                    <p>Complete verification</p>
                </a>

                <a href="upload_payment.php" class="action-card">
                    <div class="action-icon">
                        <i class="fas fa-upload"></i>
                    </div>
                    <h3>Upload Payment</h3>
                    <p>Make a donation</p>
                </a>

                <a href="view_id_card.php" class="action-card">
                    <div class="action-icon">
                        <i class="fas fa-qrcode"></i>
                    </div>
                    <h3>View ID Card</h3>
                    <p>Download member ID</p>
                </a>

                <a href="profile.php" class="action-card">
                    <div class="action-icon">
                        <i class="fas fa-user-circle"></i>
                    </div>
                    <h3>My Profile</h3>
                    <p>View & edit profile</p>
                </a>

                <a href="cancel_membership.php" class="action-card">
                    <div class="action-icon">
                        <i class="fas fa-times-circle"></i>
                    </div>
                    <h3>Cancel Membership</h3>
                    <p>Request cancellation</p>
                </a>
            </div>
        </div>

        <!-- Top Donors Section -->
        <?php if($top_donors && $top_donors->num_rows > 0): ?>
        <div class="top-donors-section">
            <h2 class="section-title">
                <i class="fas fa-trophy"></i>
                Top Contributors
            </h2>
            <div class="donor-list">
                <?php 
                $rank = 1;
                while($donor = $top_donors->fetch_assoc()): 
                    $rankClass = '';
                    if($rank == 1) $rankClass = 'gold';
                    elseif($rank == 2) $rankClass = 'silver';
                    elseif($rank == 3) $rankClass = 'bronze';
                ?>
                <div class="donor-item">
                    <div class="donor-rank <?= $rankClass ?>">
                        #<?= $rank ?>
                    </div>
                    <div class="donor-info">
                        <div class="donor-name"><?= htmlspecialchars($donor['name']) ?></div>
                        <div class="donor-amount">₹<?= number_format($donor['total'], 2) ?></div>
                    </div>
                    <?php if($rank <= 3): ?>
                    <div class="donor-crown">
                        <?php if($rank == 1): ?>👑<?php elseif($rank == 2): ?>⭐<?php else: ?>🎖️<?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php 
                    $rank++;
                endwhile; 
                ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Recent Donations -->
        <?php if($recent_donations && $recent_donations->num_rows > 0): ?>
        <div class="recent-section">
            <h2 class="section-title">
                <i class="fas fa-history"></i>
                Your Recent Donations
            </h2>
            <?php while($donation = $recent_donations->fetch_assoc()): ?>
            <div class="donation-item">
                <div class="donation-info">
                    <div class="donation-icon">
                        <i class="fas fa-hand-holding-heart"></i>
                    </div>
                    <div class="donation-details">
                        <h4>Donation #<?= $donation['id'] ?></h4>
                        <p><?= date('F j, Y, g:i a', strtotime($donation['uploaded_at'])) ?></p>
                    </div>
                </div>
                <div class="donation-amount">
                    ₹<?= number_format($donation['amount'], 2) ?>
                </div>
                <div class="donation-status">
                    <i class="fas fa-check-circle"></i> Verified
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php endif; ?>

        <!-- Fund Distribution Details -->
        <div class="distribution-section">
            <h2 class="section-title">
                <i class="fas fa-chart-line"></i>
                Fund Distribution Details
            </h2>
            <?php if($distributions && $distributions->num_rows > 0): ?>
            <table class="distribution-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Amount</th>
                        <th>Distributed To</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($row = $distributions->fetch_assoc()): ?>
                    <tr>
                        <td><?= date('d M Y', strtotime($row['date'])) ?></td>
                        <td><?= htmlspecialchars($row['description']) ?></td>
                        <td class="amount-cell">₹<?= number_format($row['amount'], 2) ?></td>
                        <td><?= htmlspecialchars($row['distributed_to']) ?></td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-chart-bar"></i>
                <p>No fund distributions recorded yet.</p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ============================================= -->
    <!-- KYC CELEBRATION AUDIO (sheldang.mp3) -->
    <!-- Plays when KYC is completed successfully -->
    <!-- ============================================= -->
    <?php if($show_kyc_completion): ?>
    <audio id="sheldangAudio" autoplay>
        <source src="https://bmyouth.org/sheldang/assets/audio/sheldang.mp3" type="audio/mpeg">
        <source src="https://bmyouth.org/sheldang/assets/audio/sheldang.ogg" type="audio/ogg">
        <!-- Fallback: Web Speech API if audio file not available -->
    </audio>

    <!-- Celebration Popup for KYC Completion -->
    <div id="celebrationPopup" class="popup-overlay" style="display: flex;">
        <div class="popup-container">
            <div class="popup-header celebration-header">
                <span class="close-popup" onclick="closeCelebrationPopup()">&times;</span>
                <i class="fas fa-trophy"></i>
                <h3>🎉 Congratulations! 🎉</h3>
                <p>KYC Verified Successfully</p>
            </div>
            <div class="popup-body">
                <div class="thank-you-box" style="background: linear-gradient(135deg, #fff3cd, #ffe4b5);">
                    <i class="fas fa-check-circle" style="color: #f59e0b; font-size: 2rem;"></i>
                    <h4 style="color: #d4a017;">धन्यवाद!</h4>
                    <div style="font-size: 0.8rem; font-weight: 600; margin: 8px 0;">अपना KYC पूरा करने के लिए धन्यवाद!</div>
                    <div style="font-size: 0.7rem; color: #333;">अब आप हमारे उद्देश्य शेल्डंग में आर्थिक सहयोग कर सकते हैं।</div>
                </div>
                <div class="popup-message" style="text-align: center;">
                    <p style="font-size: 0.8rem; color: #2c5f2d;">✨ You are now eligible to support our Sheldang mission! ✨</p>
                </div>
                <div class="popup-buttons">
                    <a href="upload_payment.php" class="popup-btn popup-btn-primary">
                        <i class="fas fa-hand-holding-heart"></i> Donate Now
                    </a>
                    <button class="popup-btn popup-btn-secondary" onclick="closeCelebrationPopup()">
                        <i class="fas fa-times"></i> Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Celebration Toast Message -->
    <div id="celebrationToast" class="celebration-toast">
        <i class="fas fa-party-horn"></i>
        <span>🎊 KYC Completed! Now you can donate to Sheldang 🎊</span>
    </div>

    <script>
        // Play sheldang.mp3 when page loads
        const sheldangAudio = document.getElementById('sheldangAudio');
        
        function playSheldangAudio() {
            if (sheldangAudio) {
                sheldangAudio.volume = 0.8;
                const playPromise = sheldangAudio.play();
                if (playPromise !== undefined) {
                    playPromise.catch(error => {
                        console.log("Audio playback failed, using speech synthesis fallback");
                        useSheldangSpeechFallback();
                    });
                }
            } else {
                useSheldangSpeechFallback();
            }
        }
        
        function useSheldangSpeechFallback() {
            if ('speechSynthesis' in window) {
                window.speechSynthesis.cancel();
                const utterance = new SpeechSynthesisUtterance("अपना केवैसी पूरा करने के लिए धन्यवाद! अब आप हमारे उद्देश्य शेल्डंग में आर्थिक सहयोग कर सकते हैं।");
                utterance.lang = "hi-IN";
                utterance.rate = 0.9;
                utterance.pitch = 1;
                window.speechSynthesis.speak(utterance);
            }
        }
        
        function closeCelebrationPopup() {
            const popup = document.getElementById('celebrationPopup');
            const toast = document.getElementById('celebrationToast');
            if(popup) popup.style.display = 'none';
            if(toast) {
                toast.style.opacity = '0';
                setTimeout(() => toast.remove(), 500);
            }
            // Stop audio when closing
            if (sheldangAudio) {
                sheldangAudio.pause();
                sheldangAudio.currentTime = 0;
            }
        }
        
        // Auto-close toast after 5 seconds
        setTimeout(() => {
            const toast = document.getElementById('celebrationToast');
            if(toast) {
                toast.style.opacity = '0';
                setTimeout(() => toast.remove(), 500);
            }
        }, 5000);
        
        // Play audio when page loads
        document.addEventListener('DOMContentLoaded', function() {
            playSheldangAudio();
        });
    </script>
    <?php endif; ?>

    <!-- ============================================= -->
    <!-- KYC AUDIO REMINDER - Plays until KYC is completed -->
    <!-- ============================================= -->
    <?php if($show_kyc_audio): ?>
    <audio id="kycAudio" loop autoplay>
        <source src="https://bmyouth.org/sheldang/assets/audio/kyc-reminder.mp3" type="audio/mpeg">
        <source src="https://bmyouth.org/sheldang/assets/audio/kyc-reminder.ogg" type="audio/ogg">
    </audio>
    
    <div id="kycAudioReminder" class="kyc-audio-reminder" onclick="document.getElementById('kycAudio').play()">
        <div class="audio-icon">
            <i class="fas fa-volume-up"></i>
        </div>
        <div class="audio-text">
            🔔 KYC Reminder
            <small>कृपया KYC Complete करे</small>
        </div>
        <button class="stop-audio-btn" onclick="stopAudio(event)">
            <i class="fas fa-stop"></i>
        </button>
    </div>
    
    <script>
        let kycAudio = null;
        let speechUtterance = null;
        let audioInterval = null;
        let isAudioPlaying = true;
        
        function playKycReminder() {
            const audioElement = document.getElementById('kycAudio');
            if (audioElement && audioElement.canPlayType) {
                audioElement.volume = 0.7;
                const playPromise = audioElement.play();
                if (playPromise !== undefined) {
                    playPromise.catch(error => {
                        console.log("Audio playback failed, using speech synthesis fallback");
                        useSpeechSynthesis();
                    });
                }
            } else {
                useSpeechSynthesis();
            }
        }
        
        function useSpeechSynthesis() {
            if (window.speechSynthesis) {
                window.speechSynthesis.cancel();
                speechUtterance = new SpeechSynthesisUtterance("कृपया KYC Complete करे");
                speechUtterance.lang = "hi-IN";
                speechUtterance.rate = 0.9;
                speechUtterance.pitch = 1;
                
                audioInterval = setInterval(function() {
                    if (isAudioPlaying && document.getElementById('kycAudioReminder')) {
                        window.speechSynthesis.cancel();
                        speechUtterance = new SpeechSynthesisUtterance("कृपया KYC Complete करे");
                        speechUtterance.lang = "hi-IN";
                        speechUtterance.rate = 0.9;
                        window.speechSynthesis.speak(speechUtterance);
                    }
                }, 5000);
                window.speechSynthesis.speak(speechUtterance);
            }
        }
        
        function stopAudio(event) {
            if (event) event.stopPropagation();
            isAudioPlaying = false;
            const audioElement = document.getElementById('kycAudio');
            if (audioElement) {
                audioElement.pause();
                audioElement.currentTime = 0;
            }
            if (window.speechSynthesis) window.speechSynthesis.cancel();
            if (audioInterval) clearInterval(audioInterval);
            const reminderBar = document.getElementById('kycAudioReminder');
            if (reminderBar) reminderBar.style.display = 'none';
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            playKycReminder();
        });
        
        document.body.addEventListener('click', function() {
            if (isAudioPlaying) {
                const audioElement = document.getElementById('kycAudio');
                if (audioElement && audioElement.paused) {
                    audioElement.play().catch(e => console.log("Playback still blocked"));
                }
            }
        });
    </script>
    <?php endif; ?>

    <!-- KYC Popup Modal (for Pending KYC) - Shows on Every Page Load -->
    <?php if($show_kyc_popup && $pending_kyc): ?>
    <div id="kycPopup" class="popup-overlay" style="display: flex;">
        <div class="popup-container">
            <div class="popup-header kyc-header">
                <span class="close-popup" onclick="closeKycPopup()">&times;</span>
                <i class="fas fa-id-card"></i>
                <h3>KYC Required!</h3>
                <p>Complete to access all features</p>
            </div>
            <div class="popup-body">
                <div class="popup-message">
                    <p>Dear <strong><?= htmlspecialchars($user['name']) ?></strong>,</p>
                    <p>Your KYC is pending. Please complete verification.</p>
                    <div style="background:#fff3cd; padding:6px 8px; border-radius:6px; margin:8px 0; font-size:0.7rem;">
                        <i class="fas fa-exclamation-triangle" style="color:#856404;"></i> Without KYC, you are not eligible.
                    </div>
                </div>
                <div class="popup-buttons">
                    <button class="popup-btn popup-btn-secondary" onclick="closeKycPopup()">Later</button>
                    <a href="submit_kyc.php" class="popup-btn popup-btn-primary">Submit KYC</a>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Smart Payment Reminder Popup (for KYC Approved Users) -->
    <?php if($show_payment_popup && $kyc_approved && !$show_kyc_completion): ?>
    <div id="paymentPopup" class="popup-overlay" style="display: flex;">
        <div class="popup-container">
            <div class="popup-header payment-header">
                <span class="close-popup" onclick="closePaymentPopup()">&times;</span>
                <i class="fas fa-hand-holding-heart"></i>
                <h3>Support Our Cause 🙏</h3>
                <p>Every contribution matters</p>
            </div>
            <div class="popup-body">
                <?php if($total_donation > 0): ?>
                <div class="thank-you-box">
                    <i class="fas fa-check-circle"></i>
                    <h4>Thank You for Your Support!</h4>
                    <div class="payment-amount-box" style="margin-top: 5px;">
                        <div class="label">Your Total Contribution</div>
                        <div class="amount">₹<?= number_format($total_donation, 2) ?></div>
                        <div style="font-size: 0.6rem; margin-top: 3px;"><?= $donation_count ?> donation(s)</div>
                    </div>
                    <p style="font-size: 0.65rem; margin-top: 6px;">Your generosity helps us provide support and continue serving the community.</p>
                </div>
                <div class="popup-message">
                    <p>Would you like to make another contribution? Every rupee counts!</p>
                </div>
                <?php else: ?>
                <div class="popup-message">
                    <p>Dear <strong><?= htmlspecialchars($user['name']) ?></strong>,</p>
                    <p>Thank you for completing your KYC! Now you can support our cause.</p>
                </div>
                <?php endif; ?>
                
                <div class="payment-steps">
                    <h4><i class="fas fa-heart"></i> How to Contribute:</h4>
                    <ul>
                        <li><i class="fas fa-qrcode"></i> Scan QR or use UPI</li>
                        <li><i class="fas fa-rupee-sign"></i> Enter donation amount</li>
                        <li><i class="fas fa-upload"></i> Upload payment screenshot</li>
                        <li><i class="fas fa-check-circle"></i> Gets verified in 24-48 hrs</li>
                    </ul>
                </div>
                
                <div class="popup-buttons">
                    <button class="popup-btn popup-btn-secondary" onclick="closePaymentPopup()">Remind Later</button>
                    <a href="upload_payment.php" class="popup-btn popup-btn-primary">
                        <i class="fas fa-donate"></i> Donate Now
                    </a>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script>
        // Close KYC Popup
        function closeKycPopup() {
            const popup = document.getElementById('kycPopup');
            if(popup) popup.style.display = 'none';
        }
        
        // Close Payment Popup
        function closePaymentPopup() {
            const popup = document.getElementById('paymentPopup');
            if(popup) popup.style.display = 'none';
        }
        
        // Close popup when clicking outside
        window.onclick = function(event) {
            const kycPopup = document.getElementById('kycPopup');
            const paymentPopup = document.getElementById('paymentPopup');
            const celebrationPopup = document.getElementById('celebrationPopup');
            if(event.target === kycPopup) closeKycPopup();
            if(event.target === paymentPopup) closePaymentPopup();
            if(event.target === celebrationPopup) closeCelebrationPopup();
        }
        
        // Auto-show popups when page loads
        document.addEventListener('DOMContentLoaded', function() {
            const kycPopup = document.getElementById('kycPopup');
            const paymentPopup = document.getElementById('paymentPopup');
            
            if(kycPopup) setTimeout(() => kycPopup.style.display = 'flex', 500);
            if(paymentPopup) setTimeout(() => paymentPopup.style.display = 'flex', 800);
        });
        
        // Stop audio when page unloads
        window.addEventListener('beforeunload', function() {
            const kycAudioElement = document.getElementById('kycAudio');
            const sheldangAudioElement = document.getElementById('sheldangAudio');
            if (kycAudioElement) { kycAudioElement.pause(); kycAudioElement.currentTime = 0; }
            if (sheldangAudioElement) { sheldangAudioElement.pause(); sheldangAudioElement.currentTime = 0; }
            if (window.speechSynthesis) window.speechSynthesis.cancel();
            if (audioInterval) clearInterval(audioInterval);
        });
        
        window.addEventListener('popstate', function() {
            const kycAudioElement = document.getElementById('kycAudio');
            if (kycAudioElement) kycAudioElement.pause();
            if (window.speechSynthesis) window.speechSynthesis.cancel();
        });
    </script>
</body>
</html>