<?php
declare(strict_types=1);

/** Speichert eine sichtbare Änderung an einer Reise und liefert ihre ID zurück. */
function triptale_log_trip_change(int $tripId, int $userId, string $type, string $message): int
{
    $statement = db()->prepare('INSERT INTO ' . table('trip_changes') . ' (trip_id, user_id, change_type, message) VALUES (:trip_id, :user_id, :change_type, :message)');
    $statement->execute([
        ':trip_id' => $tripId,
        ':user_id' => $userId,
        ':change_type' => $type,
        ':message' => function_exists('mb_substr') ? mb_substr(trim($message), 0, 500) : substr(trim($message), 0, 500),
    ]);
    return (int) db()->lastInsertId();
}

function triptale_can_manage_trip(int $tripId, array $user, int $creatorId): bool
{
    if (($user['role'] ?? '') === 'main_admin' || (int) ($user['id'] ?? 0) === $creatorId) {
        return true;
    }
    $statement = db()->prepare('SELECT 1 FROM ' . table('trip_admins') . ' WHERE trip_id = :trip_id AND user_id = :user_id LIMIT 1');
    $statement->execute([':trip_id' => $tripId, ':user_id' => (int) $user['id']]);
    return (bool) $statement->fetchColumn();
}

/** Alle aktiven Mitglieder der Reise, ohne die Person, die geändert hat. */
function triptale_trip_change_recipients(int $tripId, int $actorId): array
{
    $statement = db()->prepare('SELECT DISTINCT u.email, u.first_name, u.last_name, u.preferred_language
        FROM ' . table('users') . ' u
        LEFT JOIN ' . table('trip_admins') . ' a ON a.user_id = u.id AND a.trip_id = :trip_id_admin
        LEFT JOIN ' . table('trip_participants') . ' p ON p.user_id = u.id AND p.trip_id = :trip_id_participant
        WHERE (a.user_id IS NOT NULL OR p.user_id IS NOT NULL)
          AND u.status = \'active\' AND u.deleted_at IS NULL AND u.email <> \'\' AND u.id <> :actor_id
        ORDER BY u.first_name, u.last_name');
    $statement->execute([':trip_id_admin' => $tripId, ':trip_id_participant' => $tripId, ':actor_id' => $actorId]);
    return $statement->fetchAll();
}
