<?php

if (! function_exists('isYouTubeUrl')) {
    /**
     * Check if a given URL is a YouTube video URL
     *
     * @param string $url
     * @return bool
     */
    function isYouTubeUrl($url) {
        return preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $url);
    }
}

if (! function_exists('extractYouTubeVideoId')) {
    /**
     * Extract YouTube video ID from URL
     *
     * @param string $url
     * @return string|null
     */
    function extractYouTubeVideoId($url) {
        $pattern = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/';
        preg_match($pattern, $url, $matches);
        return $matches[1] ?? null;
    }
}

if (! function_exists('getYouTubeVideoMetadata')) {
    /**
     * Get YouTube video metadata using oEmbed API
     *
     * @param string $url
     * @return array|null
     */
    function getYouTubeVideoMetadata($url) {
        $videoId = extractYouTubeVideoId($url);
        if (! $videoId) {
            return null;
        }

        try {
            // Use YouTube oEmbed API to get video metadata
            $oembedUrl = "https://www.youtube.com/oembed?url=" . urlencode($url) . "&format=json";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $oembedUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; URL Shortener Bot)');

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200 && $response) {
                $data = json_decode($response, true);

                if ($data && isset($data['title'])) {
                    return [
                        'title'       => $data['title'],
                        'description' => $data['title'] . ' - Watch this video on YouTube',
                        'thumbnail'   => $data['thumbnail_url'] ?? "https://img.youtube.com/vi/{$videoId}/maxresdefault.jpg",
                        'author'      => $data['author_name'] ?? 'YouTube',
                        'type'        => 'video',
                        'video_id'    => $videoId,
                        'embed_url'   => "https://www.youtube.com/embed/{$videoId}",
                        'width'       => $data['width'] ?? 1280,
                        'height'      => $data['height'] ?? 720,
                    ];
                }
            }
        } catch (Exception $e) {
            // Fallback to basic metadata if API fails
        }

        // Fallback metadata using video ID
        return [
            'title'       => 'YouTube Video',
            'description' => 'Watch this video on YouTube',
            'thumbnail'   => "https://img.youtube.com/vi/{$videoId}/maxresdefault.jpg",
            'author'      => 'YouTube',
            'type'        => 'video',
            'video_id'    => $videoId,
            'embed_url'   => "https://www.youtube.com/embed/{$videoId}",
            'width'       => 1280,
            'height'      => 720,
        ];
    }
}
