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

// =============================================
// NEW FUNCTION: Manual KYC Upload by Admin
// This function allows admin to upload KYC documents for users
// =============================================

// Handle manual KYC upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['manual_kyc_submit'])) {
    $user_id = intval($_POST['user_id']);
    $kyc_status = 'pending';
    $upload_dir = "../assets/uploads/kyc/";
    
    // Create directory if not exists
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    if (isset($_FILES['kyc_document']) && $_FILES['kyc_document']['error'] == 0) {
        $file = $_FILES['kyc_document'];
        $file_name = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', basename($file['name']));
        $target_file = $upload_dir . $file_name;
        $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
        
        if (in_array($file_type, $allowed_types)) {
            if (move_uploaded_file($file['tmp_name'], $target_file)) {
                $db_path = "assets/uploads/kyc/" . $file_name;
                
                // Update user's KYC document
                $update_query = "UPDATE users SET kyc_doc = '$db_path', kyc_status = '$kyc_status' WHERE id = $user_id";
                if ($conn->query($update_query)) {
                    $_SESSION['success_msg'] = "KYC document uploaded successfully for user ID: $user_id";
                } else {
                    $_SESSION['error_msg'] = "Database error: " . $conn->error;
                }
            } else {
                $_SESSION['error_msg'] = "Failed to upload file. Please check directory permissions.";
            }
        } else {
            $_SESSION['error_msg'] = "Invalid file type. Allowed: JPG, PNG, GIF, WEBP, PDF";
        }
    } else {
        $_SESSION['error_msg'] = "Please select a file to upload.";
    }
    
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

// Handle manual KYC approval/rejection
if (isset($_GET['approve_kyc_manual']) && is_numeric($_GET['approve_kyc_manual'])) {
    $user_id = intval($_GET['approve_kyc_manual']);
    $update_query = "UPDATE users SET kyc_status = 'approved' WHERE id = $user_id";
    if ($conn->query($update_query)) {
        $_SESSION['success_msg'] = "KYC approved successfully for user ID: $user_id";
    } else {
        $_SESSION['error_msg'] = "Failed to approve KYC";
    }
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

if (isset($_GET['reject_kyc_manual']) && is_numeric($_GET['reject_kyc_manual'])) {
    $user_id = intval($_GET['reject_kyc_manual']);
    $update_query = "UPDATE users SET kyc_status = 'rejected' WHERE id = $user_id";
    if ($conn->query($update_query)) {
        $_SESSION['success_msg'] = "KYC rejected for user ID: $user_id";
    } else {
        $_SESSION['error_msg'] = "Failed to reject KYC";
    }
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

// Handle delete KYC document
if (isset($_GET['delete_kyc']) && is_numeric($_GET['delete_kyc'])) {
    $user_id = intval($_GET['delete_kyc']);
    
    // Get file path
    $file_query = "SELECT kyc_doc FROM users WHERE id = $user_id";
    $file_result = $conn->query($file_query);
    if ($file_result && $file_result->num_rows > 0) {
        $file_row = $file_result->fetch_assoc();
        $file_path = $file_row['kyc_doc'];
        
        // Delete physical file
        if (!empty($file_path)) {
            $paths_to_check = [$file_path, "../" . $file_path, "../assets/uploads/kyc/" . basename($file_path)];
            foreach ($paths_to_check as $path) {
                if (file_exists($path)) {
                    unlink($path);
                    break;
                }
            }
        }
        
        // Update database
        $update_query = "UPDATE users SET kyc_doc = NULL, kyc_status = 'pending' WHERE id = $user_id";
        if ($conn->query($update_query)) {
            $_SESSION['success_msg'] = "KYC document deleted successfully for user ID: $user_id";
        } else {
            $_SESSION['error_msg'] = "Failed to delete KYC document";
        }
    }
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

// =============================================
// NEW FUNCTION: Auto delete rejected payment proofs
// =============================================

// Handle auto delete rejected payment proofs
if (isset($_GET['delete_rejected_payments'])) {
    $rejected_query = "SELECT id, payment_proof FROM donations WHERE status = 'rejected' AND payment_proof IS NOT NULL AND payment_proof != ''";
    $rejected_result = $conn->query($rejected_query);
    
    $deleted_count = 0;
    $deleted_files = 0;
    
    if ($rejected_result && $rejected_result->num_rows > 0) {
        while ($row = $rejected_result->fetch_assoc()) {
            $payment_id = $row['id'];
            $file_path = $row['payment_proof'];
            
            if (!empty($file_path)) {
                $paths_to_check = [$file_path, "../" . $file_path, "../assets/uploads/payment_proof/" . basename($file_path)];
                foreach ($paths_to_check as $path) {
                    if (file_exists($path)) {
                        if (unlink($path)) {
                            $deleted_files++;
                        }
                        break;
                    }
                }
            }
            
            $delete_query = "DELETE FROM donations WHERE id = $payment_id";
            if ($conn->query($delete_query)) {
                $deleted_count++;
            }
        }
    }
    
    if ($deleted_count > 0) {
        $_SESSION['success_msg'] = "Successfully deleted $deleted_count rejected payment proof(s) and $deleted_files file(s) from server!";
    } else {
        $_SESSION['info_msg'] = "No rejected payment proofs found to delete.";
    }
    
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

// Handle single delete payment proof
if (isset($_GET['delete_payment']) && is_numeric($_GET['delete_payment'])) {
    $payment_id = intval($_GET['delete_payment']);
    
    $file_query = "SELECT payment_proof FROM donations WHERE id = $payment_id";
    $file_result = $conn->query($file_query);
    if ($file_result && $file_result->num_rows > 0) {
        $file_row = $file_result->fetch_assoc();
        $file_path = $file_row['payment_proof'];
        
        if (!empty($file_path)) {
            $paths_to_check = [$file_path, "../" . $file_path, "../assets/uploads/payment_proof/" . basename($file_path)];
            foreach ($paths_to_check as $path) {
                if (file_exists($path)) {
                    unlink($path);
                    break;
                }
            }
        }
        
        $delete_query = "DELETE FROM donations WHERE id = $payment_id";
        if ($conn->query($delete_query)) {
            $_SESSION['success_msg'] = "Payment proof deleted successfully!";
        } else {
            $_SESSION['error_msg'] = "Failed to delete payment proof!";
        }
    }
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit();
}

// Get filter parameters
$type = isset($_GET['type']) ? $_GET['type'] : 'all';
$search = isset($_GET['search']) ? $_GET['search'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$date_filter = isset($_GET['date_filter']) ? $_GET['date_filter'] : '';
$custom_date = isset($_GET['custom_date']) ? $_GET['custom_date'] : '';

// Get users list for manual KYC dropdown
$users_list = $conn->query("SELECT id, name, email FROM users WHERE kyc_doc IS NULL OR kyc_doc = '' ORDER BY name ASC");

// Build query for KYC documents with date grouping
$kyc_query = "SELECT id, name, email, mobile, kyc_doc, kyc_status, created_at, 'kyc' as doc_type, DATE(created_at) as date_group FROM users WHERE kyc_doc IS NOT NULL AND kyc_doc != ''";

// Build query for payment proofs with date grouping
$payment_query = "SELECT d.id, u.name, u.email, u.mobile, d.amount, d.payment_proof, d.status, d.uploaded_at, 'payment' as doc_type, DATE(d.uploaded_at) as date_group 
                  FROM donations d 
                  JOIN users u ON d.user_id = u.id 
                  WHERE d.payment_proof IS NOT NULL AND d.payment_proof != ''";

// Apply type filters
if ($type == 'kyc') {
    $payment_query = "SELECT * FROM (SELECT NULL as id) as temp WHERE 1=0";
} elseif ($type == 'payment') {
    $kyc_query = "SELECT * FROM (SELECT NULL as id) as temp WHERE 1=0";
}

// Apply date filter
if (!empty($date_filter)) {
    $today = date('Y-m-d');
    $week_ago = date('Y-m-d', strtotime('-7 days'));
    $month_ago = date('Y-m-d', strtotime('-30 days'));
    
    switch($date_filter) {
        case 'today':
            $kyc_query .= " AND DATE(created_at) = '$today'";
            $payment_query .= " AND DATE(uploaded_at) = '$today'";
            break;
        case 'yesterday':
            $yesterday = date('Y-m-d', strtotime('-1 days'));
            $kyc_query .= " AND DATE(created_at) = '$yesterday'";
            $payment_query .= " AND DATE(uploaded_at) = '$yesterday'";
            break;
        case 'week':
            $kyc_query .= " AND DATE(created_at) >= '$week_ago'";
            $payment_query .= " AND DATE(uploaded_at) >= '$week_ago'";
            break;
        case 'month':
            $kyc_query .= " AND DATE(created_at) >= '$month_ago'";
            $payment_query .= " AND DATE(uploaded_at) >= '$month_ago'";
            break;
        case 'custom':
            if (!empty($custom_date)) {
                $kyc_query .= " AND DATE(created_at) = '$custom_date'";
                $payment_query .= " AND DATE(uploaded_at) = '$custom_date'";
            }
            break;
    }
}

// Apply search filter
if (!empty($search)) {
    $search_term = $conn->real_escape_string($search);
    $kyc_query .= " AND (name LIKE '%$search_term%' OR email LIKE '%$search_term%' OR mobile LIKE '%$search_term%')";
    $payment_query .= " AND (u.name LIKE '%$search_term%' OR u.email LIKE '%$search_term%' OR u.mobile LIKE '%$search_term%')";
}

// Apply status filter
if (!empty($status) && $status != 'all') {
    if ($status == 'pending') {
        $kyc_query .= " AND kyc_status = 'pending'";
        $payment_query .= " AND d.status = 'pending'";
    } elseif ($status == 'approved') {
        $kyc_query .= " AND kyc_status = 'approved'";
    } elseif ($status == 'rejected') {
        $kyc_query .= " AND kyc_status = 'rejected'";
    } elseif ($status == 'verified') {
        $payment_query .= " AND d.status = 'verified'";
    } elseif ($status == 'rejected_payment') {
        $payment_query .= " AND d.status = 'rejected'";
    }
}

// Order by date
$kyc_query .= " ORDER BY created_at DESC";
$payment_query .= " ORDER BY uploaded_at DESC";

// Execute queries
$kyc_results = $conn->query($kyc_query);
$payment_results = $conn->query($payment_query);

// Get counts with date filters
$total_kyc = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_doc IS NOT NULL AND kyc_doc != ''")->fetch_assoc()['count'];
$total_payments = $conn->query("SELECT COUNT(*) as count FROM donations WHERE payment_proof IS NOT NULL AND payment_proof != ''")->fetch_assoc()['count'];
$pending_kyc = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_status='pending' AND kyc_doc IS NOT NULL")->fetch_assoc()['count'];
$pending_payments = $conn->query("SELECT COUNT(*) as count FROM donations WHERE status='pending' AND payment_proof IS NOT NULL")->fetch_assoc()['count'];

// Get rejected payments count for the delete button
$rejected_payments_count = $conn->query("SELECT COUNT(*) as count FROM donations WHERE status='rejected' AND payment_proof IS NOT NULL")->fetch_assoc()['count'];

// Get users without KYC for manual upload count
$users_without_kyc_count = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_doc IS NULL OR kyc_doc = ''")->fetch_assoc()['count'];

// Get date-wise statistics
$kyc_by_date = $conn->query("SELECT DATE(created_at) as date, COUNT(*) as count FROM users WHERE kyc_doc IS NOT NULL GROUP BY DATE(created_at) ORDER BY date DESC LIMIT 10");
$payment_by_date = $conn->query("SELECT DATE(uploaded_at) as date, SUM(amount) as total_amount, COUNT(*) as count FROM donations WHERE payment_proof IS NOT NULL GROUP BY DATE(uploaded_at) ORDER BY date DESC LIMIT 10");

function getFilePreview($filePath) {
    if (empty($filePath)) return ['exists' => false, 'url' => '', 'type' => 'none'];
    $paths = [$filePath, "../" . $filePath, "../assets/uploads/payment_proof/" . basename($filePath), "../assets/uploads/kyc/" . 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']);
            $isPdf = $ext == 'pdf';
            return ['exists' => true, 'web_url' => $path, 'type' => $isImage ? 'image' : ($isPdf ? 'pdf' : 'file'), 'ext' => $ext];
        }
    }
    return ['exists' => false];
}

function groupDocumentsByDate($documents) {
    $grouped = [];
    if ($documents && $documents->num_rows > 0) {
        while($row = $documents->fetch_assoc()) {
            $dateKey = date('Y-m-d', strtotime($row['created_at'] ?? $row['uploaded_at'] ?? 'now'));
            if (!isset($grouped[$dateKey])) {
                $grouped[$dateKey] = [];
            }
            $grouped[$dateKey][] = $row;
        }
    }
    return $grouped;
}

// Group documents by date
$kyc_grouped = groupDocumentsByDate($kyc_results);
$payment_grouped = groupDocumentsByDate($payment_results);

// Get sorted date keys
$kyc_dates = array_keys($kyc_grouped);
$payment_dates = array_keys($payment_grouped);
rsort($kyc_dates);
rsort($payment_dates);

// Display success/error/info messages
$success_msg = isset($_SESSION['success_msg']) ? $_SESSION['success_msg'] : '';
$error_msg = isset($_SESSION['error_msg']) ? $_SESSION['error_msg'] : '';
$info_msg = isset($_SESSION['info_msg']) ? $_SESSION['info_msg'] : '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);
unset($_SESSION['info_msg']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Management - Gau Seva Foundation</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: #f0f2f5;
            min-height: 100vh;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 1.5rem;
        }

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

        .header h1 {
            font-size: 1.8rem;
            color: #1a3a1a;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .header h1 i {
            color: #ffd700;
        }

        .back-btn {
            background: #6c757d;
            color: white;
            padding: 0.7rem 1.5rem;
            border-radius: 10px;
            text-decoration: none;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .back-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

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

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

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

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

        .alert i {
            margin-right: 10px;
        }

        .alert-close {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: inherit;
            opacity: 0.7;
        }

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

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

        .stat-card {
            background: white;
            padding: 1.2rem;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: transform 0.3s;
            cursor: pointer;
        }

        .stat-card:hover {
            transform: translateY(-3px);
        }

        .stat-card i {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .stat-card .count {
            font-size: 1.8rem;
            font-weight: 700;
        }

        .stat-card .label {
            font-size: 0.8rem;
            color: #666;
        }

        .stat-card.kyc i { color: #17a2b8; }
        .stat-card.payment i { color: #28a745; }
        .stat-card.pending-kyc i { color: #ffc107; }
        .stat-card.pending-payment i { color: #fd7e14; }

        /* Action Buttons */
        .action-btn {
            background: #2c5f2d;
            color: white;
            padding: 0.5rem 1.2rem;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .action-btn:hover {
            background: #1a3a1a;
            transform: translateY(-2px);
        }

        .delete-all-btn {
            background: #dc3545;
            color: white;
            padding: 0.5rem 1.2rem;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .delete-all-btn:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .delete-all-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }

        /* Manual KYC Form */
        .manual-kyc-form {
            background: white;
            border-radius: 15px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .manual-kyc-form h4 {
            display: flex;
            align-items: center;
            gap: 10px;
            color: #2c5f2d;
        }

        .form-group {
            display: flex;
            align-items: center;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .form-group select, .form-group input {
            padding: 0.5rem 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-family: 'Poppins', sans-serif;
        }

        .form-group select:focus, .form-group input:focus {
            outline: none;
            border-color: #2c5f2d;
        }

        .upload-btn {
            background: #28a745;
            color: white;
            padding: 0.5rem 1.2rem;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
        }

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

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

        .filter-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .filter-group {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .filter-btn {
            padding: 0.5rem 1.2rem;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            background: #f0f2f5;
            color: #333;
        }

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

        .filter-btn:hover:not(.active) {
            background: #e0e0e0;
        }

        .date-filter-group {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
            align-items: center;
        }

        .date-filter-btn {
            padding: 0.4rem 1rem;
            border: 1px solid #ddd;
            border-radius: 20px;
            background: white;
            cursor: pointer;
            font-size: 0.85rem;
            transition: all 0.3s;
        }

        .date-filter-btn.active {
            background: #2c5f2d;
            color: white;
            border-color: #2c5f2d;
        }

        .date-filter-btn:hover:not(.active) {
            background: #f0f2f5;
        }

        .custom-date-input {
            padding: 0.4rem 0.8rem;
            border: 1px solid #ddd;
            border-radius: 20px;
            font-family: 'Poppins', sans-serif;
        }

        .search-box {
            display: flex;
            gap: 0.5rem;
        }

        .search-box input {
            padding: 0.5rem 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-family: 'Poppins', sans-serif;
            width: 250px;
        }

        .search-box input:focus {
            outline: none;
            border-color: #2c5f2d;
        }

        .search-box button {
            padding: 0.5rem 1.2rem;
            background: #2c5f2d;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
        }

        /* Date Section */
        .date-section {
            margin-bottom: 2rem;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .date-section-header {
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            color: white;
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }

        .date-section-header h3 {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .date-section-header .badge {
            background: rgba(255,255,255,0.2);
            padding: 0.2rem 0.6rem;
            border-radius: 20px;
            font-size: 0.8rem;
        }

        .date-section-header .toggle-icon {
            transition: transform 0.3s;
        }

        .date-section-header.collapsed .toggle-icon {
            transform: rotate(-90deg);
        }

        .date-section-content {
            transition: all 0.3s ease;
            overflow: hidden;
        }

        .date-section-content.collapsed {
            display: none;
        }

        /* Document Table */
        .document-table {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            margin-bottom: 1rem;
        }

        .table-wrapper {
            overflow-x: auto;
        }

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

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

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

        tr:hover {
            background: #f9f9f9;
        }

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

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

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

        .doc-icon {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f0f2f5;
            border-radius: 8px;
            font-size: 1.5rem;
        }

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

        .badge-pending { background: #fff3cd; color: #856404; }
        .badge-approved, .badge-verified { background: #d4edda; color: #155724; }
        .badge-rejected { background: #f8d7da; color: #721c24; }

        .btn-sm {
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            border-radius: 5px;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

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

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

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

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #333;
        }

        /* Date Stats Sidebar */
        .stats-sidebar {
            background: white;
            border-radius: 15px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .stats-sidebar h4 {
            margin-bottom: 1rem;
            color: #1a3a1a;
        }

        .date-stats-list {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .date-stat-item {
            flex: 1;
            min-width: 150px;
            padding: 0.8rem;
            background: #f8f9fa;
            border-radius: 10px;
            text-align: center;
        }

        .date-stat-item .date {
            font-weight: 600;
            color: #2c5f2d;
        }

        .date-stat-item .count {
            font-size: 1.2rem;
            font-weight: 700;
        }

        .date-stat-item .amount {
            color: #28a745;
            font-weight: 600;
        }

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

        .modal-content {
            background: white;
            border-radius: 15px;
            max-width: 90%;
            max-height: 90%;
            overflow: auto;
            position: relative;
        }

        .modal-header {
            padding: 1rem;
            background: #2c5f2d;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 15px 15px 0 0;
        }

        .modal-body {
            padding: 1.5rem;
            text-align: center;
        }

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

        .close-modal {
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
        }

        /* Delete Confirmation Modal */
        .confirm-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1100;
        }

        .confirm-modal-content {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            max-width: 400px;
            text-align: center;
        }

        .confirm-modal-content i {
            font-size: 3rem;
            margin-bottom: 1rem;
        }

        .confirm-modal-content .warning-icon {
            color: #dc3545;
        }

        .confirm-modal-content .info-icon {
            color: #ffc107;
        }

        .confirm-modal-content h3 {
            margin-bottom: 0.5rem;
        }

        .confirm-modal-content p {
            color: #666;
            margin-bottom: 1.5rem;
        }

        .confirm-buttons {
            display: flex;
            gap: 1rem;
            justify-content: center;
        }

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

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }

            .filter-row {
                flex-direction: column;
                align-items: stretch;
            }

            .filter-group, .date-filter-group {
                justify-content: center;
            }

            .search-box {
                justify-content: center;
            }

            th, td {
                padding: 0.75rem;
                font-size: 0.8rem;
            }

            .doc-thumbnail {
                width: 35px;
                height: 35px;
            }
            
            .manual-kyc-form {
                flex-direction: column;
                align-items: stretch;
            }
            
            .form-group {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <div class="header">
        <h1>
            <i class="fas fa-folder-open"></i>
            Document Management
        </h1>
        <a href="dashboard.php" class="back-btn">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>

    <!-- Alert Messages -->
    <?php if($success_msg): ?>
    <div class="alert alert-success">
        <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_msg) ?>
        <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
    </div>
    <?php endif; ?>
    
    <?php if($error_msg): ?>
    <div class="alert alert-danger">
        <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_msg) ?>
        <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
    </div>
    <?php endif; ?>

    <?php if($info_msg): ?>
    <div class="alert alert-info">
        <i class="fas fa-info-circle"></i> <?= htmlspecialchars($info_msg) ?>
        <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
    </div>
    <?php endif; ?>

    <!-- NEW: Manual KYC Upload Form -->
    <div class="manual-kyc-form">
        <h4><i class="fas fa-upload"></i> Manual KYC Upload</h4>
        <form method="POST" enctype="multipart/form-data" class="form-group" onsubmit="return validateKYCForm()">
            <select name="user_id" id="user_id" required>
                <option value="">-- Select User --</option>
                <?php while($user = $users_list->fetch_assoc()): ?>
                <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['name']) ?> (<?= htmlspecialchars($user['email']) ?>)</option>
                <?php endwhile; ?>
            </select>
            <input type="file" name="kyc_document" id="kyc_document" accept=".jpg,.jpeg,.png,.gif,.webp,.pdf" required>
            <button type="submit" name="manual_kyc_submit" class="upload-btn"><i class="fas fa-cloud-upload-alt"></i> Upload KYC</button>
        </form>
        <?php if($users_without_kyc_count > 0): ?>
        <small style="color: #666;"><i class="fas fa-info-circle"></i> <?= $users_without_kyc_count ?> user(s) don't have KYC documents uploaded.</small>
        <?php endif; ?>
    </div>

    <!-- Stats Cards -->
    <div class="stats-grid">
        <div class="stat-card kyc" onclick="filterByType('kyc')">
            <i class="fas fa-id-card"></i>
            <div class="count"><?= $total_kyc ?></div>
            <div class="label">Total KYC Documents</div>
        </div>
        <div class="stat-card payment" onclick="filterByType('payment')">
            <i class="fas fa-receipt"></i>
            <div class="count"><?= $total_payments ?></div>
            <div class="label">Total Payment Proofs</div>
        </div>
        <div class="stat-card pending-kyc" onclick="filterByStatus('pending', 'kyc')">
            <i class="fas fa-clock"></i>
            <div class="count"><?= $pending_kyc ?></div>
            <div class="label">Pending KYC</div>
        </div>
        <div class="stat-card pending-payment" onclick="filterByStatus('pending', 'payment')">
            <i class="fas fa-hourglass-half"></i>
            <div class="count"><?= $pending_payments ?></div>
            <div class="label">Pending Payments</div>
        </div>
    </div>

    <!-- Date-wise Statistics -->
    <div class="stats-sidebar">
        <h4><i class="fas fa-chart-line"></i> Recent Activity</h4>
        <div class="date-stats-list">
            <div class="date-stat-item">
                <div class="date">Last 7 Days</div>
                <div class="count">
                    <?php 
                        $week_kyc = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_doc IS NOT NULL AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetch_assoc()['count'];
                        $week_payment = $conn->query("SELECT COUNT(*) as count FROM donations WHERE payment_proof IS NOT NULL AND uploaded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetch_assoc()['count'];
                        echo $week_kyc + $week_payment;
                    ?>
                </div>
                <div class="label">Total Documents</div>
            </div>
            <div class="date-stat-item">
                <div class="date">This Month</div>
                <div class="count">
                    <?php 
                        $month_kyc = $conn->query("SELECT COUNT(*) as count FROM users WHERE kyc_doc IS NOT NULL AND MONTH(created_at) = MONTH(NOW()) AND YEAR(created_at) = YEAR(NOW())")->fetch_assoc()['count'];
                        $month_payment = $conn->query("SELECT COUNT(*) as count FROM donations WHERE payment_proof IS NOT NULL AND MONTH(uploaded_at) = MONTH(NOW()) AND YEAR(uploaded_at) = YEAR(NOW())")->fetch_assoc()['count'];
                        echo $month_kyc + $month_payment;
                    ?>
                </div>
                <div class="label">This Month</div>
            </div>
            <div class="date-stat-item">
                <div class="date">Payment Amount</div>
                <div class="amount">
                    ₹<?php 
                        $total_amount = $conn->query("SELECT SUM(amount) as total FROM donations WHERE payment_proof IS NOT NULL AND status='verified'")->fetch_assoc()['total'];
                        echo number_format($total_amount ?? 0, 2);
                    ?>
                </div>
                <div class="label">Verified Payments</div>
            </div>
        </div>
    </div>

    <!-- Filter Bar -->
    <div class="filter-bar">
        <div class="filter-row">
            <div class="filter-group">
                <button class="filter-btn <?= $type == 'all' ? 'active' : '' ?>" onclick="filterByType('all')">All Documents</button>
                <button class="filter-btn <?= $type == 'kyc' ? 'active' : '' ?>" onclick="filterByType('kyc')">KYC Documents</button>
                <button class="filter-btn <?= $type == 'payment' ? 'active' : '' ?>" onclick="filterByType('payment')">Payment Proofs</button>
            </div>
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search by name, email..." value="<?= htmlspecialchars($search) ?>">
                <button onclick="applySearch()"><i class="fas fa-search"></i> Search</button>
                <?php if($search): ?>
                <button onclick="clearSearch()" style="background: #6c757d;"><i class="fas fa-times"></i> Clear</button>
                <?php endif; ?>
            </div>
        </div>
        <div class="filter-row">
            <div class="date-filter-group">
                <button class="date-filter-btn <?= $date_filter == '' ? 'active' : '' ?>" onclick="setDateFilter('')">All Time</button>
                <button class="date-filter-btn <?= $date_filter == 'today' ? 'active' : '' ?>" onclick="setDateFilter('today')">Today</button>
                <button class="date-filter-btn <?= $date_filter == 'yesterday' ? 'active' : '' ?>" onclick="setDateFilter('yesterday')">Yesterday</button>
                <button class="date-filter-btn <?= $date_filter == 'week' ? 'active' : '' ?>" onclick="setDateFilter('week')">Last 7 Days</button>
                <button class="date-filter-btn <?= $date_filter == 'month' ? 'active' : '' ?>" onclick="setDateFilter('month')">Last 30 Days</button>
                <input type="date" id="customDatePicker" class="custom-date-input" value="<?= $custom_date ?>">
                <button class="date-filter-btn" onclick="applyCustomDate()">Apply</button>
            </div>
            <?php if($rejected_payments_count > 0): ?>
            <button class="delete-all-btn" onclick="confirmDeleteAllRejected()">
                <i class="fas fa-trash-alt"></i> Delete All Rejected (<?= $rejected_payments_count ?>)
            </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- KYC Documents by Date -->
    <?php if($type == 'all' || $type == 'kyc'): ?>
    <div style="margin-bottom: 2rem;">
        <div class="table-header" style="background: linear-gradient(135deg, #2c5f2d, #1a3a1a); margin-bottom: 1rem; border-radius: 15px;">
            <h3><i class="fas fa-id-card"></i> KYC Documents</h3>
            <span class="badge"><?= array_sum(array_map('count', $kyc_grouped)) ?> Records</span>
        </div>
        
        <?php if(empty($kyc_dates)): ?>
            <div class="document-table">
                <div class="empty-state">
                    <i class="fas fa-folder-open"></i>
                    <p>No KYC documents found</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach($kyc_dates as $date): ?>
                <div class="date-section">
                    <div class="date-section-header" onclick="toggleDateSection(this)">
                        <h3>
                            <i class="fas fa-calendar-alt"></i>
                            <?= date('l, F j, Y', strtotime($date)) ?>
                            <span class="badge"><?= count($kyc_grouped[$date]) ?> Documents</span>
                        </h3>
                        <i class="fas fa-chevron-down toggle-icon"></i>
                    </div>
                    <div class="date-section-content">
                        <div class="document-table">
                            <div class="table-wrapper">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Mobile</th>
                                            <th>Document</th>
                                            <th>Status</th>
                                            <th>Time</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($kyc_grouped[$date] as $row): 
                                            $fileInfo = getFilePreview($row['kyc_doc']);
                                        ?>
                                        <tr>
                                            <td>#<?= $row['id'] ?></td>
                                            <td><?= htmlspecialchars($row['name']) ?></td>
                                            <td><?= htmlspecialchars($row['email']) ?></td>
                                            <td><?= htmlspecialchars($row['mobile'] ?: 'N/A') ?></td>
                                            <td>
                                                <?php if($fileInfo['exists']): ?>
                                                <div class="doc-preview">
                                                    <?php if($fileInfo['type'] == 'image'): ?>
                                                        <img src="<?= $fileInfo['web_url'] ?>" class="doc-thumbnail" onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'image', 'KYC Document - <?= htmlspecialchars($row['name']) ?>')">
                                                    <?php else: ?>
                                                        <div class="doc-icon">
                                                            <i class="fas fa-file-pdf" style="color: #dc3545;"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    <button class="btn-sm btn-info" onclick="showDocument('<?= $fileInfo['web_url'] ?>', '<?= $fileInfo['type'] ?>', 'KYC Document - <?= htmlspecialchars($row['name']) ?>')">
                                                        <i class="fas fa-eye"></i> View
                                                    </button>
                                                </div>
                                                <?php else: ?>
                                                    <span class="badge-status badge-pending">No file</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge-status badge-<?= $row['kyc_status'] ?>">
                                                    <?= ucfirst($row['kyc_status']) ?>
                                                </span>
                                            </td>
                                            <td><?= date('h:i A', strtotime($row['created_at'])) ?></td>
                                            <td>
                                                <?php if($row['kyc_status'] == 'pending'): ?>
                                                    <a href="?approve_kyc_manual=<?= $row['id'] ?>" class="btn-sm btn-success" onclick="return confirm('Approve KYC?')">
                                                        <i class="fas fa-check"></i> Approve
                                                    </a>
                                                    <a href="?reject_kyc_manual=<?= $row['id'] ?>" class="btn-sm btn-danger" onclick="return confirm('Reject KYC?')">
                                                        <i class="fas fa-times"></i> Reject
                                                    </a>
                                                <?php endif; ?>
                                                <a href="?delete_kyc=<?= $row['id'] ?>" class="btn-sm btn-warning" onclick="return confirm('Delete KYC document? This action cannot be undone.')">
                                                    <i class="fas fa-trash-alt"></i> Delete
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Payment Proofs by Date -->
    <?php if($type == 'all' || $type == 'payment'): ?>
    <div>
        <div class="table-header" style="background: linear-gradient(135deg, #17a2b8, #138496); margin-bottom: 1rem; border-radius: 15px;">
            <h3><i class="fas fa-receipt"></i> Payment Proofs</h3>
            <span class="badge"><?= array_sum(array_map('count', $payment_grouped)) ?> Records</span>
        </div>
        
        <?php if(empty($payment_dates)): ?>
            <div class="document-table">
                <div class="empty-state">
                    <i class="fas fa-folder-open"></i>
                    <p>No payment proofs found</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach($payment_dates as $date): ?>
                <div class="date-section">
                    <div class="date-section-header" onclick="toggleDateSection(this)" style="background: linear-gradient(135deg, #17a2b8, #138496);">
                        <h3>
                            <i class="fas fa-calendar-alt"></i>
                            <?= date('l, F j, Y', strtotime($date)) ?>
                            <span class="badge"><?= count($payment_grouped[$date]) ?> Payments</span>
                        </h3>
                        <i class="fas fa-chevron-down toggle-icon"></i>
                    </div>
                    <div class="date-section-content">
                        <div class="document-table">
                            <div class="table-wrapper">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Mobile</th>
                                            <th>Amount</th>
                                            <th>Document</th>
                                            <th>Status</th>
                                            <th>Time</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($payment_grouped[$date] as $row): 
                                            $fileInfo = getFilePreview($row['payment_proof']);
                                        ?>
                                        <tr>
                                            <td>#<?= str_pad($row['id'], 6, '0', STR_PAD_LEFT) ?></td>
                                            <td><?= htmlspecialchars($row['name']) ?></td>
                                            <td><?= htmlspecialchars($row['email']) ?></td>
                                            <td><?= htmlspecialchars($row['mobile'] ?: 'N/A') ?></td>
                                            <td><strong style="color: #28a745;">₹<?= number_format($row['amount'], 2) ?></strong></td>
                                            <td>
                                                <?php if($fileInfo['exists']): ?>
                                                <div class="doc-preview">
                                                    <?php if($fileInfo['type'] == 'image'): ?>
                                                        <img src="<?= $fileInfo['web_url'] ?>" class="doc-thumbnail" onclick="showDocument('<?= $fileInfo['web_url'] ?>', 'image', 'Payment Proof - <?= htmlspecialchars($row['name']) ?>')">
                                                    <?php else: ?>
                                                        <div class="doc-icon">
                                                            <i class="fas fa-file-pdf" style="color: #dc3545;"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    <button class="btn-sm btn-info" onclick="showDocument('<?= $fileInfo['web_url'] ?>', '<?= $fileInfo['type'] ?>', 'Payment Proof - <?= htmlspecialchars($row['name']) ?>')">
                                                        <i class="fas fa-eye"></i> View
                                                    </button>
                                                    <a href="<?= $fileInfo['web_url'] ?>" download class="btn-sm btn-primary">
                                                        <i class="fas fa-download"></i>
                                                    </a>
                                                    <?php if($row['status'] == 'rejected'): ?>
                                                    <button class="btn-sm btn-danger" onclick="confirmSingleDelete(<?= $row['id'] ?>, '<?= htmlspecialchars($row['name']) ?>')">
                                                        <i class="fas fa-trash-alt"></i> Delete
                                                    </button>
                                                    <?php endif; ?>
                                                </div>
                                                <?php else: ?>
                                                    <span class="badge-status badge-pending">No file</span>
                                                <?php endif; ?>
                                              </td>
                                            <td>
                                                <span class="badge-status badge-<?= $row['status'] == 'verified' ? 'approved' : ($row['status'] == 'pending' ? 'pending' : 'rejected') ?>">
                                                    <?= ucfirst($row['status']) ?>
                                                </span>
                                            </td>
                                            <td><?= date('h:i A', strtotime($row['uploaded_at'])) ?></td>
                                            <td>
                                                <?php if($row['status'] == 'pending'): ?>
                                                    <a href="verify_payment.php?id=<?= $row['id'] ?>&action=approve" class="btn-sm btn-success" onclick="return confirm('Verify this payment?')">
                                                        <i class="fas fa-check"></i> Verify
                                                    </a>
                                                    <a href="verify_payment.php?id=<?= $row['id'] ?>&action=reject" class="btn-sm btn-danger" onclick="return confirm('Reject this payment?')">
                                                        <i class="fas fa-times"></i> Reject
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Document View Modal -->
<div id="docModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">Document Viewer</h3>
            <button class="close-modal" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body" id="modalBody">
        </div>
    </div>
</div>

<!-- Delete Confirmation Modals -->
<!-- Single Delete Confirmation Modal -->
<div id="deleteSingleModal" class="confirm-modal">
    <div class="confirm-modal-content">
        <i class="fas fa-exclamation-triangle warning-icon"></i>
        <h3>Confirm Delete</h3>
        <p>Are you sure you want to delete payment proof for <strong id="deleteSingleUserName"></strong>?<br>This action cannot be undone and the file will be permanently removed.</p>
        <div class="confirm-buttons">
            <button class="btn-sm btn-success" onclick="executeSingleDelete()">Yes, Delete</button>
            <button class="btn-sm btn-danger" onclick="closeSingleDeleteModal()">Cancel</button>
        </div>
    </div>
</div>

<!-- Delete All Rejected Confirmation Modal -->
<div id="deleteAllModal" class="confirm-modal">
    <div class="confirm-modal-content">
        <i class="fas fa-trash-alt warning-icon"></i>
        <h3>Delete All Rejected Payments</h3>
        <p>Are you sure you want to delete ALL rejected payment proofs?<br><strong>Total: <?= $rejected_payments_count ?> record(s)</strong><br>This action cannot be undone and all files will be permanently removed from server.</p>
        <div class="confirm-buttons">
            <button class="btn-sm btn-success" onclick="executeDeleteAll()">Yes, Delete All</button>
            <button class="btn-sm btn-danger" onclick="closeDeleteAllModal()">Cancel</button>
        </div>
    </div>
</div>

<script>
    let deleteSingleId = null;
    
    // Form validation for manual KYC upload
    function validateKYCForm() {
        const userId = document.getElementById('user_id').value;
        const file = document.getElementById('kyc_document').value;
        
        if (!userId) {
            alert('Please select a user');
            return false;
        }
        if (!file) {
            alert('Please select a file to upload');
            return false;
        }
        
        const fileExt = file.split('.').pop().toLowerCase();
        const allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
        if (!allowedExt.includes(fileExt)) {
            alert('Invalid file type. Allowed: JPG, JPEG, PNG, GIF, WEBP, PDF');
            return false;
        }
        
        return true;
    }
    
    // Filter functions
    function filterByType(type) {
        const url = new URL(window.location.href);
        url.searchParams.set('type', type);
        url.searchParams.delete('status');
        window.location.href = url.toString();
    }

    function filterByStatus(status, type) {
        const url = new URL(window.location.href);
        url.searchParams.set('type', type);
        url.searchParams.set('status', status);
        window.location.href = url.toString();
    }

    function applySearch() {
        const search = document.getElementById('searchInput').value;
        const url = new URL(window.location.href);
        if (search) {
            url.searchParams.set('search', search);
        } else {
            url.searchParams.delete('search');
        }
        window.location.href = url.toString();
    }

    function clearSearch() {
        const url = new URL(window.location.href);
        url.searchParams.delete('search');
        window.location.href = url.toString();
    }

    function setDateFilter(filter) {
        const url = new URL(window.location.href);
        url.searchParams.set('date_filter', filter);
        url.searchParams.delete('custom_date');
        window.location.href = url.toString();
    }

    function applyCustomDate() {
        const customDate = document.getElementById('customDatePicker').value;
        if (customDate) {
            const url = new URL(window.location.href);
            url.searchParams.set('date_filter', 'custom');
            url.searchParams.set('custom_date', customDate);
            window.location.href = url.toString();
        }
    }

    function toggleDateSection(element) {
        element.classList.toggle('collapsed');
        const content = element.nextElementSibling;
        content.classList.toggle('collapsed');
    }

    // Document View Functions
    function showDocument(filePath, type, title) {
        const modal = document.getElementById('docModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        
        modalTitle.textContent = title || 'Document Viewer';
        
        if (type === 'image') {
            modalBody.innerHTML = `<img src="${filePath}?t=${Date.now()}" alt="Document" style="max-width: 100%; max-height: 70vh;" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%22 height=%22100%22 viewBox=%220 0 24 24%22 fill=%22%23dc3545%22%3E%3Cpath d=%22M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z%22/%3E%3C/svg%3E'">`;
        } else if (type === 'pdf') {
            modalBody.innerHTML = `<iframe src="${filePath}" style="width: 100%; height: 70vh;" frameborder="0"></iframe>`;
        } else {
            modalBody.innerHTML = `<div style="text-align: center; padding: 2rem;">
                <i class="fas fa-file" style="font-size: 4rem; color: #666;"></i>
                <p><a href="${filePath}" download class="btn btn-primary" style="margin-top: 1rem;">Download File</a></p>
            </div>`;
        }
        
        modal.style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('docModal').style.display = 'none';
        document.getElementById('modalBody').innerHTML = '';
    }
    
    // Single Delete functions
    function confirmSingleDelete(id, userName) {
        deleteSingleId = id;
        document.getElementById('deleteSingleUserName').textContent = userName;
        document.getElementById('deleteSingleModal').style.display = 'flex';
    }
    
    function closeSingleDeleteModal() {
        document.getElementById('deleteSingleModal').style.display = 'none';
        deleteSingleId = null;
    }
    
    function executeSingleDelete() {
        if (deleteSingleId) {
            const url = new URL(window.location.href);
            url.searchParams.set('delete_payment', deleteSingleId);
            window.location.href = url.toString();
        }
    }
    
    // Delete All Rejected functions
    function confirmDeleteAllRejected() {
        document.getElementById('deleteAllModal').style.display = 'flex';
    }
    
    function closeDeleteAllModal() {
        document.getElementById('deleteAllModal').style.display = 'none';
    }
    
    function executeDeleteAll() {
        const url = new URL(window.location.href);
        url.searchParams.set('delete_rejected_payments', '1');
        window.location.href = url.toString();
    }

    // Close modals on escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
            closeSingleDeleteModal();
            closeDeleteAllModal();
        }
    });

    // Close modals on click outside
    window.onclick = function(event) {
        const modal = document.getElementById('docModal');
        if (event.target == modal) {
            closeModal();
        }
        const singleModal = document.getElementById('deleteSingleModal');
        if (event.target == singleModal) {
            closeSingleDeleteModal();
        }
        const allModal = document.getElementById('deleteAllModal');
        if (event.target == allModal) {
            closeDeleteAllModal();
        }
    }

    // Enter key search
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            applySearch();
        }
    });
    
    // Auto close alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            alert.style.opacity = '0';
            setTimeout(function() {
                if (alert.parentElement) alert.remove();
            }, 300);
        });
    }, 5000);
</script>
</body>
</html>