<?php
require_once '../config/database.php';

try {
    $pdo = getDBConnection();
    
    // Get filters from GET parameters
    $filters = $_GET;
    
    // Build WHERE clause based on filters
    $whereConditions = [];
    $params = [];
    
    // Date range filter
    if (!empty($filters['dateFrom'])) {
        $whereConditions[] = "DATE(p.created_at) >= :date_from";
        $params[':date_from'] = $filters['dateFrom'];
    }
    
    if (!empty($filters['dateTo'])) {
        $whereConditions[] = "DATE(p.created_at) <= :date_to";
        $params[':date_to'] = $filters['dateTo'];
    }
    
    // Status filter
    if (!empty($filters['status'])) {
        $whereConditions[] = "p.status = :status";
        $params[':status'] = $filters['status'];
    }
    
    // Payment method filter
    if (!empty($filters['paymentMethod'])) {
        $whereConditions[] = "p.payment_method = :payment_method";
        $params[':payment_method'] = $filters['paymentMethod'];
    }
    
    // Amount range filters
    if (!empty($filters['amountMin'])) {
        $whereConditions[] = "p.amount >= :amount_min";
        $params[':amount_min'] = $filters['amountMin'];
    }
    
    if (!empty($filters['amountMax'])) {
        $whereConditions[] = "p.amount <= :amount_max";
        $params[':amount_max'] = $filters['amountMax'];
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Get payments data for export
    $query = "
        SELECT 
            p.id,
            p.transaction_id,
            p.amount,
            p.status,
            p.payment_method,
            p.created_at,
            a.user_name,
            a.user_mobile,
            a.appointment_date,
            a.time_slot,
            a.consultation_type
        FROM payments p
        LEFT JOIN appointments a ON p.appointment_id = a.id
        $whereClause
        ORDER BY p.created_at DESC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Set headers for CSV download
    $filename = 'payments_export_' . date('Y-m-d_H-i-s') . '.csv';
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Expires: 0');
    
    // Create CSV output
    $output = fopen('php://output', 'w');
    
    // CSV headers
    $headers = [
        'ID',
        'Transaction ID',
        'Amount',
        'Status',
        'Payment Method',
        'Created Date',
        'User Name',
        'User Mobile',
        'Appointment Date',
        'Time Slot',
        'Consultation Type'
    ];
    
    fputcsv($output, $headers);
    
    // CSV data
    foreach ($payments as $payment) {
        $row = [
            $payment['id'],
            $payment['transaction_id'],
            $payment['amount'],
            $payment['status'],
            $payment['payment_method'],
            $payment['created_at'],
            $payment['user_name'] ?? 'N/A',
            $payment['user_mobile'] ?? 'N/A',
            $payment['appointment_date'] ?? 'N/A',
            $payment['time_slot'] ?? 'N/A',
            $payment['consultation_type'] ?? 'N/A'
        ];
        
        fputcsv($output, $row);
    }
    
    fclose($output);
    
} catch (Exception $e) {
    error_log("Export payments error: " . $e->getMessage());
    
    // Return error response
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Export failed: ' . $e->getMessage()
    ]);
}
?>
