<?php
ob_start();
require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';

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

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

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

// Handle sending message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    ob_clean();
    header('Content-Type: application/json');
    
    $message = trim($_POST['message'] ?? '');
    $ticketId = intval($_POST['ticket_id'] ?? 0);
    
    if (empty($message)) {
        echo json_encode(['success' => false]);
        exit();
    }
    
    if ($ticketId <= 0) {
        echo json_encode(['success' => false]);
        exit();
    }
    
    try {
        $escaped_msg = addslashes($message);
        $sql = "INSERT INTO support_messages (ticket_id, sender_id, message, created_at) 
                VALUES ($ticketId, $userId, '$escaped_msg', NOW())";
        
        $db->query($sql);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false]);
    }
    exit();
}

// Handle fetching messages
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['get_messages'])) {
    ob_clean();
    header('Content-Type: application/json');
    
    $ticketId = intval($_POST['ticket_id'] ?? 0);
    
    if ($ticketId <= 0) {
        echo json_encode([]);
        exit();
    }
    
    $sql = "SELECT m.id, m.sender_id, m.message, m.created_at, u.name as sender_name
            FROM support_messages m
            LEFT JOIN users u ON u.id = m.sender_id
            WHERE m.ticket_id = $ticketId
            ORDER BY m.created_at ASC";
    
    $messages = $db->fetchAll($sql) ?: [];
    echo json_encode($messages);
    exit();
}

// Create or get ticket
$sql = "SELECT id FROM support_tickets WHERE user_id = $userId LIMIT 1";
$result = $db->fetchAll($sql);

$ticketId = null;
if ($result && count($result) > 0) {
    $ticketId = $result[0]['id'];
} else {
    $sql = "INSERT INTO support_tickets (user_id, title, body, status, created_at, updated_at) 
            VALUES ($userId, 'Support', 'Support Chat', 'open', NOW(), NOW())";
    $db->query($sql);
    
    $result = $db->fetchAll("SELECT id FROM support_tickets WHERE user_id = $userId LIMIT 1");
    if ($result && count($result) > 0) {
        $ticketId = $result[0]['id'];
    }
}

ob_end_clean();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support - <?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: #f5f5f5;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 12px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            color: white;
        }

        .navbar-brand {
            font-weight: 600;
            font-size: 18px;
            margin: 0;
        }

        .navbar a {
            color: white;
            text-decoration: none;
            font-size: 24px;
            cursor: pointer;
        }

        .container-main {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .chat-box {
            width: 100%;
            display: flex;
            flex-direction: column;
            background: white;
            margin: 10px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            font-weight: 600;
            font-size: 16px;
        }

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

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

        .empty-state svg {
            width: 80px;
            height: 80px;
            margin-bottom: 15px;
            opacity: 0.3;
        }

        .message-wrapper {
            display: flex;
            margin-bottom: 8px;
        }

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

        .message-wrapper.admin-msg {
            justify-content: flex-start;
        }

        .message-bubble {
            max-width: 65%;
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.4;
        }

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

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

        .message-time {
            font-size: 12px;
            color: #999;
            margin-top: 4px;
            padding: 0 16px;
        }

        .user-msg .message-time {
            text-align: right;
        }

        .message-sender {
            font-size: 11px;
            color: #666;
            margin-bottom: 4px;
            padding: 0 16px;
            font-weight: 500;
        }

        .input-area {
            padding: 15px 20px;
            background: white;
            border-top: 1px solid #e9ecef;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .input-area input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 24px;
            font-size: 14px;
            font-family: inherit;
            outline: none;
            transition: all 0.3s;
        }

        .input-area input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .input-area button {
            background: #667eea;
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 18px;
            transition: all 0.3s;
            flex-shrink: 0;
        }

        .input-area button:hover {
            background: #764ba2;
            transform: scale(1.05);
        }

        .input-area button:active {
            transform: scale(0.95);
        }

        @media (max-width: 768px) {
            .message-bubble {
                max-width: 80%;
            }

            .chat-box {
                margin: 0;
                border-radius: 0;
            }

            .navbar {
                padding: 10px 15px;
            }

            .container-main {
                margin: 0;
            }
        }
    </style>
</head>
<body>

<div class="navbar">
    <div class="navbar-brand">💬 Support Chat</div>
    <a href="dashboard.php">←</a>
</div>

<div class="container-main">
    <div class="chat-box">
        <div class="chat-header">Chat with Admin</div>
        
        <div class="messages-area" id="messagesArea">
            <div class="empty-state">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                </svg>
                <p>Start a conversation with admin</p>
            </div>
        </div>

        <div class="input-area">
            <input type="text" id="messageInput" placeholder="Type your message..." autocomplete="off">
            <button onclick="sendMessage()" type="button">➤</button>
        </div>
    </div>
</div>

<script>
const ticketId = <?php echo $ticketId; ?>;
const userId = <?php echo $userId; ?>;
const messagesArea = document.getElementById('messagesArea');
const messageInput = document.getElementById('messageInput');

function sendMessage() {
    const text = messageInput.value.trim();
    if (!text) return;

    const data = new FormData();
    data.append('message', text);
    data.append('ticket_id', ticketId);

    fetch(window.location.href, {
        method: 'POST',
        body: data
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            messageInput.value = '';
            loadMessages();
        }
    })
    .catch(e => console.error('Error:', e));
}

function loadMessages() {
    const data = new FormData();
    data.append('get_messages', '1');
    data.append('ticket_id', ticketId);

    fetch(window.location.href, {
        method: 'POST',
        body: data
    })
    .then(r => r.json())
    .then(messages => {
        messagesArea.innerHTML = '';
        
        if (!messages || messages.length === 0) {
            messagesArea.innerHTML = `
                <div class="empty-state">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                    </svg>
                    <p>Start a conversation with admin</p>
                </div>
            `;
            return;
        }

        messages.forEach(msg => {
            const isUser = msg.sender_id == userId;
            const timeStr = new Date(msg.created_at).toLocaleTimeString('en-US', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            });

            const html = `
                <div class="message-wrapper ${isUser ? 'user-msg' : 'admin-msg'}">
                    <div>
                        ${!isUser ? '<div class="message-sender">' + (msg.sender_name || 'Admin') + '</div>' : ''}
                        <div class="message-bubble">${escapeHtml(msg.message).replace(/\n/g, '<br>')}</div>
                        <div class="message-time">${timeStr}</div>
                    </div>
                </div>
            `;
            messagesArea.innerHTML += html;
        });

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

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

messageInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        sendMessage();
    }
});

// Load messages on startup
loadMessages();

// Refresh every 2 seconds
setInterval(loadMessages, 2000);
</script>

</body>
</html>
