<?php
require_once 'auth.php';
require_once '../db_config.php';
require_once 'RegistrationLogger.php';

// Require admin login
requireLogin();

$export_type = $_GET['type'] ?? '';
$format = $_GET['format'] ?? 'csv';

if (empty($export_type)) {
    header('Location: dashboard.php');
    exit;
}

try {
    $pdo = getDBConnection();
    
    switch ($export_type) {
        case 'registrations':
            $query = "
                SELECT 
                    registration_number,
                    delegate_type,
                    delegate_count,
                    has_standard_table,
                    has_double_table,
                    contact_full_name,
                    contact_badge_name,
                    contact_designation,
                    contact_department,
                    contact_email,
                    contact_mobile,
                    university_name,
                    country,
                    payment_method,
                    payment_status,
                    payment_reference,
                    total_amount,
                    payment_deadline,
                    created_at
                FROM registrations 
                ORDER BY created_at DESC
            ";
            $filename = 'xchange_registrations_' . date('Y-m-d');
            break;
            
        case 'delegates':
            $query = "
                SELECT 
                    r.registration_number,
                    d.full_name,
                    d.badge_name,
                    d.email,
                    d.designation,
                    d.department,
                    d.dietary_requirements,
                    d.special_assistance,
                    r.university_name,
                    r.country,
                    r.delegate_type,
                    r.payment_status,
                    r.created_at as registration_date
                FROM delegates d 
                JOIN registrations r ON d.registration_id = r.id 
                ORDER BY r.created_at DESC, d.id ASC
            ";
            $filename = 'xchange_delegates_' . date('Y-m-d');
            break;
            
        case 'payments':
            $query = "
                SELECT 
                    registration_number,
                    contact_full_name,
                    university_name,
                    payment_method,
                    payment_status,
                    payment_reference,
                    total_amount,
                    payment_deadline,
                    created_at,
                    updated_at
                FROM registrations 
                ORDER BY created_at DESC
            ";
            $filename = 'xchange_payments_' . date('Y-m-d');
            break;
            
        default:
            throw new Exception("Invalid export type");
    }
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Log export operation
    try {
        $logger = new RegistrationLogger($pdo, $_SESSION['admin_user'] ?? null);
        $exportTypeLabel = ucfirst($export_type);
        $recordCount = count($data);
        $logger->logBulkOperation(
            'data_export',
            $recordCount,
            "Exported {$exportTypeLabel} data: {$recordCount} records in {$format} format",
            []
        );
    } catch (Exception $e) {
        error_log("Failed to log export operation: " . $e->getMessage());
    }
    
    if ($format === 'csv') {
        // Set headers for CSV download
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
        
        // Output CSV
        $output = fopen('php://output', 'w');
        
        // Write header row
        if (!empty($data)) {
            fputcsv($output, array_keys($data[0]));
            
            // Write data rows
            foreach ($data as $row) {
                fputcsv($output, $row);
            }
        }
        
        fclose($output);
        exit;
    }
    
} catch (Exception $e) {
    $error = "Export error: " . $e->getMessage();
    header('Location: dashboard.php?error=' . urlencode($error));
    exit;
}
?>
