<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/chat.php';

// Set page title
$meta = [
    'title' => 'Live Chat Support - Go Legal',
    'description' => 'Chat with our support team for instant assistance with your business registration needs.'
];

// Ensure user is authenticated or has guest ID
if (!$user && empty($_SESSION['guest_id'])) {
    get_or_create_guest_id(); // This will create and set guest ID
}

// Get user/guest info
$userId = $user['id'] ?? null;
$guestId = $_SESSION['guest_id'] ?? null;

// Get or create chat thread
$threadId = get_or_create_thread($pdo, $userId, $guestId);

// Get recent messages for this thread
$messages = [];
if ($threadId) {
    $stmt = $pdo->prepare("
        SELECT cm.*, u.first_name, u.last_name 
        FROM chat_messages cm 
        LEFT JOIN users u ON cm.sender_id = u.id 
        WHERE cm.thread_id = ? 
        ORDER BY cm.created_at ASC 
        LIMIT 50
    ");
    $stmt->execute([$threadId]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Decrypt message bodies
    foreach ($messages as &$message) {
        $message['body'] = decrypt_chat_msg($message['body']);
        $message['sender_name'] = $message['is_admin'] ? 'Support' : 
            (($message['sender_id'] == $userId) ? 'You' : 'Guest');
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="page-header">
    <h1>Live Chat Support</h1>
    <p>Get instant help from our support team. We're here to assist you with any questions about your business registration.</p>
</div>

<div class="chat-container">
    <div class="chat-messages" id="chat-messages">
        <?php if (empty($messages)): ?>
            <div class="system-message">
                Welcome to Go Legal Live Chat! How can we help you today?
            </div>
        <?php else: ?>
            <?php foreach ($messages as $message): ?>
                <div class="chat-message <?= $message['sender_id'] == $userId ? 'sent' : 'received' ?>">
                    <div class="message-content">
                        <div class="sender-info"><?= $message['sender_name'] ?></div>
                        <div class="message-text"><?= htmlspecialchars($message['body']) ?></div>
                        <div class="message-time"><?= date('h:i A', strtotime($message['created_at'])) ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <form class="chat-input-form" id="chat-form">
        <input type="text" id="message-input" placeholder="Type your message..." autocomplete="off">
        <button type="submit">Send</button>
    </form>
</div>

<style>
.chat-container {
    max-width: 800px;
    margin: 0 auto;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.chat-messages {
    height: 400px;
    overflow-y: auto;
    padding: 20px;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
}

.chat-message {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-start;
}

.chat-message.sent {
    justify-content: flex-end;
}

.message-content {
    max-width: 70%;
    background: white;
    padding: 12px 16px;
    border-radius: 12px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.chat-message.sent .message-content {
    background: #10b981;
    color: white;
}

.sender-info {
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 4px;
    color: #64748b;
}

.chat-message.sent .sender-info {
    color: rgba(255, 255, 255, 0.8);
}

.message-text {
    margin-bottom: 4px;
    line-height: 1.4;
}

.message-time {
    font-size: 11px;
    opacity: 0.7;
}

.system-message {
    text-align: center;
    padding: 12px;
    background: #f1f5f9;
    border-radius: 8px;
    color: #64748b;
    font-style: italic;
    margin-bottom: 16px;
}

.chat-input-form {
    display: flex;
    padding: 16px;
    background: white;
    gap: 12px;
}

.chat-input-form input {
    flex: 1;
    padding: 12px 16px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 14px;
    outline: none;
}

.chat-input-form input:focus {
    border-color: #10b981;
}

.chat-input-form button {
    background: #10b981;
    color: white;
    border: none;
    padding: 12px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 600;
    transition: background 0.2s;
}

.chat-input-form button:hover {
    background: #059669;
}

@media (max-width: 640px) {
    .chat-container {
        margin: 0 16px;
        border-radius: 0;
    }
    
    .message-content {
        max-width: 85%;
    }
}
</style>

<script>
// Chat functionality
document.addEventListener('DOMContentLoaded', function() {
    const chatMessages = document.getElementById('chat-messages');
    const chatForm = document.getElementById('chat-form');
    const messageInput = document.getElementById('message-input');
    
    // Scroll to bottom
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    // Handle form submission
    chatForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const message = messageInput.value.trim();
        if (!message) return;
        
        // Add message to UI immediately (optimistic update)
        addMessageToUI('You', message, 'sent', new Date().toISOString());
        
        // Clear input
        messageInput.value = '';
        
        // Send to server
        try {
            const response = await fetch('/api/save_chat_message.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message_body: message
                })
            });
            
            const result = await response.json();
            if (!result.success) {
                console.error('Failed to send message:', result.error);
            }
        } catch (error) {
            console.error('Error sending message:', error);
        }
    });
    
    function addMessageToUI(sender, text, type, timestamp) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${type}`;
        
        messageDiv.innerHTML = `
            <div class="message-content">
                <div class="sender-info">${sender}</div>
                <div class="message-text">${text}</div>
                <div class="message-time">${new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</div>
            </div>
        `;
        
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
});
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
