<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/Auth.php';

$db = Database::getInstance();
$auth = new Auth($db);

// Check if user is logged in
if (!$auth->isLoggedIn()) {
    header('Location: login.php');
    exit();
}

$user = $auth->getCurrentUser();
$userId = $user['id'];

// Get or create chat for this user
$existingChat = $db->fetch(
    "SELECT id FROM chatbot_chats WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
    [$userId]
);

$chatId = $existingChat ? $existingChat['id'] : null;

// Create new chat if doesn't exist
if (!$chatId) {
    $chatId = $db->insert('chatbot_chats', [
        'user_id' => $userId,
        'status' => 'active',
        'created_at' => date('Y-m-d H:i:s')
    ]);
}

// Handle sending message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    header('Content-Type: application/json');
    
    $message = trim($_POST['message'] ?? '');
    
    if (empty($message)) {
        echo json_encode(['success' => false]);
        exit();
    }
    
    try {
        $db->insert('chatbot_messages', [
            'chat_id' => $chatId,
            'sender_id' => $userId,
            'message' => $message,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit();
}

// Get messages
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['get_messages'])) {
    header('Content-Type: application/json');
    
    $messages = $db->fetchAll(
        "SELECT m.*, u.name as sender_name
         FROM chatbot_messages m
         LEFT JOIN users u ON u.id = m.sender_id
         WHERE m.chat_id = ?
         ORDER BY m.created_at ASC",
        [$chatId]
    ) ?: [];
    
    echo json_encode($messages);
    exit();
}

// Get existing messages
$messages = $db->fetchAll(
    "SELECT m.*, u.name as sender_name
     FROM chatbot_messages m
     LEFT JOIN users u ON u.id = m.sender_id
     WHERE m.chat_id = ?
     ORDER BY m.created_at ASC",
    [$chatId]
) ?: [];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat with Admin - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }

        .chat-container {
            width: 100%;
            max-width: 600px;
            height: 80vh;
            max-height: 600px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            font-weight: 600;
            text-align: center;
            border-bottom: 1px solid #5568d3;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            background: #f8f9fa;
        }

        .message {
            display: flex;
            margin-bottom: 12px;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-bubble {
            max-width: 70%;
            padding: 10px 14px;
            border-radius: 18px;
            word-wrap: break-word;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .message.user .message-bubble {
            background: #667eea;
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.admin .message-bubble {
            background: #e9ecef;
            color: #000;
            border-bottom-left-radius: 4px;
        }

        .message-time {
            font-size: 11px;
            color: #999;
            margin-top: 4px;
            text-align: right;
        }

        .message.admin .message-time {
            text-align: left;
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #999;
            text-align: center;
        }

        .chat-footer {
            padding: 15px 20px;
            border-top: 1px solid #e5e5e5;
            background: white;
            display: flex;
            gap: 10px;
        }

        .chat-footer input {
            flex: 1;
            padding: 10px 14px;
            border: 1px solid #ddd;
            border-radius: 20px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.2s;
        }

        .chat-footer input:focus {
            border-color: #667eea;
        }

        .chat-footer button {
            background: #667eea;
            color: white;
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 18px;
            transition: all 0.2s;
        }

        .chat-footer button:hover {
            background: #5568d3;
            transform: scale(1.05);
        }

        @media (max-width: 600px) {
            .chat-container {
                max-width: 100%;
                height: 90vh;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <!-- Header -->
        <div class="chat-header">
            💬 Chat with Admin
        </div>

        <!-- Messages -->
        <div class="chat-messages" id="messagesContainer">
            <?php if (empty($messages)): ?>
                <div class="empty-state">
                    <p style="font-size: 14px; color: #bbb;">👋 Start the conversation!</p>
                    <small>Type a message below to chat with admin</small>
                </div>
            <?php else: ?>
                <?php foreach ($messages as $msg): ?>
                    <div class="message <?= ($msg['sender_id'] == 1) ? 'admin' : 'user' ?>">
                        <div>
                            <div class="message-bubble">
                                <?= nl2br(htmlspecialchars($msg['message'])) ?>
                            </div>
                            <div class="message-time">
                                <?= date('M d, H:i', strtotime($msg['created_at'])) ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Input -->
        <div class="chat-footer">
            <input type="text" id="messageInput" placeholder="Type a message..." autocomplete="off">
            <button onclick="sendMessage()" type="button">➤</button>
        </div>
    </div>

    <script>
        const chatId = <?= $chatId ?>;

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();

            if (!message) return;

            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'message=' + encodeURIComponent(message)
            })
            .then(res => res.json())
            .then(result => {
                if (result.success) {
                    input.value = '';
                    loadMessages();
                } else {
                    console.error('Failed to send:', result.error);
                }
            })
            .catch(err => console.error('Error:', err));
        }

        function loadMessages() {
            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'get_messages=1'
            })
            .then(res => res.json())
            .then(messages => {
                const container = document.getElementById('messagesContainer');
                container.innerHTML = '';

                if (messages.length === 0) {
                    container.innerHTML = '<div class="empty-state"><p style="font-size: 14px; color: #bbb;">👋 Start the conversation!</p><small>Type a message below to chat with admin</small></div>';
                    return;
                }

                messages.forEach(msg => {
                    const isAdmin = msg.sender_id == 1;
                    // Convert MySQL datetime format to ISO format
                    const dateStr = msg.created_at.replace(' ', 'T');
                    const time = new Date(dateStr).toLocaleString('en-US', {
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: true
                    });

                    const msgHtml = `
                        <div class="message ${isAdmin ? 'admin' : 'user'}">
                            <div>
                                <div class="message-bubble">
                                    ${msg.message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}
                                </div>
                                <div class="message-time">${time}</div>
                            </div>
                        </div>
                    `;
                    container.innerHTML += msgHtml;
                });

                container.scrollTop = container.scrollHeight;
            })
            .catch(err => console.error('Error:', err));
        }

        // Auto-refresh messages every 500ms for near real-time experience
        let lastMessageCount = 0;
        setInterval(() => {
            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'get_messages=1'
            })
            .then(res => res.json())
            .then(messages => {
                if (messages.length !== lastMessageCount) {
                    lastMessageCount = messages.length;
                    loadMessages();
                }
            })
            .catch(err => console.error('Error:', err));
        }, 500);

        // Enter to send
        document.getElementById('messageInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                sendMessage();
            }
        });

        // Initial scroll
        window.addEventListener('load', () => {
            setTimeout(() => {
                document.getElementById('messagesContainer').scrollTop = document.getElementById('messagesContainer').scrollHeight;
            }, 100);
        });
    </script>
</body>
</html>
