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

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

$userId = intval($_GET['user'] ?? 0);

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

$db = getDB();

// Get user info
$stmt = $db->prepare("SELECT id, unique_id, name, profile_photo, email, mobile, status, created_at FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    redirect(APP_URL . '/admin/chats.php?error=user_not_found');
}

// Get all conversations this user has
$stmt = $db->prepare("
    SELECT DISTINCT 
        u.id as other_user_id,
        u.unique_id as other_unique_id,
        u.name as other_name,
        u.profile_photo as other_photo,
        u.is_ghost_mode,
        (SELECT COUNT(*) FROM messages 
         WHERE ((sender_id = ? AND receiver_id = u.id) OR (sender_id = u.id AND receiver_id = ?))
         AND is_deleted_for_all = 0) as message_count,
        (SELECT MAX(created_at) FROM messages 
         WHERE ((sender_id = ? AND receiver_id = u.id) OR (sender_id = u.id AND receiver_id = ?))
         AND is_deleted_for_all = 0) as last_message_time
    FROM users u
    JOIN messages m ON (m.sender_id = u.id AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = u.id)
    WHERE u.id != ? AND u.status = 'approved'
    AND m.is_deleted_for_all = 0
    ORDER BY last_message_time DESC
");
$stmt->execute([$userId, $userId, $userId, $userId, $userId, $userId, $userId]);
$conversations = $stmt->fetchAll();

$pageTitle = 'View Chats - ' . $user['name'];

include '../includes/header.php';
?>

<div class="min-h-screen bg-slate-50 dark:bg-slate-900">
    <!-- Admin Header -->
    <header class="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 sticky top-0 z-20">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between h-16">
                <div class="flex items-center gap-4">
                    <a href="chats.php" class="text-slate-600 dark:text-slate-400 hover:text-primary">
                        <span class="material-symbols-outlined">arrow_back</span>
                    </a>
                    <div class="text-primary flex items-center gap-2">
                        <span class="material-symbols-outlined text-2xl">chat</span>
                        <span class="font-bold text-lg">User Chat History</span>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- User Info Card -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6 mb-6">
            <div class="flex items-center gap-4">
                <?php if ($user['profile_photo']): ?>
                <img src="../uploads/images/<?php echo htmlspecialchars($user['profile_photo']); ?>" class="w-16 h-16 rounded-full object-cover border-2 border-primary/20">
                <?php else: ?>
                <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center border-2 border-primary/20">
                    <span class="material-symbols-outlined text-3xl text-primary">person</span>
                </div>
                <?php endif; ?>
                <div class="flex-1">
                    <h2 class="text-xl font-bold text-slate-900 dark:text-white"><?php echo htmlspecialchars($user['name']); ?></h2>
                    <p class="text-sm text-slate-500">@<?php echo htmlspecialchars($user['unique_id']); ?></p>
                    <p class="text-sm text-slate-500"><?php echo htmlspecialchars($user['email']); ?></p>
                </div>
                <div class="text-right">
                    <span class="px-3 py-1 rounded-full text-sm font-medium <?php echo $user['status'] === 'approved' ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'; ?>">
                        <?php echo ucfirst($user['status']); ?>
                    </span>
                    <p class="text-xs text-slate-400 mt-2">Joined: <?php echo date('M j, Y', strtotime($user['created_at'])); ?></p>
                </div>
            </div>
        </div>

        <!-- Conversations -->
        <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div class="p-4 border-b border-slate-200 dark:border-slate-700">
                <h3 class="font-semibold text-slate-900 dark:text-white">Active Conversations (<?php echo count($conversations); ?>)</h3>
            </div>
            
            <?php if (empty($conversations)): ?>
            <div class="p-8 text-center">
                <span class="material-symbols-outlined text-4xl text-slate-300 mb-2">chat_bubble_outline</span>
                <p class="text-slate-500">No active conversations</p>
            </div>
            <?php else: ?>
            <div class="divide-y divide-slate-200 dark:divide-slate-700">
                <?php foreach ($conversations as $conv): ?>
                <div class="p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <?php if ($conv['other_photo']): ?>
                            <img src="../uploads/images/<?php echo htmlspecialchars($conv['other_photo']); ?>" class="w-10 h-10 rounded-full object-cover">
                            <?php else: ?>
                            <div class="w-10 h-10 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center">
                                <span class="material-symbols-outlined text-slate-500">person</span>
                            </div>
                            <?php endif; ?>
                            <div>
                                <p class="font-medium text-slate-900 dark:text-white"><?php echo htmlspecialchars($conv['other_name']); ?></p>
                                <p class="text-sm text-slate-500">@<?php echo htmlspecialchars($conv['other_unique_id']); ?></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-sm font-medium text-slate-900 dark:text-white"><?php echo number_format($conv['message_count']); ?> messages</p>
                            <p class="text-xs text-slate-400">Last: <?php echo $conv['last_message_time'] ? date('M j, g:i A', strtotime($conv['last_message_time'])) : 'N/A'; ?></p>
                        </div>
                    </div>
                    <div class="mt-3 flex gap-2">
                        <a href="view-conversation.php?user1=<?php echo $userId; ?>&user2=<?php echo $conv['other_user_id']; ?>" class="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors">
                            View Conversation
                        </a>
                        <form method="POST" action="chat-action.php" class="inline" onsubmit="return confirm('Delete this conversation?')">
                            <input type="hidden" name="action" value="delete_conversation">
                            <input type="hidden" name="user1" value="<?php echo $userId; ?>">
                            <input type="hidden" name="user2" value="<?php echo $conv['other_user_id']; ?>">
                            <button type="submit" class="px-4 py-2 bg-red-500 text-white rounded-lg text-sm font-medium hover:bg-red-600 transition-colors">
                                Delete
                            </button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Quick Stats -->
        <div class="grid grid-cols-3 gap-4 mt-6">
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-4 text-center">
                <p class="text-2xl font-bold text-primary"><?php echo count($conversations); ?></p>
                <p class="text-sm text-slate-500">Active Chats</p>
            </div>
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-4 text-center">
                <p class="text-2xl font-bold text-blue-600">
                    <?php 
                    $totalMsgs = array_sum(array_column($conversations, 'message_count'));
                    echo number_format($totalMsgs);
                    ?>
                </p>
                <p class="text-sm text-slate-500">Total Messages</p>
            </div>
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-4 text-center">
                <p class="text-2xl font-bold text-green-600">
                    <?php echo $user['status'] === 'approved' ? 'Active' : 'Pending'; ?>
                </p>
                <p class="text-sm text-slate-500">Account Status</p>
            </div>
        </div>
    </main>
</div>

<?php $hideFooter = true; include '../includes/footer.php'; ?>
