<?php
require_once '../includes/init.php';

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    redirect(APP_URL . '/login.php');
}

$user1 = intval($_POST['user1'] ?? 0);
$user2 = intval($_POST['user2'] ?? 0);
$format = $_POST['format'] ?? 'csv';

if (!$user1 || !$user2) {
    redirect(APP_URL . '/admin/chats.php');
}

$db = getDB();

// Get user names
$stmt = $db->prepare("SELECT id, name, unique_id FROM users WHERE id IN (?, ?)");
$stmt->execute([$user1, $user2]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Create key-value pairs for easy access
$userMap = [];
foreach ($users as $user) {
    $userMap[$user['id']] = $user;
}

// Get messages
$stmt = $db->prepare("
    SELECT m.*, 
        sender.name as sender_name, sender.unique_id as sender_unique,
        receiver.name as receiver_name, receiver.unique_id as receiver_unique
    FROM messages m
    JOIN users sender ON m.sender_id = sender.id
    JOIN users receiver ON m.receiver_id = receiver.id
    WHERE ((m.sender_id = ? AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = ?))
    AND m.is_deleted_for_all = 0
    ORDER BY m.created_at ASC
");
$stmt->execute([$user1, $user2, $user2, $user1]);
$messages = $stmt->fetchAll();

if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="chat_' . $userMap[$user1]['unique_id'] . '_' . $userMap[$user2]['unique_id'] . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Date', 'Sender', 'Receiver', 'Message Type', 'Message', 'File URL']);
    
    foreach ($messages as $msg) {
        fputcsv($output, [
            $msg['created_at'],
            $msg['sender_name'] . ' (@' . $msg['sender_unique'] . ')',
            $msg['receiver_name'] . ' (@' . $msg['receiver_unique'] . ')',
            $msg['message_type'],
            $msg['message'],
            $msg['file_url'] ?? ''
        ]);
    }
    fclose($output);
    exit;
} elseif ($format === 'json') {
    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename="chat_' . $userMap[$user1]['unique_id'] . '_' . $userMap[$user2]['unique_id'] . '.json"');
    
    $data = [
        'users' => [
            'user1' => $userMap[$user1],
            'user2' => $userMap[$user2]
        ],
        'messages' => $messages,
        'exported_at' => date('Y-m-d H:i:s'),
        'exported_by' => $_SESSION['user_name']
    ];
    
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}

// Default redirect
redirect(APP_URL . '/admin/chats.php');
?>
