<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/auth.php';
require_once '../../vendor/autoload.php';
require_once '../../config/pusher.php';

use Pusher\Pusher;

$admin = requireAdmin();
$data = json_decode(file_get_contents('php://input'), true);

$stream_id = $data['stream_id'] ?? null;
$message = trim($data['message'] ?? '');
$parent_id = $data['parent_id'] ?? null;

if (!$stream_id || !$message || !$parent_id) {
    sendError('Stream ID, message, and parent ID required', 400);
}

// Insert admin reply
$stmt = $pdo->prepare("
    INSERT INTO chat_messages (stream_id, admin_id, user_type, message, parent_id)
    VALUES (?, ?, 'admin', ?, ?)
");
$stmt->execute([$stream_id, $admin['id'], $message, $parent_id]);
$messageId = $pdo->lastInsertId();

// Initialize Pusher
$pusher = new Pusher(PUSHER_KEY, PUSHER_SECRET, PUSHER_APP_ID, ['cluster' => PUSHER_CLUSTER]);

// Trigger real-time event for the reply
$pusher->trigger("chat-stream-{$stream_id}", 'new-reply', [
    'id' => $messageId,
    'message' => $message,
    'created_at' => date('Y-m-d H:i:s'),
    'user_name' => $admin['name'],
    'parent_id' => $parent_id
]);

sendSuccess(['message_id' => $messageId], 'Reply sent');
?>