<?php
// get_messages.php
require 'config/db.php';


// 1. Session Security
if (!isset($_SESSION['user_id'])) { 
    exit; // No output if not logged in
}

$current_user_id = $_SESSION['user_id']; // Direct numeric ID
$product_id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
$other_user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;

try {
    /** * 2. Fetch Conversation History
     * We filter by product_id and the two users involved.
     * Note: I updated 'message_text' to 'message' to match your table schema.
     */
    $stmt_msgs = $pdo->prepare("
        SELECT * FROM messages 
        WHERE product_id = ? 
        AND (
            (sender_id = ? AND receiver_id = ?) 
            OR 
            (sender_id = ? AND receiver_id = ?)
        )
        ORDER BY created_at ASC
    ");
    
    $stmt_msgs->execute([
        $product_id, 
        $current_user_id, $other_user_id, 
        $other_user_id, $current_user_id
    ]);
    
    $chat_history = $stmt_msgs->fetchAll();

    // 3. Generate HTML Output
    if ($chat_history) {
        foreach($chat_history as $msg) {
            $alignment_class = ($msg['sender_id'] == $current_user_id) ? 'me' : 'other';
            $formatted_time = date('H:i', strtotime($msg['created_at']));
            
            echo "<div class='bubble $alignment_class'>";
            echo htmlspecialchars($msg['message']); // Using 'message' column
            echo "<span class='time'>$formatted_time</span>";
            echo "</div>";
        }
    }

} catch (PDOException $e) {
    // Silent error for AJAX calls
    error_log("Chat Fetch Error: " . $e->getMessage());
}
?>