<?php
/**
 * Reglas de negocio para enlaces YouTube (watch, Shorts, youtu.be, embed) → ID y URL embed wallpaper.
 */

if (!function_exists('grid_youtube_normalize_url')) {
    function grid_youtube_normalize_url($url) {
        $url = trim((string)$url);
        if ($url === '') {
            return '';
        }
        if (!preg_match('#^https?://#i', $url)) {
            $url = 'https://' . $url;
        }
        return $url;
    }
}

if (!function_exists('grid_youtube_extract_video_id')) {
    /**
     * Extrae el ID de vídeo (11 caracteres) desde cualquier URL YouTube soportada.
     */
    function grid_youtube_extract_video_id($url) {
        $raw = grid_youtube_normalize_url($url);
        if ($raw === '') {
            return null;
        }

        $parts = @parse_url($raw);
        if (!is_array($parts)) {
            return grid_youtube_extract_video_id_regex($raw);
        }

        $host = strtolower((string)($parts['host'] ?? ''));
        $host = preg_replace('/^(www\.|m\.)/', '', $host);
        $path = (string)($parts['path'] ?? '');

        if (in_array($host, ['youtube.com', 'youtube-nocookie.com'], true)) {
            if (preg_match('#^/shorts/([a-zA-Z0-9_-]{11})#', $path, $m)) {
                return $m[1];
            }
            if (preg_match('#^/(?:embed|v|live)/([a-zA-Z0-9_-]{11})#', $path, $m)) {
                return $m[1];
            }
            if (preg_match('#^/watch#', $path)) {
                parse_str((string)($parts['query'] ?? ''), $q);
                $v = isset($q['v']) ? (string)$q['v'] : '';
                if (preg_match('/^[a-zA-Z0-9_-]{11}$/', $v)) {
                    return $v;
                }
            }
        }

        if ($host === 'youtu.be' && preg_match('#^/([a-zA-Z0-9_-]{11})#', $path, $m)) {
            return $m[1];
        }

        return grid_youtube_extract_video_id_regex($raw);
    }

    function grid_youtube_extract_video_id_regex($raw) {
        $patterns = [
            '#youtube\.com/shorts/([a-zA-Z0-9_-]{11})#i',
            '#youtube\.com/(?:embed|v|live)/([a-zA-Z0-9_-]{11})#i',
            '#youtu\.be/([a-zA-Z0-9_-]{11})#i',
            '#[?&]v=([a-zA-Z0-9_-]{11})#i',
        ];
        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $raw, $m)) {
                return $m[1];
            }
        }
        return null;
    }
}

if (!function_exists('grid_youtube_is_valid_url')) {
    function grid_youtube_is_valid_url($url) {
        return grid_youtube_extract_video_id($url) !== null;
    }
}

if (!function_exists('grid_youtube_wallpaper_embed_url')) {
    /**
     * URL embed lista para videowallpaper (autoplay, mute, loop, sin controles).
     *
     * @param string $urlOrId URL o ID de 11 caracteres
     */
    function grid_youtube_wallpaper_embed_url($urlOrId) {
        $id = null;
        $s = trim((string)$urlOrId);
        if ($s !== '' && preg_match('/^[a-zA-Z0-9_-]{11}$/', $s)) {
            $id = $s;
        } else {
            $id = grid_youtube_extract_video_id($s);
        }
        if ($id === null || $id === '') {
            return null;
        }
        $params = [
            'autoplay' => '1',
            'mute' => '1',
            'loop' => '1',
            'playlist' => $id,
            'controls' => '0',
            'modestbranding' => '1',
            'rel' => '0',
            'playsinline' => '1',
            'enablejsapi' => '1',
        ];
        $host = (string)($_SERVER['HTTP_HOST'] ?? '');
        if ($host !== '') {
            $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                || (strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');
            $params['origin'] = ($https ? 'https' : 'http') . '://' . $host;
        }
        return 'https://www.youtube-nocookie.com/embed/' . rawurlencode($id) . '?' . http_build_query($params);
    }
}
