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

if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

$pageTitle = 'Chats';
$activePage = 'chats';

$db = getDB();

// Get unread messages count
$stmt = $db->prepare("
    SELECT COUNT(*) FROM messages 
    WHERE receiver_id = ? 
    AND id NOT IN (SELECT message_id FROM message_status WHERE user_id = ? AND status = 'read')
    AND deleted_by_receiver = 0 AND is_deleted_for_all = 0
");
$stmt->execute([$_SESSION['user_id'], $_SESSION['user_id']]);
$unreadCount = $stmt->fetchColumn();

// Get unread announcements count
$stmt = $db->prepare("
    SELECT COUNT(*) FROM announcements 
    WHERE is_active = 1 
    AND id NOT IN (SELECT announcement_id FROM announcement_reads WHERE user_id = ? AND is_read = 1)
");
$stmt->execute([$_SESSION['user_id']]);
$unreadAnnouncements = $stmt->fetchColumn();

// Get all conversations for the current user
$stmt = $db->prepare("
    SELECT DISTINCT 
        u.id as user_id,
        u.unique_id,
        u.name,
        u.profile_photo,
        u.is_ghost_mode,
        u.last_seen,
        u.status as user_status,
        u.last_activity,
        (SELECT message FROM messages 
         WHERE ((sender_id = ? AND receiver_id = u.id) OR (sender_id = u.id AND receiver_id = ?))
         AND ((sender_id = ? AND deleted_by_sender = 0) OR (receiver_id = ? AND deleted_by_receiver = 0))
         AND is_deleted_for_all = 0
         ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT message_type FROM messages 
         WHERE ((sender_id = ? AND receiver_id = u.id) OR (sender_id = u.id AND receiver_id = ?))
         AND ((sender_id = ? AND deleted_by_sender = 0) OR (receiver_id = ? AND deleted_by_receiver = 0))
         AND is_deleted_for_all = 0
         ORDER BY created_at DESC LIMIT 1) as last_message_type,
        (SELECT created_at FROM messages 
         WHERE ((sender_id = ? AND receiver_id = u.id) OR (sender_id = u.id AND receiver_id = ?))
         AND ((sender_id = ? AND deleted_by_sender = 0) OR (receiver_id = ? AND deleted_by_receiver = 0))
         AND is_deleted_for_all = 0
         ORDER BY created_at DESC LIMIT 1) as last_message_time
    FROM users u
    WHERE u.id != ? AND u.status = 'approved'
    ORDER BY CASE WHEN last_message_time IS NULL THEN 1 ELSE 0 END, last_message_time DESC
");
$stmt->execute([
    $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'],
    $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'],
    $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'],
    $_SESSION['user_id']
]);
$chats = $stmt->fetchAll();

include 'includes/header.php';
?>

<div class="relative flex h-screen w-full flex-col overflow-hidden bg-background-light dark:bg-background-dark max-w-md mx-auto">
    <!-- Header -->
    <header class="flex items-center bg-background-light dark:bg-background-dark p-4 border-b border-slate-200 dark:border-slate-800 justify-between sticky top-0 z-10">
        <div class="flex items-center gap-3">
            <div class="text-primary flex size-10 items-center justify-center rounded-lg bg-primary/10">
                <span class="material-symbols-outlined">chat</span>
            </div>
            <div class="flex items-center justify-between p-4">
                <h1 class="text-xl font-bold text-slate-900 dark:text-slate-100">Chats</h1>
                <div class="flex items-center gap-2">
                    <?php if ($unreadAnnouncements > 0): ?>
                    <a href="announcements.php" class="relative flex size-10 items-center justify-center rounded-full bg-red-500 text-white">
                        <span class="material-symbols-outlined">campaign</span>
                        <span class="absolute -top-1 -right-1 size-4 bg-red-600 rounded-full text-[10px] flex items-center justify-center font-bold"><?php echo $unreadAnnouncements; ?></span>
                    </a>
                    <?php endif; ?>
                    <a href="search.php" class="flex size-10 items-center justify-center rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors">
                        <span class="material-symbols-outlined">search</span>
                    </a>
                    <button onclick="toggleDarkMode()" class="flex size-10 items-center justify-center rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors">
                        <span class="material-symbols-outlined" id="darkModeIcon"><?php echo isset($_COOKIE['darkMode']) && $_COOKIE['darkMode'] === 'true' ? 'light_mode' : 'dark_mode'; ?></span>
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- Filter Tabs -->
    <nav class="bg-background-light dark:bg-background-dark px-4 border-b border-slate-200 dark:border-slate-800">
        <div class="flex gap-6 overflow-x-auto no-scrollbar">
            <a class="flex flex-col items-center justify-center border-b-2 border-primary text-primary pb-3 pt-4 shrink-0" href="#">
                <p class="text-sm font-bold tracking-wide">All Chats</p>
            </a>
            <a class="flex flex-col items-center justify-center border-b-2 border-transparent text-slate-500 dark:text-slate-400 pb-3 pt-4 shrink-0" href="#">
                <p class="text-sm font-bold tracking-wide">Unread</p>
            </a>
            <a class="flex flex-col items-center justify-center border-b-2 border-transparent text-slate-500 dark:text-slate-400 pb-3 pt-4 shrink-0" href="#">
                <p class="text-sm font-bold tracking-wide">Groups</p>
            </a>
        </div>
    </nav>

    <!-- Chat List -->
    <main class="flex-1 overflow-y-auto">
        <?php if (empty($chats)): ?>
            <div class="flex flex-col items-center justify-center h-full text-center p-8">
                <div class="size-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-4">
                    <span class="material-symbols-outlined text-3xl text-slate-400">chat</span>
                </div>
                <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">No chats yet</h3>
                <p class="text-slate-500 dark:text-slate-400 mb-6">Start a conversation with someone</p>
                <a href="search.php" class="inline-flex items-center gap-2 bg-primary text-white px-6 py-3 rounded-lg hover:bg-primary/90 transition-colors font-medium">
                    <span class="material-symbols-outlined">person_search</span>
                    Find People
                </a>
            </div>
        <?php else: ?>
            <div class="divide-y divide-slate-100 dark:divide-slate-800">
                <?php foreach ($chats as $chat): ?>
                    <?php
                    // Calculate online status
                    $lastActivity = new DateTime($chat['last_activity'] ?: 'now');
                    $now = new DateTime();
                    $interval = $now->diff($lastActivity);
                    $isOnline = $interval->i < 2;
                    $isAway = $interval->i >= 2 && $interval->i < 5;
                    $statusColor = $isOnline ? '#10b981' : ($isAway ? '#f59e0b' : '#6b7280');
                    ?>
                    <a href="chat.php?user=<?php echo $chat['unique_id']; ?>" class="flex items-center gap-3 p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors block">
                        <div class="relative shrink-0">
                            <?php if ($chat['profile_photo']): ?>
                            <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full size-12 border-2 border-primary/20" style="background-image: url('uploads/images/<?php echo htmlspecialchars($chat['profile_photo']); ?>')"></div>
                            <?php else: ?>
                            <div class="size-12 rounded-full bg-primary/10 flex items-center justify-center border-2 border-primary/20">
                                <span class="material-symbols-outlined text-primary">person</span>
                            </div>
                            <?php endif; ?>
                            <div class="absolute bottom-0 right-0 size-3 bg-slate-400 rounded-full border-2 border-background-light dark:border-background-dark transition-colors" 
                                 style="background-color: <?php echo $statusColor; ?>;"></div>
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center justify-between mb-1">
                                <h3 class="font-semibold text-slate-900 dark:text-slate-100 truncate">
                                    <?php echo htmlspecialchars($chat['name']); ?>
                                </h3>
                                <?php if ($chat['last_message_time']): ?>
                                <span class="text-xs text-slate-500 dark:text-slate-400">
                                    <?php 
                                    $msgTime = new DateTime($chat['last_message_time'] ?: 'now');
                                    $now = new DateTime();
                                    $diff = $now->diff($msgTime);
                                    if ($diff->d > 0) {
                                        echo $msgTime->format('M j');
                                    } elseif ($diff->h > 0) {
                                        echo $diff->h . 'h ago';
                                    } elseif ($diff->i > 0) {
                                        echo $diff->i . 'm ago';
                                    } else {
                                        echo 'Just now';
                                    }
                                    ?>
                                </span>
                                <?php endif; ?>
                            </div>
                            <div class="flex items-center justify-between">
                                <p class="text-sm text-slate-600 dark:text-slate-400 truncate">
                                    <?php 
                                    if ($chat['last_message_type'] === 'image') {
                                        echo '📷 Photo';
                                    } elseif ($chat['last_message_type'] === 'video') {
                                        echo '🎥 Video';
                                    } elseif ($chat['last_message_type'] === 'gif') {
                                        echo '🎬 GIF';
                                    } elseif ($chat['last_message_type'] === 'voice') {
                                        echo '🎤 Voice';
                                    } else {
                                        echo htmlspecialchars(substr($chat['last_message'] ?? '', 0, 50));
                                    }
                                    ?>
                                </p>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </main>

    <!-- Bottom Navigation -->
    <nav class="flex items-center justify-around p-4 bg-background-light dark:bg-background-dark border-t border-slate-200 dark:border-slate-800">
        <a href="index.php" class="flex flex-col items-center gap-1 text-slate-500 dark:text-slate-400 hover:text-primary transition-colors">
            <span class="material-symbols-outlined">home</span>
            <span class="text-xs">Home</span>
        </a>
        <a href="chats.php" class="flex flex-col items-center gap-1 text-primary">
            <span class="material-symbols-outlined">chat</span>
            <span class="text-xs">Chats</span>
        </a>
        <a href="settings.php" class="flex flex-col items-center gap-1 text-slate-500 dark:text-slate-400 hover:text-primary transition-colors">
            <span class="material-symbols-outlined">settings</span>
            <span class="text-xs">Settings</span>
        </a>
    </nav>
</div>

<script>
// Auto-logout checker for all pages
function checkAutoLogout() {
    fetch('api/user-status.php')
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            if (!data.success && data.logged_out) {
                // Show logout message
                if (typeof showToast === 'function') {
                    showToast(data.message || 'You have been logged out due to inactivity', 'warning');
                }
                
                // Redirect to login page after 2 seconds
                setTimeout(function() {
                    window.location.href = data.redirect_to || 'login.php';
                }, 2000);
            }
        })
        .catch(function(error) {
            console.error('Error checking user status:', error);
        });
}

// Auto-logout checker - runs every 30 seconds
setInterval(checkAutoLogout, 30000);

// Check on page load
document.addEventListener('DOMContentLoaded', function() {
    checkAutoLogout();
});

// Update user activity on any interaction
document.addEventListener('mousemove', function() {
    if (!window.lastActivityUpdate || Date.now() - window.lastActivityUpdate > 30000) {
        fetch('api/user-status.php')
            .then(function(response) {
                return response.json();
            })
            .catch(function(error) {
                console.log('Activity update failed:', error);
            });
        window.lastActivityUpdate = Date.now();
    }
});

document.addEventListener('keydown', function() {
    if (!window.lastActivityUpdate || Date.now() - window.lastActivityUpdate > 30000) {
        fetch('api/user-status.php')
            .then(function(response) {
                return response.json();
            })
            .catch(function(error) {
                console.log('Activity update failed:', error);
            });
        window.lastActivityUpdate = Date.now();
    }
});

document.addEventListener('scroll', function() {
    if (!window.lastActivityUpdate || Date.now() - window.lastActivityUpdate > 30000) {
        fetch('api/user-status.php')
            .then(function(response) {
                return response.json();
            })
            .catch(function(error) {
                console.log('Activity update failed:', error);
            });
        window.lastActivityUpdate = Date.now();
    }
});
</script>

<?php include 'includes/footer.php'; ?>
