<?php

namespace App\Http\Controllers;

use App\Models\Recommendation;

class RekomendasiController extends Controller
{
    /**
     * Helper function untuk mengekstrak ID video dari URL YouTube.
     */
    private function extractYouTubeId(string $url): ?string
    {
        preg_match('/(v=|vi=|youtu.be\/|embed\/|\/v\/|\?v=|\&v=)(.+?)\b/i', $url, $matches);
        return $matches[2] ?? null;
    }

    public function show($id)
    {
        $rekomendasi = Recommendation::findOrFail($id);

        $embedLink = null;
        $videoId = $this->extractYouTubeId($rekomendasi->youtube_link);
        if ($videoId) {
            $embedLink = "https://www.youtube.com/embed/" . $videoId;
        }

        $data = $rekomendasi->toArray();
        $data['youtube_embed_link'] = $embedLink;

        return view('rekomendasiShow', [
            'pageTitle' => $rekomendasi->judul,
            'rekomendasi' => $data,
        ]);
    }
}