<?php
/**
 * ITSWEBER CMS – Social Embed Section
 *
 * Embeds from TikTok, Instagram, YouTube Shorts.
 * Migriert aus plugins/social-embed-section.
 *
 * @author    Benny Weber (ITSWEBER)
 * @copyright © ITSWEBER – www.itsweber.de
 * @contact   kontakt@itsweber.de
 */

namespace App\Sections\Extended;

use App\Sections\AbstractSection;
use App\Core\Request;

class SocialEmbedSection extends AbstractSection
{
    public static function typeKey(): string    { return 'social_embed'; }
    public static function label(): string      { return 'Social Embed'; }
    public static function category(): string   { return 'media'; }
    public static function description(): string { return 'Eingebettete Inhalte von TikTok, Instagram, YouTube Shorts'; }

    public static function iconSvg(): string
    {
        return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">'
             . '<circle cx="12" cy="12" r="10"/>'
             . '<path d="M8 12l3 3 5-5"/>'
             . '</svg>';
    }

    public function buildData(Request $request): array
    {
        $allowedColumns = ['1', '2', '3', '4'];

        $itemUrls  = $request->input('ses_url', []);
        $itemTitles = $request->input('ses_title', []);
        $itemDescs  = $request->input('ses_description', []);

        $items = [];
        if (is_array($itemUrls)) {
            foreach ($itemUrls as $i => $itemUrl) {
                $url = trim((string) $itemUrl);
                if ($url === '' || !preg_match('/^https?:\/\//i', $url)) {
                    continue;
                }

                $providerInfo = self::detectProvider($url);

                $items[] = [
                    'url'         => $url,
                    'title'       => trim((string) ($itemTitles[$i] ?? '')),
                    'description' => trim((string) ($itemDescs[$i] ?? '')),
                    'provider'    => $providerInfo['provider'],
                    'provider_id' => $providerInfo['id'],
                    'username'    => $providerInfo['username'],
                ];
            }
        }
        $items = array_slice($items, 0, 12);

        $columns = (string) ($request->input('columns', '3') ?? '3');
        if (!in_array($columns, $allowedColumns, true)) {
            $columns = '3';
        }

        $ctaUrl = trim((string) ($request->input('cta_url', '') ?? ''));
        if ($ctaUrl !== '' && !preg_match('/^(https?:\/\/|\/)/i', $ctaUrl)) {
            $ctaUrl = '';
        }

        $data = [
            'title'              => trim((string) ($request->input('title', '') ?? '')),
            'subtitle'           => trim((string) ($request->input('subtitle', '') ?? '')),
            'color_scheme'       => self::sanitizeToken((string) ($request->input('color_scheme', '') ?? ''), self::allowedColorScheme()),
            'section_text_color' => self::sanitizeToken((string) ($request->input('section_text_color', '') ?? ''), self::allowedSectionTextColor()),
            'columns'            => $columns,
            'cta_text'           => trim((string) ($request->input('cta_text', '') ?? '')),
            'cta_url'            => $ctaUrl,
            'items'              => $items,
        ];

        return $this->mergeThemeExtras($data, $request);
    }

    public function defaultData(): array
    {
        return [
            'title' => 'Social Media',
            'subtitle' => 'Folgen Sie uns',
            'color_scheme' => '', 'section_text_color' => '',
            'columns' => '3', 'cta_text' => '', 'cta_url' => '',
            'items' => [],
        ];
    }

    public function styles(): array
    {
        return ['/assets/css/sections/social-embed-section.css'];
    }

    public function scripts(): array
    {
        return ['/assets/js/sections/social-embed-section.js'];
    }

    /**
     * Detect social media provider from URL.
     * Ported from plugins/social-embed-section/plugin.php ses_detect_provider().
     */
    public static function detectProvider(string $url): array
    {
        $url = trim($url);

        // TikTok: https://www.tiktok.com/@username/video/1234567890
        if (preg_match('#(?:https?://)?(?:www\.)?tiktok\.com/@([^/]+)/video/(\d+)#i', $url, $m)) {
            return ['provider' => 'tiktok', 'id' => $m[2], 'username' => $m[1]];
        }

        // TikTok short URL: https://vm.tiktok.com/XXXXXX/
        if (preg_match('#(?:https?://)?vm\.tiktok\.com/([a-zA-Z0-9]+)#i', $url, $m)) {
            return ['provider' => 'tiktok', 'id' => $m[1], 'username' => ''];
        }

        // Instagram: https://www.instagram.com/p/XXXXX/ or /reel/XXXXX/
        if (preg_match('#(?:https?://)?(?:www\.)?instagram\.com/(?:p|reel)/([a-zA-Z0-9_-]+)#i', $url, $m)) {
            return ['provider' => 'instagram', 'id' => $m[1], 'username' => ''];
        }

        // YouTube Shorts: https://www.youtube.com/shorts/XXXXX
        if (preg_match('#(?:https?://)?(?:www\.)?youtube\.com/shorts/([\w-]+)#i', $url, $m)) {
            return ['provider' => 'youtube_shorts', 'id' => $m[1], 'username' => ''];
        }

        return ['provider' => 'unknown', 'id' => '', 'username' => ''];
    }
}
