<?php
// Clear any output buffer to prevent JSON corruption
if (ob_get_level()) {
    ob_end_clean();
}

// Start session only if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../config.php';
require_once '../../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$raw_input = file_get_contents('php://input');
$input = json_decode($raw_input, true);

// If no input from php://input, try to get from POST data (for testing)
if (empty($raw_input) && !empty($_POST)) {
    $input = $_POST;
}





if (!$input || !isset($input['order_ids']) || !is_array($input['order_ids'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing or invalid order IDs']);
    exit;
}

$order_ids = array_map('intval', $input['order_ids']);
$source = isset($input['source']) ? $input['source'] : 'orders';
$network_type = isset($input['network_type']) ? $input['network_type'] : null;

// Debug logging
error_log("Export CSV - Order IDs: " . json_encode($order_ids));
error_log("Export CSV - Source: " . $source);
error_log("Export CSV - Network Type: " . $network_type);

if (empty($order_ids)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No orders selected']);
    exit;
}

try {
    // Create placeholders for the IN clause
    $placeholders = str_repeat('?,', count($order_ids) - 1) . '?';
    
    // Query to get order details based on source
    if ($source === 'agent_orders') {
        $sql = "SELECT 
                    ao.id,
                    ao.package_size,
                    ao.amount,
                    ao.beneficiary_number,
                    ao.status,
                    ao.created_at,
                    ao.network_type,
                    COALESCE(a.username, CONCAT('Agent #', ao.agent_id), 'Unknown Agent') as username,
                    a.role
                FROM agent_orders ao
                LEFT JOIN agents a ON ao.agent_id = a.id
                WHERE ao.id IN ($placeholders)";
        
        if ($network_type) {
            $sql .= " AND ao.network_type = ?";
        }
        
        $sql .= " ORDER BY ao.id DESC";
    } else {
        $sql = "SELECT 
                    o.id,
                    o.package_size,
                    o.amount,
                    o.beneficiary_number,
                    o.status,
                    o.created_at,
                    COALESCE(a.username, CONCAT('Agent #', o.user_id), 'Unknown Agent') as username,
                    a.role
                FROM orders o
                LEFT JOIN agents a ON o.user_id = a.id
                WHERE o.id IN ($placeholders)
                ORDER BY o.id DESC";
    }
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Failed to prepare statement: " . $conn->error);
    }
    
    // Bind parameters
    $types = str_repeat('i', count($order_ids));
    $params = $order_ids;
    
    if ($source === 'agent_orders' && $network_type) {
        $types .= 's';
        $params[] = $network_type;
    }
    
    $stmt->bind_param($types, ...$params);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to execute query: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    
    // Set headers for CSV download
    $filename_prefix = $source === 'agent_orders' ? 'agent_orders' : 'orders';
    if ($network_type) {
        $filename_prefix .= '_' . $network_type;
    }
    $filename = $filename_prefix . '_export_' . date('Y-m-d_H-i-s') . '.csv';
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    // Create CSV content
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8 to ensure proper encoding in Excel
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // Write CSV header (optional - you can remove this if you don't want headers)
    // fputcsv($output, ['Beneficiary Number', 'Username', '', 'Package Size (MB)']);
    
    // Write data rows in the format: Beneficiary Number, Username, Empty Column, Package Size (MB)
    while ($row = $result->fetch_assoc()) {
        // Convert package size to megabytes
        $package_size_mb = '';
        if (!empty($row['package_size'])) {
            // Extract number from package size (e.g., "1GB" -> 1024, "500MB" -> 500)
            if (preg_match('/(\d+(?:\.\d+)?)\s*(GB|MB)/i', $row['package_size'], $matches)) {
                $size = floatval($matches[1]);
                $unit = strtoupper($matches[2]);
                
                if ($unit === 'GB') {
                    $package_size_mb = $size * 1024; // Convert GB to MB
                } else {
                    $package_size_mb = $size; // Already in MB
                }
            }
        }
        
        $csv_row = [
            $row['username'], // Name (first column)
            $row['beneficiary_number'], // Beneficiary number (second column)
            $package_size_mb // Package size in megabytes (third column)
        ];
        fputcsv($output, $csv_row, "\t"); // Use tab separator as in your example
    }
    
    fclose($output);
    $stmt->close();
    
} catch (Exception $e) {
    error_log("Export CSV Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Export failed: ' . $e->getMessage()]);
}
?>
