<?php
// chat_view.php
require 'config/db.php';
require_once 'addons/verified_sellers/main.php'; 
require_once 'addons/last_seen/main.php'; 



if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$contact_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$current_user_id = (int)$_SESSION['user_id'];

// Evitar chatear con uno mismo
if ($contact_id === $current_user_id) {
    header("Location: messages.php");
    exit;
}

try {
    $stmt_contact = $pdo->prepare("SELECT id, username FROM users WHERE id = ?");
    $stmt_contact->execute([$contact_id]);
    $contact_data = $stmt_contact->fetch();

    if (!$contact_data) { 
        die("<div style='color:white; text-align:center; margin-top:50px;'>User not found in the encrypted database.</div>"); 
    }

    // Marcar como leídos los mensajes entrantes
    $update_read = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE sender_id = ? AND receiver_id = ? AND is_read = 0");
    $update_read->execute([$contact_id, $current_user_id]);

    // Obtener historial (últimos 50 mensajes)
    $stmt_msgs = $pdo->prepare("
        SELECT * FROM messages 
        WHERE (sender_id = ? AND receiver_id = ?) 
           OR (sender_id = ? AND receiver_id = ?)
        ORDER BY created_at ASC LIMIT 50
    ");
    $stmt_msgs->execute([$current_user_id, $contact_id, $contact_id, $current_user_id]);
    $chat_messages = $stmt_msgs->fetchAll();

    // Obtener el ID del último mensaje para el puntero de AJAX
    $last_msg_id = 0;
    if (count($chat_messages) > 0) {
        $last_msg_id = end($chat_messages)['id'];
    }

} catch (PDOException $e) {
    die("Connection error.");
}

include 'includes/header.php'; 
?>

<style>
    /* Estilos del Contenedor de Chat */
    .chat-window { 
        max-width: 900px; 
        margin: 30px auto; 
        background: #161b22; 
        border: 1px solid #30363d; 
        border-radius: 20px; 
        display: flex; 
        flex-direction: column; 
        height: 80vh; 
        overflow: hidden; 
        box-shadow: 0 20px 40px rgba(0,0,0,0.5);
    }
    
    .chat-header { 
        padding: 20px; 
        border-bottom: 1px solid #30363d; 
        display: flex; 
        align-items: center; 
        justify-content: space-between; 
        background: rgba(0,0,0,0.2); 
    }

    .messages-area { 
        flex: 1; 
        overflow-y: auto; 
        padding: 25px; 
        display: flex; 
        flex-direction: column; 
        gap: 12px; 
        background: #0d1117; 
        scroll-behavior: smooth; 
    }

    /* Burbujas de Mensaje */
    .msg { 
        max-width: 75%; 
        padding: 12px 18px; 
        border-radius: 18px; 
        font-size: 14px; 
        line-height: 1.5; 
        position: relative; 
        word-wrap: break-word; 
    }
    .msg-me { 
        align-self: flex-end; 
        background: #00ff88; 
        color: #0d1117; 
        border-bottom-right-radius: 4px; 
        font-weight: 600; 
    }
    .msg-them { 
        align-self: flex-start; 
        background: #21262d; 
        color: #eee; 
        border: 1px solid #30363d; 
        border-bottom-left-radius: 4px; 
    }
    .msg-time { 
        font-size: 10px; 
        opacity: 0.6; 
        margin-top: 6px; 
        display: block; 
    }

    /* Área de Entrada */
    .chat-input-area { 
        padding: 20px; 
        background: #161b22; 
        border-top: 1px solid #30363d; 
        display: flex; 
        gap: 12px; 
    }
    .chat-input { 
        flex: 1; 
        background: #0d1117; 
        border: 1px solid #30363d; 
        color: white; 
        padding: 14px 18px; 
        border-radius: 12px; 
        outline: none; 
        transition: 0.3s; 
    }
    .chat-input:focus { border-color: #00ff88; }
    
    .btn-send { 
        background: #00ff88; 
        color: #0d1117; 
        border: none; 
        width: 55px; 
        height: 50px; 
        border-radius: 12px; 
        font-size: 18px; 
        cursor: pointer; 
        display: flex; 
        align-items: center; 
        justify-content: center; 
    }

    /* Scroll Personalizado */
    .messages-area::-webkit-scrollbar { width: 5px; }
    .messages-area::-webkit-scrollbar-thumb { background: #30363d; border-radius: 10px; }
</style>

<div class="chat-window">
    <div class="chat-header">
        <div style="display: flex; align-items: center; gap: 15px;">
            <a href="messages.php" style="color: #8b949e; font-size: 20px;"><i class="fa-solid fa-circle-chevron-left"></i></a>
            <div>
                <span style="font-weight: 900; color: white; font-family: 'Syncopate', sans-serif; font-size: 13px;">
                    @<?php echo htmlspecialchars($contact_data['username']); ?>
                </span>
                <div style="display: flex; align-items: center; gap: 5px; margin-top: 4px;">
                    <?php if (function_exists('get_user_status')) echo get_user_status($contact_data['id'], $pdo); ?>
                    <?php if (function_exists('get_user_badges')) echo get_user_badges($contact_data['id'], $pdo); ?>
                </div>
            </div>
        </div>
        <div style="text-align: right;">
            <span style="font-size: 9px; color: #00ff88; font-weight: 900; letter-spacing: 1px; text-transform: uppercase;">Encrypted Channel</span>
        </div>
    </div>

    <div class="messages-area" id="msg-box">
        <?php foreach($chat_messages as $m): ?>
            <?php $is_me = ($m['sender_id'] == $current_user_id); ?>
            <div class="msg <?php echo $is_me ? 'msg-me' : 'msg-them'; ?>" data-id="<?php echo $m['id']; ?>">
                <?php echo htmlspecialchars($m['message']); ?> 
                <span class="msg-time"><?php echo date('H:i', strtotime($m['created_at'])); ?></span>
            </div>
        <?php endforeach; ?>
    </div>

    <form class="chat-input-area" id="chat-form">
        <input type="hidden" id="receiver_id" value="<?php echo $contact_id; ?>">
        <input type="text" id="message_input" class="chat-input" placeholder="Type an encrypted message..." required autocomplete="off">
        <button type="submit" class="btn-send"><i class="fa-solid fa-paper-plane"></i></button>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    const msgBox = document.getElementById("msg-box");
    let lastMsgId = <?php echo $last_msg_id; ?>;
    let windowFocus = true;

    // Control de Foco de Pestaña
    $(window).focus(function() { 
        windowFocus = true; 
        document.title = "VVAULT - Secure Chat"; 
    }).blur(function() { 
        windowFocus = false; 
    });

    // Scroll al final al cargar
    msgBox.scrollTop = msgBox.scrollHeight;

    // Enviar Mensaje
    $("#chat-form").on("submit", function(e) {
        e.preventDefault();
        const msg = $("#message_input").val().trim();
        const rid = $("#receiver_id").val();
        
        if(msg == "") return;

        // Feedback visual instantáneo
        const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
        const localMsg = `
            <div class="msg msg-me">
                ${escapeHtml(msg)}
                <span class="msg-time">${time}</span>
            </div>
        `;
        $("#msg-box").append(localMsg);
        $("#message_input").val("");
        msgBox.scrollTop = msgBox.scrollHeight;

        $.ajax({
            url: 'send_message_ajax.php',
            method: 'POST',
            data: { receiver_id: rid, message: msg },
            dataType: 'json',
            success: function(response) {
                if(response.status === "success") {
                    lastMsgId = response.last_id;
                }
            }
        });
    });

    // Auto-refresh inteligente (cada 3 segundos)
    setInterval(function() {
        $.ajax({
            url: 'fetch_new_messages_ajax.php',
            method: 'GET',
            data: { 
                contact_id: <?php echo $contact_id; ?>,
                last_id: lastMsgId 
            },
            success: function(data) {
                if(data.trim() !== "") {
                    $("#msg-box").append(data);
                    msgBox.scrollTop = msgBox.scrollHeight;
                    
                    // Actualizar lastMsgId buscando el último elemento inyectado
                    const newId = $("#msg-box .msg").last().data("id");
                    if(newId) lastMsgId = newId;

                    // Mejora: Alerta en pestaña si el usuario no está viendo el chat
                    if(!windowFocus) {
                        document.title = "(*) New Message - VVAULT";
                    }
                }
            }
        });
    }, 3000);

    function escapeHtml(text) {
        return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    }
</script>

<?php include 'includes/footer.php'; ?>