<?php
// dispute_chat.php
require 'config/db.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

$order_id = intval($_GET['id'] ?? 0);
$current_user_id = $_SESSION['user_id'] ?? null;

if (!$current_user_id) { header("Location: login.php"); exit; }

// 1. VERIFICAR QUE LA ORDEN EXISTE Y ESTÁ EN DISPUTA (Cambiado a 'IN_DISPUTE')
$stmt = $pdo->prepare("
    SELECT o.*, p.title as product_title 
    FROM orders o 
    JOIN products p ON o.product_id = p.id 
    WHERE o.id = ? AND o.status = 'IN_DISPUTE'
");
$stmt->execute([$order_id]);
$order_data = $stmt->fetch();

// Verificamos si es comprador, vendedor o admin
if (!$order_data || ($order_data['buyer_id'] != $current_user_id && $order_data['seller_id'] != $current_user_id && $_SESSION['role'] !== 'admin')) {
    die("Acceso Denegado: Esta disputa no existe o no tienes permiso.");
}

// 2. PROCESAR NUEVO MENSAJE (Cambiado user_id por sender_id)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty(trim($_POST['message']))) {
    $chat_message = trim($_POST['message']);
    $insert_msg = $pdo->prepare("INSERT INTO dispute_messages (order_id, sender_id, message) VALUES (?, ?, ?)");
    $insert_msg->execute([$order_id, $current_user_id, $chat_message]);
    
    header("Location: dispute_chat.php?id=$order_id&status=sent");
    exit;
}

// 3. CARGAR HISTORIAL (Cambiado user_id por sender_id)
$msg_stmt = $pdo->prepare("
    SELECT dm.*, u.username 
    FROM dispute_messages dm 
    JOIN users u ON dm.sender_id = u.id 
    WHERE dm.order_id = ? 
    ORDER BY dm.created_at ASC
");
$msg_stmt->execute([$order_id]);
$chat_history = $msg_stmt->fetchAll();

include 'includes/header.php';
?>

<div style="max-width: 800px; margin: 30px auto; padding: 20px; font-family: 'Inter', sans-serif; color: white;">
    <div style="background: #161b22; border: 1px solid #30363d; border-radius: 15px; overflow: hidden;">
        
        <div style="padding: 20px; background: rgba(255, 77, 77, 0.1); border-bottom: 1px solid #30363d; display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h3 style="margin: 0; color: #ff4d4d; font-family: 'Syncopate'; font-size: 14px;">CASE #<?php echo $order_id; ?>: <?php echo htmlspecialchars($order_data['product_title']); ?></h3>
                <span style="font-size: 11px; color: #8b949e;">Tribunal de Disputas | El administrador está monitoreando</span>
            </div>
            <a href="dashboard.php" style="color: #8b949e; text-decoration: none; font-size: 12px; font-weight: 800;">SALIR</a>
        </div>

        <div style="height: 450px; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 15px; background: #0d1117;">
            <?php foreach($chat_history as $msg): 
                $is_mine = ($msg['sender_id'] == $current_user_id);
            ?>
                <div style="align-self: <?php echo $is_mine ? 'flex-end' : 'flex-start'; ?>; max-width: 80%; min-width: 150px;">
                    <div style="font-size: 10px; color: #555; margin-bottom: 4px; text-align: <?php echo $is_mine ? 'right' : 'left'; ?>;">
                        @<?php echo $msg['username']; ?> • <?php echo date('H:i', strtotime($msg['created_at'])); ?>
                    </div>
                    <div style="padding: 12px; border-radius: 12px; background: <?php echo $is_mine ? '#21262d' : '#161b22'; ?>; 
                                border: 1px solid <?php echo $is_mine ? '#00ff88' : '#30363d'; ?>; color: white; font-size: 13px;">
                        <?php echo htmlspecialchars($msg['message']); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <form method="POST" style="padding: 20px; border-top: 1px solid #30363d; display: flex; gap: 10px; background: #161b22;">
            <input type="text" name="message" placeholder="Escribe tu mensaje o prueba aquí..." required autocomplete="off"
                   style="flex: 1; background: #0d1117; border: 1px solid #30363d; padding: 12px; border-radius: 8px; color: white; outline: none;">
            <button type="submit" style="background: #00ff88; border: none; padding: 0 25px; border-radius: 8px; font-weight: 900; cursor: pointer; color: black; font-size: 12px;">
                ENVIAR
            </button>
        </form>
    </div>
</div>

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