<?php

namespace App\Core;

class YouTube
{
    /**
     * Ambil video ID dari berbagai format URL YouTube.
     * Mendukung: watch?v=, youtu.be/, embed/, shorts/
     */
    public static function extractId(string $url): ?string
    {
        $patterns = [
            '/youtu\.be\/([a-zA-Z0-9_-]{6,})/',
            '/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{6,})/',
            '/youtube\.com\/embed\/([a-zA-Z0-9_-]{6,})/',
            '/youtube\.com\/shorts\/([a-zA-Z0-9_-]{6,})/',
        ];

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $url, $matches)) {
                return $matches[1];
            }
        }

        return null;
    }

    public static function embedUrl(string $originalUrl): string
    {
        $id = self::extractId($originalUrl);
        return $id ? "https://www.youtube.com/embed/{$id}" : $originalUrl;
    }

    public static function thumbnailUrl(string $originalUrl): ?string
    {
        $id = self::extractId($originalUrl);
        return $id ? "https://img.youtube.com/vi/{$id}/hqdefault.jpg" : null;
    }
}
