<?php
require_once '../config/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['user_id'])) {
    $sender_id = $_SESSION['user_id'];
    $receiver_id = $_POST['receiver_id']; // ID del vendedor
    $product_id = $_POST['product_id'];
    $message = trim($_POST['message'] ?? '');
    $image_path = null;

    // 1. Manejo de Imagen (Si existe)
    if (!empty($_FILES['chat_img']['name'])) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($_FILES['chat_img']['name'], PATHINFO_EXTENSION));
        
        // Restricción: Solo 2MB y formatos permitidos
        if (in_array($ext, $allowed) && $_FILES['chat_img']['size'] <= 2000000) {
            $new_name = uniqid('chat_', true) . '.' . $ext;
            $upload_dir = '../uploads/chat/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            if (move_uploaded_file($_FILES['chat_img']['tmp_name'], $upload_dir . $new_name)) {
                $image_path = 'uploads/chat/' . $new_name;
            }
        }
    }

    // 2. Insertar solo si hay mensaje o imagen
    if (!empty($message) || $image_path) {
        $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, product_id, message, image_url) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$sender_id, $receiver_id, $product_id, $message, $image_path]);
        
        // Respuesta para AJAX
        echo json_encode(['status' => 'success']);
    }
}
?>