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

// Check if user is authenticated
if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

$pageTitle = 'Home';
$activePage = 'home';

$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 recent chats preview
$stmt = $db->prepare("
    SELECT u.id, u.unique_id, u.name, u.profile_photo, u.last_seen,
        u.last_activity, u.status,
        (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 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
    LIMIT 5
");
$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']
]);
$recentChats = $stmt->fetchAll();

// Get chat statistics
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_messages,
        COUNT(DISTINCT CASE WHEN sender_id = ? THEN receiver_id WHEN receiver_id = ? THEN sender_id END) as total_chats
    FROM messages 
    WHERE ((sender_id = ? OR receiver_id = ?) 
    AND deleted_by_sender = 0 AND deleted_by_receiver = 0 AND is_deleted_for_all = 0)
");
$stmt->execute([$_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id']]);
$stats = $stmt->fetch();

include 'includes/header.php';
?>

<div class="min-h-screen bg-background-light dark:bg-background-dark">
    <div class="max-w-md mx-auto">
        <!-- Header -->
        <header class="bg-background-light dark:bg-background-dark p-4 border-b border-slate-200 dark:border-slate-800">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Welcome back!</h1>
                    <p class="text-slate-600 dark:text-slate-400">What would you like to do today?</p>
                </div>
                <div class="text-primary flex size-12 items-center justify-center rounded-full bg-primary/10">
                    <span class="material-symbols-outlined text-2xl">home</span>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="p-4 space-y-6">
            <!-- Quick Actions -->
            <div class="grid grid-cols-2 gap-4">
                <a href="chats.php" class="flex items-center gap-3 p-4 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary transition-colors">
                    <div class="size-10 rounded-full bg-blue-100 dark:bg-blue-900/20 flex items-center justify-center">
                        <span class="material-symbols-outlined text-blue-600">chat</span>
                    </div>
                    <div>
                        <p class="font-medium text-slate-900 dark:text-white text-sm">My Chats</p>
                        <p class="text-xs text-slate-500"><?php echo $unreadCount; ?> unread</p>
                    </div>
                </a>
                <a href="search.php" class="flex items-center gap-3 p-4 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary transition-colors">
                    <div class="size-10 rounded-full bg-green-100 dark:bg-green-900/20 flex items-center justify-center">
                        <span class="material-symbols-outlined text-green-600">search</span>
                    </div>
                    <div>
                        <p class="font-medium text-slate-900 dark:text-white text-sm">Find People</p>
                        <p class="text-xs text-slate-500">Discover users</p>
                    </div>
                </a>
                <a href="settings.php" class="flex items-center gap-3 p-4 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary transition-colors">
                    <div class="size-10 rounded-full bg-orange-100 dark:bg-orange-900/20 flex items-center justify-center">
                        <span class="material-symbols-outlined text-orange-600">settings</span>
                    </div>
                    <div>
                        <p class="font-medium text-slate-900 dark:text-white text-sm">Settings</p>
                        <p class="text-xs text-slate-500">App settings</p>
                    </div>
                </a>
                <a href="profile.php" class="flex items-center gap-3 p-4 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary transition-colors">
                    <div class="size-10 rounded-full bg-purple-100 dark:bg-purple-900/20 flex items-center justify-center">
                        <span class="material-symbols-outlined text-purple-600">person</span>
                    </div>
                    <div>
                        <p class="font-medium text-slate-900 dark:text-white text-sm">Profile</p>
                        <p class="text-xs text-slate-500">My profile</p>
                    </div>
                </a>
            </div>

            <!-- Statistics -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">Your Activity</h2>
                <div class="grid grid-cols-2 gap-4">
                    <div class="text-center p-4 bg-slate-50 dark:bg-slate-700 rounded-lg">
                        <div class="text-2xl font-bold text-primary"><?php echo $stats['total_messages']; ?></div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">Messages</div>
                    </div>
                    <div class="text-center p-4 bg-slate-50 dark:bg-slate-700 rounded-lg">
                        <div class="text-2xl font-bold text-primary"><?php echo $stats['total_chats']; ?></div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">Chats</div>
                    </div>
                </div>
            </div>

            <!-- Recent Chats -->
            <?php if (!empty($recentChats)): ?>
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">Recent Chats</h2>
                <div class="space-y-3">
                    <?php foreach ($recentChats 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-3 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors">
                            <div class="relative shrink-0">
                                <?php if ($chat['profile_photo']): ?>
                                <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full size-10 border-2 border-slate-200 dark:border-slate-700" style="background-image: url('uploads/images/<?php echo htmlspecialchars($chat['profile_photo']); ?>')"></div>
                                <?php else: ?>
                                <div class="size-10 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center">
                                    <span class="material-symbols-outlined text-sm text-slate-500 dark:text-slate-400">person</span>
                                </div>
                                <?php endif; ?>
                                <div class="absolute bottom-0 right-0 size-2.5 bg-slate-400 rounded-full border-2 border-white dark:border-slate-800" 
                                     style="background-color: <?php echo $statusColor; ?>;"></div>
                            </div>
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center justify-between">
                                    <h3 class="font-medium 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>
                                <p class="text-sm text-slate-600 dark:text-slate-400 truncate">
                                    <?php echo htmlspecialchars(substr($chat['last_message'] ?? '', 0, 40)); ?>
                                </p>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
                <div class="mt-4">
                    <a href="chats.php" class="text-primary text-sm font-medium hover:text-primary/80 transition-colors">
                        View all chats →
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </main>

        <!-- Bottom Navigation -->
        <nav class="fixed bottom-0 left-0 right-0 bg-background-light dark:bg-background-dark border-t border-slate-200 dark:border-slate-800">
            <div class="max-w-md mx-auto flex items-center justify-around p-4">
                <a href="index.php" class="flex flex-col items-center gap-1 text-primary">
                    <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-slate-500 dark:text-slate-400 hover:text-primary transition-colors">
                    <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>
            </div>
        </nav>
    </div>
</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'; ?>
