<?php
/**
 * ============================================================================
 * chat/index.php - Interactive Chat/Messaging Main Page
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Messages';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get user's chats
$chatClass = new \App\Chat($db);
$chats = $chatClass->getUserChats($userId);

// Get unread count
$messageClass = new \App\Message($db);
$unreadCount = $messageClass->getUnreadCount($userId);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
.chat-sidebar {
    height: calc(100vh - 120px);
    overflow-y: auto;
    border-right: 1px solid #dee2e6;
}

.chat-item {
    padding: 15px;
    cursor: pointer;
    border-bottom: 1px solid #f1f3f5;
    transition: background-color 0.2s;
}

.chat-item:hover {
    background-color: #f8f9fa;
}

.chat-item.active {
    background-color: #e7f3ff;
    border-left: 3px solid #0d6efd;
}

.chat-avatar {
    position: relative;
}

.online-badge {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 12px;
    height: 12px;
    background-color: #28a745;
    border: 2px solid white;
    border-radius: 50%;
}

.unread-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    min-width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #dc3545;
    color: white;
    border-radius: 10px;
    font-size: 0.75rem;
    font-weight: bold;
    padding: 0 5px;
}

.quick-actions {
    position: sticky;
    top: 0;
    background: white;
    z-index: 10;
    padding: 15px;
    border-bottom: 1px solid #dee2e6;
}

.status-indicator {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 5px;
}

.status-indicator.online {
    background-color: #28a745;
}

.status-indicator.offline {
    background-color: #6c757d;
}

.chat-type-badge {
    font-size: 0.7rem;
    padding: 2px 6px;
    border-radius: 3px;
}
</style>

<div class="container-fluid p-0">
    <div class="row g-0">
        <!-- Chat Sidebar -->
        <div class="col-md-4 col-lg-3 chat-sidebar">
            <!-- Quick Actions -->
            <div class="quick-actions">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">
                        <i class="bi bi-chat-dots text-primary"></i> Messages
                        <?php if ($unreadCount > 0): ?>
                            <span class="badge bg-danger"><?php echo $unreadCount; ?></span>
                        <?php endif; ?>
                    </h5>
                    <div class="dropdown">
                        <button class="btn btn-link text-dark" data-bs-toggle="dropdown">
                            <i class="bi bi-three-dots-vertical"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/groups/create.php">
                                <i class="bi bi-people me-2"></i>New Group
                            </a></li>
                            <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/friends/find-farmers.php">
                                <i class="bi bi-person-plus me-2"></i>New Chat
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/groups/">
                                <i class="bi bi-collection me-2"></i>My Groups
                            </a></li>
                        </ul>
                    </div>
                </div>
                
                <!-- Search -->
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-light border-0">
                        <i class="bi bi-search"></i>
                    </span>
                    <input type="text" 
                           class="form-control border-0 bg-light" 
                           id="searchChats"
                           placeholder="Search chats..."
                           onkeyup="filterChats()">
                </div>
            </div>

            <!-- Chat List -->
            <div id="chatList">
                <?php if (!empty($chats)): ?>
                    <?php foreach ($chats as $chat): ?>
                        <?php
                        // Determine the correct URL based on chat type
                        $chatUrl = ($chat['chat_type'] === 'group') 
                            ? APP_URL . '/groups/view.php?id=' . $chat['id']
                            : APP_URL . '/chat/one-on-one.php?chat_id=' . $chat['id'];
                        ?>
                        <div class="chat-item" 
                             data-chat-id="<?php echo $chat['id']; ?>"
                             data-chat-type="<?php echo $chat['chat_type']; ?>"
                             data-chat-name="<?php echo htmlspecialchars($chat['chat_name'] ?: 'Chat'); ?>"
                             onclick="window.location.href='<?php echo $chatUrl; ?>'">
                            <div class="d-flex align-items-start">
                                <div class="chat-avatar position-relative me-3">
                                    <img src="<?php echo getAvatarUrl($chat['chat_avatar']); ?>" 
                                         class="rounded-circle" 
                                         width="50" height="50"
                                         alt="<?php echo htmlspecialchars($chat['chat_name'] ?: 'Chat'); ?>">
                                    <?php if ($chat['unread_count'] > 0): ?>
                                        <span class="unread-badge"><?php echo $chat['unread_count']; ?></span>
                                    <?php endif; ?>
                                    <?php if ($chat['chat_type'] !== 'group'): ?>
                                        <span class="online-badge"></span>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <h6 class="mb-0 fw-bold">
                                            <?php echo htmlspecialchars($chat['chat_name'] ?: 'Chat'); ?>
                                            <?php if ($chat['chat_type'] === 'group'): ?>
                                                <i class="bi bi-people-fill text-primary small ms-1"></i>
                                            <?php else: ?>
                                                <i class="bi bi-person-fill text-success small ms-1"></i>
                                            <?php endif; ?>
                                        </h6>
                                        <small class="text-muted">
                                            <?php echo $chat['last_message_time'] ? timeAgo($chat['last_message_time']) : ''; ?>
                                        </small>
                                    </div>
                                    <p class="mb-0 small text-muted text-truncate" style="max-width: 200px;">
                                        <?php if ($chat['last_message']): ?>
                                            <?php if (strpos($chat['last_message'], '[Encrypted Message]') !== false): ?>
                                                <i class="bi bi-shield-lock-fill text-success me-1"></i>
                                                Encrypted message
                                            <?php else: ?>
                                                <?php echo truncate($chat['last_message'], 40); ?>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            No messages yet
                                        <?php endif; ?>
                                    </p>
                                    <!-- Chat Type Badge -->
                                    <span class="chat-type-badge badge <?php echo $chat['chat_type'] === 'group' ? 'bg-primary' : 'bg-success'; ?>">
                                        <?php echo $chat['chat_type'] === 'group' ? 'Group' : 'Direct'; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="text-center py-5 px-3">
                        <i class="bi bi-chat-dots text-muted" style="font-size: 4rem;"></i>
                        <h5 class="mt-3">No Conversations Yet</h5>
                        <p class="text-muted small">Start connecting with other farmers</p>
                        <div class="d-grid gap-2">
                            <a href="<?php echo APP_URL; ?>/friends/find-farmers.php" class="btn btn-sm btn-primary">
                                <i class="bi bi-person-plus"></i> Start Direct Chat
                            </a>
                            <a href="<?php echo APP_URL; ?>/groups/create.php" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-people"></i> Create Group
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="col-md-8 col-lg-9 d-none d-md-flex align-items-center justify-content-center bg-light">
            <div class="text-center py-5">
                <i class="bi bi-chat-dots-fill" style="font-size: 5rem; color: #dee2e6;"></i>
                <h4 class="mt-4 text-muted">Select a chat to start messaging</h4>
                <p class="text-muted">Choose from your existing conversations or start a new one</p>
                
                <div class="mt-4">
                    <a href="<?php echo APP_URL; ?>/groups/create.php" class="btn btn-outline-primary me-2">
                        <i class="bi bi-people"></i> Create Group
                    </a>
                    <a href="<?php echo APP_URL; ?>/friends/find-farmers.php" class="btn btn-primary">
                        <i class="bi bi-person-plus"></i> New Chat
                    </a>
                </div>
                
                <!-- Quick Links -->
                <div class="row mt-5 text-start justify-content-center">
                    <div class="col-md-6 col-lg-4">
                        <div class="card border-0 shadow-sm mb-3">
                            <div class="card-body">
                                <h6><i class="bi bi-collection text-primary me-2"></i>Groups</h6>
                                <p class="small text-muted mb-2">Join or create farming discussion groups</p>
                                <a href="<?php echo APP_URL; ?>/groups/" class="btn btn-sm btn-outline-primary">
                                    View Groups
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4">
                        <div class="card border-0 shadow-sm mb-3">
                            <div class="card-body">
                                <h6><i class="bi bi-person text-success me-2"></i>Friends</h6>
                                <p class="small text-muted mb-2">Connect with other farmers</p>
                                <a href="<?php echo APP_URL; ?>/friends/" class="btn btn-sm btn-outline-success">
                                    Find Farmers
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
function filterChats() {
    const searchTerm = document.getElementById('searchChats').value.toLowerCase();
    const chatItems = document.querySelectorAll('.chat-item');
    
    chatItems.forEach(item => {
        const chatName = item.dataset.chatName.toLowerCase();
        if (chatName.includes(searchTerm)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

// Auto-refresh chat list every 30 seconds
setInterval(function() {
    location.reload();
}, 30000);
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>