<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// Get export parameters
$export_type = $_GET['type'] ?? 'all'; // all, pending, approved, rejected
$date_range = $_GET['date_range'] ?? 'all'; // all, today, week, month, custom
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$format = $_GET['format'] ?? 'csv'; // csv, excel, pdf

// Build query based on filters
$where_conditions = [];
$params = [];
$types = '';

// KYC status filter
if ($export_type != 'all' && in_array($export_type, ['pending', 'approved', 'rejected', 'under_review'])) {
    $where_conditions[] = "u.kyc_status = ?";
    $params[] = $export_type;
    $types .= 's';
}

// Date range filter
if ($date_range != 'all') {
    switch ($date_range) {
        case 'today':
            $where_conditions[] = "DATE(u.created_at) = CURDATE()";
            break;
        case 'week':
            $where_conditions[] = "u.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
            break;
        case 'month':
            $where_conditions[] = "u.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
            break;
        case 'custom':
            if (!empty($start_date) && !empty($end_date)) {
                $where_conditions[] = "DATE(u.created_at) BETWEEN ? AND ?";
                $params[] = $start_date;
                $params[] = $end_date;
                $types .= 'ss';
            }
            break;
    }
}

// Only include users with KYC data
$where_conditions[] = "(u.kyc_document_path IS NOT NULL OR u.kyc_status != '')";

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Fetch KYC data with user details - FIXED QUERY
$query = "SELECT 
    u.id as user_id,
    u.username,
    u.full_name,
    u.email,
    u.phone,
    u.country,
    u.state,
    u.city,
    u.kyc_status,
    u.kyc_document_path,
    u.account_tier,
    u.account_status,
    u.account_balance,
    u.total_invested,
    u.created_at as account_created,
    u.updated_at as last_updated,
    COALESCE(kl.last_action, 'No action') as last_action,
    COALESCE(kl.action_date, 'Never') as last_action_date,
    COALESCE(kl.performed_by_email, 'System') as last_action_by
FROM users u
LEFT JOIN (
    SELECT 
        kl.user_id,
        MAX(kl.created_at) as latest_date,
        GROUP_CONCAT(kl.action ORDER BY kl.created_at DESC SEPARATOR ', ') as last_action,
        MAX(kl.created_at) as action_date,
        GROUP_CONCAT(a.email ORDER BY kl.created_at DESC SEPARATOR ', ') as performed_by_email
    FROM kyc_logs kl
    LEFT JOIN admin_table a ON kl.performed_by = a.id
    GROUP BY kl.user_id
) kl ON u.id = kl.user_id
$where_clause
ORDER BY u.created_at DESC";

$stmt = $conn->prepare($query);

// Bind parameters if any
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
$kyc_data = [];

while ($row = $result->fetch_assoc()) {
    $kyc_data[] = $row;
}
$stmt->close();

// Get statistics for the export
$statsQuery = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN kyc_status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN kyc_status = 'approved' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN kyc_status = 'rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN kyc_status = 'under_review' THEN 1 ELSE 0 END) as under_review
FROM users 
WHERE kyc_document_path IS NOT NULL OR kyc_status != ''";

$statsResult = $conn->query($statsQuery);
$stats = $statsResult->fetch_assoc();

// Set headers based on format
if ($format == 'csv') {
    exportToCSV($kyc_data, $export_type, $date_range, $stats);
} elseif ($format == 'excel') {
    exportToExcel($kyc_data, $export_type, $date_range, $stats);
} elseif ($format == 'pdf') {
    exportToPDF($kyc_data, $export_type, $date_range, $stats);
} else {
    // If accessed directly without parameters, show export form
    showExportForm();
}

// CSV Export Function
function exportToCSV($data, $export_type, $date_range, $stats) {
    // Generate filename
    $filename = 'kyc_export_' . $export_type . '_' . date('Y-m-d_H-i-s') . '.csv';
    
    // Set headers for CSV download
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    // Create output stream
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8
    fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
    
    // Add metadata header
    fputcsv($output, ['KYC Data Export - Unify Grant']);
    fputcsv($output, ['Export Type:', ucfirst($export_type) . ' Applications']);
    fputcsv($output, ['Date Range:', ucfirst($date_range)]);
    fputcsv($output, ['Export Date:', date('Y-m-d H:i:s')]);
    fputcsv($output, ['Total Records:', count($data)]);
    fputcsv($output, []); // Empty row
    
    // Add statistics
    fputcsv($output, ['Statistics Summary']);
    fputcsv($output, ['Total Applications:', $stats['total']]);
    fputcsv($output, ['Pending:', $stats['pending']]);
    fputcsv($output, ['Approved:', $stats['approved']]);
    fputcsv($output, ['Rejected:', $stats['rejected']]);
    fputcsv($output, ['Under Review:', $stats['under_review']]);
    fputcsv($output, []); // Empty row
    
    // Column headers
    $headers = [
        'User ID',
        'Username',
        'Full Name',
        'Email',
        'Phone',
        'Country',
        'State/Province',
        'City',
        'KYC Status',
        'Account Tier',
        'Account Status',
        'Account Balance ($)',
        'Total Invested ($)',
        'Document Uploaded',
        'Account Created',
        'Last Updated',
        'Last KYC Action',
        'Last Action Date',
        'Action Performed By'
    ];
    
    fputcsv($output, $headers);
    
    // Data rows
    foreach ($data as $row) {
        $document_uploaded = !empty($row['kyc_document_path']) ? 'Yes' : 'No';
        
        $csv_row = [
            $row['user_id'],
            $row['username'],
            $row['full_name'],
            $row['email'],
            $row['phone'],
            $row['country'],
            $row['state'],
            $row['city'],
            ucfirst($row['kyc_status']),
            ucfirst($row['account_tier']),
            ucfirst($row['account_status']),
            number_format($row['account_balance'], 2),
            number_format($row['total_invested'], 2),
            $document_uploaded,
            date('Y-m-d', strtotime($row['account_created'])),
            date('Y-m-d H:i:s', strtotime($row['last_updated'])),
            $row['last_action'],
            $row['last_action_date'] != 'Never' ? date('Y-m-d H:i:s', strtotime($row['last_action_date'])) : 'Never',
            $row['last_action_by']
        ];
        
        fputcsv($output, $csv_row);
    }
    
    // Add footer with summary
    fputcsv($output, []); // Empty row
    fputcsv($output, ['Export Summary']);
    fputcsv($output, ['Generated by:', 'Admin Panel']);
    fputcsv($output, ['Generated on:', date('Y-m-d H:i:s')]);
    
    fclose($output);
    exit();
}

// Excel Export Function (CSV with Excel formatting)
function exportToExcel($data, $export_type, $date_range, $stats) {
    // Generate filename
    $filename = 'kyc_export_' . $export_type . '_' . date('Y-m-d_H-i-s') . '.xls';
    
    // Set headers for Excel download
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    // Create output
    echo "<html>";
    echo "<head>";
    echo "<meta charset=\"UTF-8\">";
    echo "<style>";
    echo "table { border-collapse: collapse; width: 100%; }";
    echo "th { background-color: #4CAF50; color: white; font-weight: bold; padding: 8px; border: 1px solid #ddd; }";
    echo "td { padding: 8px; border: 1px solid #ddd; }";
    echo ".summary { background-color: #f2f2f2; font-weight: bold; }";
    echo ".header { background-color: #2196F3; color: white; font-size: 18px; padding: 10px; }";
    echo "</style>";
    echo "</head>";
    echo "<body>";
    
    // Header
    echo "<table>";
    echo "<tr><td colspan=\"10\" class=\"header\">KYC Data Export - Unify Grant</td></tr>";
    echo "<tr class=\"summary\"><td>Export Type:</td><td>" . ucfirst($export_type) . " Applications</td>";
    echo "<td>Date Range:</td><td>" . ucfirst($date_range) . "</td>";
    echo "<td>Export Date:</td><td>" . date('Y-m-d H:i:s') . "</td>";
    echo "<td>Total Records:</td><td>" . count($data) . "</td></tr>";
    echo "</table><br>";
    
    // Statistics
    echo "<table>";
    echo "<tr><td colspan=\"4\" class=\"summary\">Statistics Summary</td></tr>";
    echo "<tr><td>Total Applications:</td><td>" . $stats['total'] . "</td>";
    echo "<td>Pending:</td><td>" . $stats['pending'] . "</td></tr>";
    echo "<tr><td>Approved:</td><td>" . $stats['approved'] . "</td>";
    echo "<td>Rejected:</td><td>" . $stats['rejected'] . "</td></tr>";
    echo "<tr><td>Under Review:</td><td>" . $stats['under_review'] . "</td>";
    echo "<td>Approval Rate:</td><td>" . ($stats['total'] > 0 ? number_format(($stats['approved'] / $stats['total']) * 100, 1) . '%' : '0%') . "</td></tr>";
    echo "</table><br>";
    
    // Data table
    echo "<table>";
    echo "<tr>";
    echo "<th>User ID</th>";
    echo "<th>Username</th>";
    echo "<th>Full Name</th>";
    echo "<th>Email</th>";
    echo "<th>Phone</th>";
    echo "<th>Country</th>";
    echo "<th>KYC Status</th>";
    echo "<th>Account Tier</th>";
    echo "<th>Account Balance ($)</th>";
    echo "<th>Total Invested ($)</th>";
    echo "<th>Document Uploaded</th>";
    echo "<th>Account Created</th>";
    echo "<th>Last Updated</th>";
    echo "</tr>";
    
    foreach ($data as $row) {
        $document_uploaded = !empty($row['kyc_document_path']) ? 'Yes' : 'No';
        $kyc_status_class = '';
        
        switch ($row['kyc_status']) {
            case 'approved': $kyc_status_class = 'color: green; font-weight: bold;'; break;
            case 'rejected': $kyc_status_class = 'color: red; font-weight: bold;'; break;
            case 'pending': $kyc_status_class = 'color: orange; font-weight: bold;'; break;
            case 'under_review': $kyc_status_class = 'color: blue; font-weight: bold;'; break;
        }
        
        echo "<tr>";
        echo "<td>" . $row['user_id'] . "</td>";
        echo "<td>" . htmlspecialchars($row['username']) . "</td>";
        echo "<td>" . htmlspecialchars($row['full_name']) . "</td>";
        echo "<td>" . htmlspecialchars($row['email']) . "</td>";
        echo "<td>" . htmlspecialchars($row['phone']) . "</td>";
        echo "<td>" . htmlspecialchars($row['country']) . "</td>";
        echo "<td style=\"$kyc_status_class\">" . ucfirst($row['kyc_status']) . "</td>";
        echo "<td>" . ucfirst($row['account_tier']) . "</td>";
        echo "<td>" . number_format($row['account_balance'], 2) . "</td>";
        echo "<td>" . number_format($row['total_invested'], 2) . "</td>";
        echo "<td>" . $document_uploaded . "</td>";
        echo "<td>" . date('Y-m-d', strtotime($row['account_created'])) . "</td>";
        echo "<td>" . date('Y-m-d H:i', strtotime($row['last_updated'])) . "</td>";
        echo "</tr>";
    }
    
    echo "</table>";
    echo "</body>";
    echo "</html>";
    
    exit();
}

// PDF Export Function (Simple version)
function exportToPDF($data, $export_type, $date_range, $stats) {
    // For PDF, we'll create a simple HTML version that can be printed as PDF
    
    // Generate filename
    $filename = 'kyc_export_' . $export_type . '_' . date('Y-m-d_H-i-s') . '.html';
    
    // Set headers for HTML download (users can save as PDF)
    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    echo "<!DOCTYPE html>";
    echo "<html>";
    echo "<head>";
    echo "<meta charset=\"UTF-8\">";
    echo "<title>KYC Export - " . ucfirst($export_type) . " - " . date('Y-m-d') . "</title>";
    echo "<style>";
    echo "@media print {";
    echo "    @page { size: A4 landscape; margin: 1cm; }";
    echo "    body { font-family: Arial, sans-serif; font-size: 10pt; }";
    echo "    table { width: 100%; border-collapse: collapse; page-break-inside: auto; }";
    echo "    tr { page-break-inside: avoid; page-break-after: auto; }";
    echo "    th, td { border: 1px solid #000; padding: 4px; text-align: left; font-size: 9pt; }";
    echo "    th { background-color: #f2f2f2; font-weight: bold; }";
    echo "    .header { text-align: center; margin-bottom: 20px; }";
    echo "    .summary { margin-bottom: 20px; }";
    echo "    .footer { margin-top: 20px; font-size: 8pt; color: #666; text-align: center; }";
    echo "}";
    echo "body { font-family: Arial, sans-serif; margin: 20px; }";
    echo "table { width: 100%; border-collapse: collapse; margin-top: 10px; }";
    echo "th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }";
    echo "th { background-color: #4CAF50; color: white; }";
    echo ".header { text-align: center; background-color: #2196F3; color: white; padding: 15px; border-radius: 5px; }";
    echo ".summary { background-color: #f9f9f9; padding: 15px; border-radius: 5px; margin: 20px 0; }";
    echo ".footer { margin-top: 30px; padding-top: 10px; border-top: 1px solid #ddd; color: #666; }";
    echo "</style>";
    echo "</head>";
    echo "<body>";
    
    // Header
    echo "<div class=\"header\">";
    echo "<h1>KYC Data Export - Unify Grant</h1>";
    echo "<p>Export Type: " . ucfirst($export_type) . " Applications | Date Range: " . ucfirst($date_range) . " | Generated: " . date('Y-m-d H:i:s') . "</p>";
    echo "</div>";
    
    // Summary
    echo "<div class=\"summary\">";
    echo "<h3>Export Summary</h3>";
    echo "<p>Total Records: " . count($data) . " | ";
    echo "Pending: " . $stats['pending'] . " | ";
    echo "Approved: " . $stats['approved'] . " | ";
    echo "Rejected: " . $stats['rejected'] . " | ";
    echo "Under Review: " . $stats['under_review'] . "</p>";
    echo "<p>Approval Rate: " . ($stats['total'] > 0 ? number_format(($stats['approved'] / $stats['total']) * 100, 1) . '%' : '0%') . "</p>";
    echo "</div>";
    
    // Data table
    echo "<table>";
    echo "<thead>";
    echo "<tr>";
    echo "<th>ID</th>";
    echo "<th>User</th>";
    echo "<th>Email</th>";
    echo "<th>Phone</th>";
    echo "<th>Country</th>";
    echo "<th>KYC Status</th>";
    echo "<th>Account Tier</th>";
    echo "<th>Balance</th>";
    echo "<th>Invested</th>";
    echo "<th>Document</th>";
    echo "<th>Created</th>";
    echo "</tr>";
    echo "</thead>";
    echo "<tbody>";
    
    foreach ($data as $row) {
        $document_uploaded = !empty($row['kyc_document_path']) ? 'Yes' : 'No';
        
        echo "<tr>";
        echo "<td>" . $row['user_id'] . "</td>";
        echo "<td>" . htmlspecialchars($row['full_name'] ?: $row['username']) . "</td>";
        echo "<td>" . htmlspecialchars($row['email']) . "</td>";
        echo "<td>" . htmlspecialchars($row['phone']) . "</td>";
        echo "<td>" . htmlspecialchars($row['country']) . "</td>";
        echo "<td>" . ucfirst($row['kyc_status']) . "</td>";
        echo "<td>" . ucfirst($row['account_tier']) . "</td>";
        echo "<td>$" . number_format($row['account_balance'], 2) . "</td>";
        echo "<td>$" . number_format($row['total_invested'], 2) . "</td>";
        echo "<td>" . $document_uploaded . "</td>";
        echo "<td>" . date('Y-m-d', strtotime($row['account_created'])) . "</td>";
        echo "</tr>";
    }
    
    echo "</tbody>";
    echo "</table>";
    
    // Footer
    echo "<div class=\"footer\">";
    echo "<p>Generated by Admin Panel | Page 1 of 1 | " . date('Y-m-d H:i:s') . "</p>";
    echo "<p>Confidential - For Internal Use Only</p>";
    echo "</div>";
    
    // Print button
    echo "<script>";
    echo "window.onload = function() {";
    echo "    window.print();";
    echo "    setTimeout(function() {";
    echo "        window.close();";
    echo "    }, 1000);";
    echo "};";
    echo "</script>";
    
    echo "</body>";
    echo "</html>";
    
    exit();
}

// Show export form if accessed directly
function showExportForm() {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Export KYC Data - Unify Grant</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
        <script>
            tailwind.config = {
                theme: {
                    extend: {
                        colors: {
                            primary: {
                                50: '#eff6ff',
                                100: '#dbeafe',
                                200: '#bfdbfe',
                                300: '#93c5fd',
                                400: '#60a5fa',
                                500: '#3b82f6',
                                600: '#2563eb',
                                700: '#1d4ed8',
                                800: '#1e40af',
                                900: '#1e3a8a',
                            }
                        },
                        fontFamily: {
                            'inter': ['Inter', 'system-ui', 'sans-serif'],
                        }
                    }
                }
            }
        </script>
    </head>
    <body class="bg-gray-50 font-inter min-h-screen flex items-center justify-center p-4">

    <div class="bg-white rounded-xl shadow-lg border border-gray-200 w-full max-w-2xl">
        <div class="p-8">
            <div class="text-center mb-8">
                <i class="fas fa-file-export text-5xl text-primary-600 mb-4"></i>
                <h1 class="text-2xl font-bold text-gray-800">Export KYC Data</h1>
                <p class="text-gray-600 mt-2">Export KYC applications to various formats</p>
            </div>

            <form method="GET" class="space-y-6">
                <!-- Export Type -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-filter mr-2"></i>
                        Export Type
                    </label>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
                        <label class="flex items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="type" value="all" checked class="h-4 w-4 text-primary-600">
                            <span class="ml-2 text-sm text-gray-700">All KYC</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="type" value="pending" class="h-4 w-4 text-primary-600">
                            <span class="ml-2 text-sm text-gray-700">Pending Only</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="type" value="approved" class="h-4 w-4 text-primary-600">
                            <span class="ml-2 text-sm text-gray-700">Approved Only</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="type" value="rejected" class="h-4 w-4 text-primary-600">
                            <span class="ml-2 text-sm text-gray-700">Rejected Only</span>
                        </label>
                    </div>
                </div>

                <!-- Date Range -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-calendar-alt mr-2"></i>
                        Date Range
                    </label>
                    <select name="date_range" id="dateRange" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500">
                        <option value="all">All Time</option>
                        <option value="today">Today</option>
                        <option value="week">Last 7 Days</option>
                        <option value="month">Last 30 Days</option>
                        <option value="custom">Custom Range</option>
                    </select>
                    
                    <div id="customDateRange" class="mt-3 hidden">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                                <input type="date" name="start_date" id="startDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                                <input type="date" name="end_date" id="endDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Export Format -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-file mr-2"></i>
                        Export Format
                    </label>
                    <div class="grid grid-cols-3 gap-3">
                        <label class="flex flex-col items-center p-4 border-2 border-primary-200 bg-primary-50 rounded-lg cursor-pointer">
                            <input type="radio" name="format" value="csv" checked class="h-4 w-4 text-primary-600 mb-2">
                            <i class="fas fa-file-csv text-2xl text-primary-600 mb-2"></i>
                            <span class="text-sm font-medium text-gray-800">CSV</span>
                            <span class="text-xs text-gray-500 mt-1">Compatible</span>
                        </label>
                        <label class="flex flex-col items-center p-4 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="format" value="excel" class="h-4 w-4 text-primary-600 mb-2">
                            <i class="fas fa-file-excel text-2xl text-green-600 mb-2"></i>
                            <span class="text-sm font-medium text-gray-800">Excel</span>
                            <span class="text-xs text-gray-500 mt-1">Spreadsheet</span>
                        </label>
                        <label class="flex flex-col items-center p-4 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="format" value="pdf" class="h-4 w-4 text-primary-600 mb-2">
                            <i class="fas fa-file-pdf text-2xl text-red-600 mb-2"></i>
                            <span class="text-sm font-medium text-gray-800">PDF</span>
                            <span class="text-xs text-gray-500 mt-1">Printable</span>
                        </label>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex space-x-3 pt-6 border-t border-gray-200">
                    <button type="button" onclick="window.history.back()" 
                            class="flex-1 px-4 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                        <i class="fas fa-arrow-left mr-2"></i>
                        Back
                    </button>
                    <button type="submit" 
                            class="flex-1 px-4 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                        <i class="fas fa-download mr-2"></i>
                        Generate Export
                    </button>
                </div>
            </form>

            <!-- Quick Export Buttons -->
            <div class="mt-8 pt-6 border-t border-gray-200">
                <p class="text-sm font-medium text-gray-700 mb-3">Quick Export</p>
                <div class="grid grid-cols-2 gap-3">
                    <a href="?type=pending&format=csv&date_range=today" 
                       class="flex items-center justify-center p-3 bg-yellow-50 text-yellow-700 rounded-lg hover:bg-yellow-100 transition">
                        <i class="fas fa-clock mr-2"></i>
                        Today's Pending
                    </a>
                    <a href="?type=approved&format=excel&date_range=month" 
                       class="flex items-center justify-center p-3 bg-green-50 text-green-700 rounded-lg hover:bg-green-100 transition">
                        <i class="fas fa-check-circle mr-2"></i>
                        Monthly Approved
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Show/hide custom date range
        document.getElementById('dateRange').addEventListener('change', function() {
            const customDiv = document.getElementById('customDateRange');
            if (this.value === 'custom') {
                customDiv.classList.remove('hidden');
            } else {
                customDiv.classList.add('hidden');
            }
        });

        // Set default dates for custom range
        const today = new Date().toISOString().split('T')[0];
        const lastMonth = new Date();
        lastMonth.setMonth(lastMonth.getMonth() - 1);
        const lastMonthStr = lastMonth.toISOString().split('T')[0];
        
        document.getElementById('startDate').value = lastMonthStr;
        document.getElementById('endDate').value = today;

        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const dateRange = document.getElementById('dateRange').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            if (dateRange === 'custom' && (!startDate || !endDate)) {
                e.preventDefault();
                alert('Please select both start and end dates for custom range.');
                document.getElementById('customDateRange').classList.remove('hidden');
            }
        });
    </script>

    </body>
    </html>
    <?php
    exit();
}