<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");

require_once '../../config/db.php';
require_once '../../core/Auth.php';

try {
    $user_id = Auth::check();
    $data = json_decode(file_get_contents("php://input"), true);

    $item_id = isset($data['item_id']) ? (int)$data['item_id'] : 0;
    $chat_id = isset($data['chat_id']) ? (int)$data['chat_id'] : 0;

    if ($item_id <= 0 || $chat_id <= 0) {
        throw new Exception("Missing parameters");
    }

    // Verify item ownership
    $stmt = $pdo->prepare("SELECT * FROM chest_items WHERE id = ? AND user_id = ?");
    $stmt->execute([$item_id, $user_id]);
    $item = $stmt->fetch();

    if (!$item) {
        throw new Exception("Item not found or access denied");
    }

    // Insert Message into Chat
    $content = "📦 Compartió un ítem del cofre: " . $item['name'];
    $meta_data = json_encode([
        'item_id' => $item_id,
        'type' => 'chest_item',
        'item_name' => $item['name'],
        'price' => $item['price'],
        'file_url' => $item['file_url']
    ]);

    $stmt_msg = $pdo->prepare("INSERT INTO messages (chat_id, sender_id, content, type, meta_data) VALUES (?, ?, ?, 'content', ?)");
    $stmt_msg->execute([$chat_id, $user_id, $content, $meta_data]);

    echo json_encode(['success' => true, 'message' => 'Compartido al chat exitosamente']);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
