<?php

namespace App\Services;

class PublicSiteMediaService
{
    /**
     * YouTube or Vimeo watch URL to embed src, or null.
     */
    public static function videoEmbedUrl(?string $url): ?string
    {
        if (! $url || ! is_string($url)) {
            return null;
        }
        $url = trim($url);
        if ($url === '') {
            return null;
        }
        if (preg_match('~(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/embed/)([a-zA-Z0-9_-]{6,20})~', $url, $m)) {
            $id = $m[1];
            // loop=1 requires playlist=VIDEO_ID (same id) for a single video to repeat.
            return 'https://www.youtube.com/embed/' . $id
                . '?autoplay=1&mute=1&playsinline=1&controls=0&rel=0&modestbranding=1&loop=1&playlist=' . $id;
        }
        if (preg_match('~vimeo\.com/(?:video/)?(\d+)~', $url, $m)) {
            return 'https://player.vimeo.com/video/' . $m[1] . '?autoplay=1&muted=1&loop=1&background=1&controls=0';
        }

        return null;
    }

    public static function storageUrl(?string $path): ?string
    {
        if (! $path) {
            return null;
        }

        return asset('storage/' . ltrim($path, '/'));
    }
}
