<?php
/**
 * ============================================================================
 * chat/index.php - FIXED with SweetAlert Integration
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

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

// Get database connection using Singleton pattern
$database = \App\Database::getInstance();
$db = $database->getConnection();

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

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

// Get online friends
$onlineFriends = $chatClass->getOnlineFriends($userId);

// Check if user has encryption keys
$keyCheckSql = "SELECT id FROM user_encryption_keys WHERE user_id = ?";
$stmt = $db->prepare($keyCheckSql);
$stmt->execute([$userId]);
$hasEncryptionKeys = $stmt->fetch() ? true : false;

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

<style>
body {
    background: #f0f2f5;
}

.messages-container {
    background: white;
    min-height: calc(100vh - 60px);
}

.messages-header {
    position: sticky;
    top: 0;
    background: white;
    z-index: 100;
    padding: 12px 16px;
    border-bottom: 1px solid #e4e6eb;
}

.messages-title {
    font-size: 1.5rem;
    font-weight: 700;
    color: #050505;
    margin-bottom: 0;
}

.header-actions {
    display: flex;
    gap: 8px;
}

.header-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: #e4e6eb;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #050505;
    cursor: pointer;
    transition: background 0.2s;
}

.header-btn:hover {
    background: #d8dadf;
}

.encryption-warning {
    background: #fff3cd;
    border-left: 4px solid #ffc107;
    padding: 12px 16px;
    margin: 8px 16px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.encryption-warning i {
    font-size: 1.5rem;
    color: #ffc107;
}

.encryption-warning-content {
    flex: 1;
}

.encryption-warning h6 {
    margin: 0 0 4px 0;
    font-size: 0.9rem;
    font-weight: 600;
    color: #856404;
}

.encryption-warning p {
    margin: 0;
    font-size: 0.85rem;
    color: #856404;
}

.btn-setup-encryption {
    background: #ffc107;
    color: #000;
    border: none;
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    white-space: nowrap;
}

.btn-setup-encryption:hover {
    background: #e0a800;
}

.search-section {
    padding: 8px 16px;
    background: white;
    border-bottom: 1px solid #e4e6eb;
}

.search-input {
    width: 100%;
    padding: 8px 12px 8px 36px;
    border: none;
    border-radius: 20px;
    background: #f0f2f5;
    font-size: 0.9rem;
}

.search-input:focus {
    outline: none;
    background: #e4e6eb;
}

.search-icon {
    position: absolute;
    left: 28px;
    top: 50%;
    transform: translateY(-50%);
    color: #65676b;
}

.stories-section {
    padding: 12px 16px;
    background: white;
    border-bottom: 1px solid #e4e6eb;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    scrollbar-width: none;
}

.stories-section::-webkit-scrollbar {
    display: none;
}

.stories-list {
    display: inline-flex;
    gap: 12px;
}

.story-item {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    flex-shrink: 0;
}

.story-avatar {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #1877f2;
    background: #f0f2f5;
}

.story-online-badge {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 16px;
    height: 16px;
    background: #31a24c;
    border: 3px solid white;
    border-radius: 50%;
}

.story-name {
    font-size: 0.75rem;
    color: #050505;
    max-width: 60px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.chats-list {
    overflow-y: auto;
    height: calc(100vh - 280px);
}

.chat-item {
    padding: 12px 16px;
    cursor: pointer;
    transition: background 0.2s;
    position: relative;
}

.chat-item:hover {
    background: #f2f3f5;
}

.chat-item.unread {
    background: #f0f8ff;
}

.chat-preview {
    display: flex;
    align-items: center;
    gap: 12px;
}

.chat-avatar-wrapper {
    position: relative;
    flex-shrink: 0;
}

.chat-avatar {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    object-fit: cover;
    background: #e4e6eb;
}

.online-dot {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 14px;
    height: 14px;
    background: #31a24c;
    border: 3px solid white;
    border-radius: 50%;
}

.unread-indicator {
    position: absolute;
    top: -2px;
    right: -2px;
    min-width: 20px;
    height: 20px;
    background: #e41e3f;
    color: white;
    border-radius: 10px;
    font-size: 0.7rem;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 6px;
}

.chat-info {
    flex: 1;
    min-width: 0;
}

.chat-name {
    font-size: 0.95rem;
    font-weight: 500;
    color: #050505;
    margin-bottom: 2px;
}

.chat-item.unread .chat-name {
    font-weight: 700;
}

.last-message {
    font-size: 0.85rem;
    color: #65676b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.chat-item.unread .last-message {
    color: #050505;
    font-weight: 600;
}

.chat-meta {
    text-align: right;
    flex-shrink: 0;
}

.chat-time {
    font-size: 0.75rem;
    color: #65676b;
    margin-bottom: 4px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}

.empty-state i {
    font-size: 4rem;
    color: #bcc0c4;
    margin-bottom: 16px;
}

.fab-new-message {
    position: fixed;
    bottom: 80px;
    right: 20px;
    width: 56px;
    height: 56px;
    background: #1877f2;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    cursor: pointer;
    transition: all 0.3s;
    z-index: 1000;
}

.fab-new-message:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 16px rgba(0,0,0,0.2);
}

@media (max-width: 768px) {
    .fab-new-message {
        bottom: 100px;
    }
}
</style>

<div class="messages-container">
    <!-- Header -->
    <div class="messages-header">
        <div class="d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center gap-2">
                <a href="<?php echo APP_URL; ?>/dashboard.php" class="btn btn-link text-dark p-0 d-md-none">
                    <i class="bi bi-arrow-left" style="font-size: 1.4rem;"></i>
                </a>
                <h1 class="messages-title">Messages</h1>
            </div>
            <div class="header-actions">
                <button class="header-btn" title="Settings">
                    <i class="bi bi-gear-fill"></i>
                </button>
                <button class="header-btn" title="New message" onclick="window.location.href='<?php echo APP_URL; ?>/friends/find-users.php'">
                    <i class="bi bi-pencil-square"></i>
                </button>
                <button class="header-btn" title="Search">
                    <i class="bi bi-search"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Encryption Warning (if user doesn't have keys) -->
    <?php if (!$hasEncryptionKeys): ?>
    <div class="encryption-warning">
        <i class="bi bi-shield-exclamation"></i>
        <div class="encryption-warning-content">
            <h6>End-to-End Encryption Not Set Up</h6>
            <p>Set up encryption to send secure messages that only you and the recipient can read.</p>
        </div>
        <button class="btn-setup-encryption" onclick="setupEncryption()">
            Setup Now
        </button>
    </div>
    <?php endif; ?>

    <!-- Search -->
    <div class="search-section">
        <div class="position-relative">
            <i class="bi bi-search search-icon"></i>
            <input type="text" 
                   class="search-input" 
                   id="searchChats"
                   placeholder="Search Messenger"
                   onkeyup="filterChats()">
        </div>
    </div>

    <!-- Online Friends Section -->
    <div class="stories-section">
        <div class="stories-list">
            <?php if (!empty($onlineFriends)): ?>
                <?php foreach ($onlineFriends as $friend): ?>
                    <div class="story-item" onclick="openChatByFriendId(<?php echo $friend['id']; ?>)">
                        <div class="story-avatar-wrapper position-relative">
                            <img src="<?php echo getAvatarUrl($friend['profile_picture']); ?>" 
                                 class="story-avatar"
                                 alt="<?php echo htmlspecialchars($friend['full_name']); ?>">
                            <span class="story-online-badge"></span>
                        </div>
                        <span class="story-name"><?php echo htmlspecialchars(explode(' ', $friend['full_name'])[0]); ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="text-muted mb-0">No friends online</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Chat List -->
    <div class="chats-list" id="chatList">
        <?php if (!empty($chats)): ?>
            <?php foreach ($chats as $chat): ?>
                <?php
                $isUnread = $chat['unread_count'] > 0;
                $isOnline = false;
                if (!empty($chat['friend_last_activity'])) {
                    $isOnline = (strtotime($chat['friend_last_activity']) > strtotime('-5 minutes'));
                }
                ?>
                <div class="chat-item <?php echo $isUnread ? 'unread' : ''; ?>" 
                     data-chat-id="<?php echo $chat['id']; ?>"
                     data-friend-id="<?php echo $chat['friend_id']; ?>"
                     data-chat-name="<?php echo htmlspecialchars($chat['chat_name']); ?>"
                     onclick="openChatById(<?php echo $chat['id']; ?>)">
                    <div class="chat-preview">
                        <div class="chat-avatar-wrapper">
                            <img src="<?php echo getAvatarUrl($chat['chat_avatar']); ?>" 
                                 class="chat-avatar"
                                 alt="<?php echo htmlspecialchars($chat['chat_name']); ?>"
                                 onerror="this.src='<?php echo APP_URL; ?>/assets/images/default-avatar.png'">
                            <?php if ($isOnline): ?>
                                <span class="online-dot"></span>
                            <?php endif; ?>
                            <?php if ($chat['unread_count'] > 0): ?>
                                <span class="unread-indicator"><?php echo $chat['unread_count']; ?></span>
                            <?php endif; ?>
                        </div>
                        
                        <div class="chat-info">
                            <div class="chat-name">
                                <?php echo htmlspecialchars($chat['chat_name']); ?>
                            </div>
                            <div class="last-message">
                                <?php if ($chat['last_message']): ?>
                                    <?php if (!empty($chat['last_message_encrypted'])): ?>
                                        <i class="bi bi-shield-lock-fill text-success"></i>
                                        <span class="text-muted">Encrypted message</span>
                                    <?php else: ?>
                                        <?php if ($chat['last_sender_id'] == $userId): ?>
                                            <span style="color: #050505;">You: </span>
                                        <?php endif; ?>
                                        <?php echo htmlspecialchars(substr($chat['last_message'], 0, 35)) . (strlen($chat['last_message']) > 35 ? '...' : ''); ?>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted">Start a conversation</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="chat-meta">
                            <?php if (!empty($chat['last_message_time'])): ?>
                                <div class="chat-time"><?php echo timeAgo($chat['last_message_time']); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="bi bi-chat-dots"></i>
                <h5 class="mt-3" style="color: #65676b;">No messages yet</h5>
                <p class="text-muted">Start connecting with other farmers</p>
                <a href="<?php echo APP_URL; ?>/friends/find-users.php" class="btn btn-primary mt-3">
                    <i class="bi bi-person-plus"></i> Find Friends
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Floating Action Button for New Message -->
<div class="fab-new-message" onclick="window.location.href='<?php echo APP_URL; ?>/friends/find-users.php'">
    <i class="bi bi-pencil-fill"></i>
</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();
        const lastMessage = item.querySelector('.last-message').textContent.toLowerCase();
        
        if (chatName.includes(searchTerm) || lastMessage.includes(searchTerm)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

// FIXED: Use chat ID from data attribute, not index
function openChatById(chatId) {
    console.log('Opening chat ID:', chatId);
    window.location.href = '<?php echo APP_URL; ?>/chat/one-on-one.php?chat_id=' + chatId;
}

// FIXED: Open chat by friend ID (creates new chat if doesn't exist)
function openChatByFriendId(friendId) {
    console.log('Opening chat with friend ID:', friendId);
    window.location.href = '<?php echo APP_URL; ?>/chat/one-on-one.php?friend_id=' + friendId;
}

function setupEncryption() {
    Swal.fire({
        title: '<i class="bi bi-shield-lock-fill text-success"></i> Setup End-to-End Encryption',
        html: `
            <div class="text-start">
                <div class="alert alert-info mb-3">
                    <i class="bi bi-info-circle"></i>
                    <strong>What is End-to-End Encryption?</strong>
                    <p class="mb-0 mt-2 small">Your messages will be encrypted so that only you and the recipient can read them. Not even system administrators can access your encrypted messages.</p>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Create Encryption Password</label>
                    <input type="password" id="encryptionPassword" class="form-control" 
                           placeholder="Enter a strong password" minlength="8">
                    <small class="text-muted">This password protects your encryption keys. Don't forget it!</small>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Confirm Password</label>
                    <input type="password" id="encryptionPasswordConfirm" class="form-control" 
                           placeholder="Re-enter your password">
                </div>
                
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="agreeBackup">
                    <label class="form-check-label small" for="agreeBackup">
                        I understand that if I lose this password, I won't be able to decrypt my old messages
                    </label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: '<i class="bi bi-shield-check"></i> Setup Encryption',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        width: '600px',
        preConfirm: () => {
            const password = document.getElementById('encryptionPassword').value;
            const passwordConfirm = document.getElementById('encryptionPasswordConfirm').value;
            const agreeBackup = document.getElementById('agreeBackup').checked;
            
            // Validation
            if (!password || password.length < 8) {
                Swal.showValidationMessage('Password must be at least 8 characters long');
                return false;
            }
            
            if (password !== passwordConfirm) {
                Swal.showValidationMessage('Passwords do not match');
                return false;
            }
            
            if (!agreeBackup) {
                Swal.showValidationMessage('Please confirm that you understand the backup warning');
                return false;
            }
            
            return { password: password };
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            completeEncryptionSetup(result.value.password);
        }
    });
}

function completeEncryptionSetup(password) {
    // Show loading
    Swal.fire({
        title: 'Generating Encryption Keys',
        html: '<div class="spinner-border text-primary" role="status"></div><p class="mt-3">Please wait...</p>',
        allowOutsideClick: false,
        allowEscapeKey: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Generate encryption keys
    $.ajax({
        url: '<?php echo APP_URL; ?>/chat/ajax/generate-keys.php',
        type: 'POST',
        data: {
            password: password
        },
        dataType: 'json',
        success: function(response) {
            console.log('Generate keys response:', response);
            
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Encryption Setup Complete!',
                    html: `
                        <p>Your encryption keys have been generated successfully.</p>
                        <p class="small text-muted mb-0">You can now send secure, end-to-end encrypted messages.</p>
                    `,
                    confirmButtonText: 'Got it!',
                    confirmButtonColor: '#28a745'
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Setup Failed',
                    text: response.message || 'Failed to setup encryption. Please try again.',
                    confirmButtonText: 'Try Again',
                    confirmButtonColor: '#dc3545'
                }).then(() => {
                    setupEncryption(); // Retry
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', {xhr, status, error});
            console.error('Response text:', xhr.responseText);
            
            let errorMessage = 'An error occurred while setting up encryption.';
            
            try {
                const response = JSON.parse(xhr.responseText);
                errorMessage = response.message || errorMessage;
            } catch(e) {
                errorMessage += ' Please check the browser console for details.';
            }
            
            Swal.fire({
                icon: 'error',
                title: 'Setup Failed',
                html: `<p>${errorMessage}</p><p class="small text-muted">Error: ${error}</p>`,
                confirmButtonText: 'Try Again',
                confirmButtonColor: '#dc3545'
            }).then(() => {
                setupEncryption(); // Retry
            });
        }
    });
}

// Update last activity every 30 seconds
setInterval(function() {
    $.post('<?php echo APP_URL; ?>/ajax/update-activity.php');
}, 30000);
</script>

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