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

use Pusher\Pusher;

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

$user = requirePublicAuth();

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

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

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

if (strlen($message) > 500) {
    sendError('Message too long', 400);
}

/*
|----------------------------------------------------------
| Check stream status
|----------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT chat_enabled, status 
    FROM live_streams 
    WHERE id = ?
");
$stmt->execute([$stream_id]);
$stream = $stmt->fetch();

if (!$stream) {
    sendError('Stream not found', 404);
}

if ($stream['status'] !== 'live') {
    sendError('Stream is not live', 400);
}

if (!$stream['chat_enabled']) {
    sendError('Chat is currently disabled', 403);
}

/*
|----------------------------------------------------------
| Simple rate limit (basic spam protection)
|----------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT created_at 
    FROM chat_messages 
    WHERE user_id = ? 
    ORDER BY id DESC 
    LIMIT 1
");
$stmt->execute([$user['id']]);
$last = $stmt->fetchColumn();

if ($last && (time() - strtotime($last)) < 2) {
    sendError('Slow down', 429);
}

/*
|----------------------------------------------------------
| Save message
|----------------------------------------------------------
*/
$stmt = $pdo->prepare("
    INSERT INTO chat_messages 
        (stream_id, user_id, user_type, message, temp_id)
    VALUES 
        (?, ?, 'public', ?, ?)
");

$stmt->execute([
    $stream_id,
    $user['id'],
    $message,
    $temp_id
]);

$messageId = $pdo->lastInsertId();

/*
|----------------------------------------------------------
| Display name
|----------------------------------------------------------
*/
$displayName = explode('@', $user['email'])[0];

if (strlen($displayName) > 10) {
    $displayName = substr($displayName, 0, 7) . '...';
}

/*
|----------------------------------------------------------
| Pusher payload (IMPORTANT: includes temp_id)
|----------------------------------------------------------
*/
$messageData = [
    'id'         => (int)$messageId,
    'temp_id'    => $temp_id,
    'user_name'  => $displayName,
    'message'    => $message,
    'created_at' => date('Y-m-d H:i:s'),
    'user_type'  => 'public'
];

try {
    $pusher->trigger(
        "chat-stream-{$stream_id}",
        'new-message',
        $messageData
    );
} catch (Exception $e) {
    error_log("Pusher error: " . $e->getMessage());
    // message already saved, so don't fail request
}

sendSuccess([
    'message_id' => $messageId,
    'temp_id' => $temp_id
], 'Message sent');