<?php
    session_start();
    require('conexion.php');
    $outgoing_id = $_SESSION['id_usuario'];
    $incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']);
    echo '<p>' . $outgoing_id . '</p>';
    echo "<script>";
    echo "console.log('outgoing_id: ', " . json_encode($outgoing_id) . ");";
    echo "console.log('incoming_id: ', " . json_encode($incoming_id) . ");";
    echo "</script>";
    $output = "";
    $sql = "SELECT 
    m.*,  
    u.documento 
FROM 
    messages m  
LEFT JOIN 
    usuarios u ON u.usuario_id = m.outgoing_msg_id
WHERE 
    (m.outgoing_msg_id = {$outgoing_id} AND m.incoming_msg_id = {$incoming_id})
    OR (m.outgoing_msg_id = {$incoming_id} AND m.incoming_msg_id = {$outgoing_id})
ORDER BY 
    m.msg_id";
    $query = mysqli_query($conn, $sql);
    if (mysqli_num_rows($query) > 0) {
        while ($row = mysqli_fetch_assoc($query)) {
            if ($row['outgoing_msg_id'] === $outgoing_id) {
                $output .= '<div class="chat outgoing">
                                <div class="details">
                                    <p>' . $row['msg'] . '</p>
                                </div>
                                </div>';
            } else {
                $output .= '<div class="chat incoming">
                                <img src="img/perfiles/' . $row['documento'] . '.jpg" alt="">
                                <div class="details">
                                    <p>' . $row['msg'] . '</p>
                                </div>
                                </div>';
            }
        }
    } else {
        $output .= '<div class="text">No hay mensajes disponibles. Una vez que envíe el mensaje, aparecerán aquí1.</div>';
    }
    echo $output;