<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\DummyDataService;
use Illuminate\Http\Request;

class AdminRekomendasiController 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 index()
    {
        $rekomendasiMentah = DummyDataService::getRekomendasiPembelajaran();

        // Menambahkan thumbnail YouTube ke setiap rekomendasi
        $semuaRekomendasi = $rekomendasiMentah->map(function ($item) {
            $videoId = $this->extractYouTubeId($item['youtube_link']);
            if ($videoId) {
                $item['thumbnail'] = "https://img.youtube.com/vi/{$videoId}/hqdefault.jpg";
            } else {
                $item['thumbnail'] = 'https://via.placeholder.com/150?text=No+Preview';
            }
            return $item;
        });

        return view('admin.rekomendasi.index', [
            'pageTitle' => 'Manajemen Rekomendasi',
            'semuaRekomendasi' => $semuaRekomendasi
        ]);
    }

    public function create()
    {
        return view('admin.rekomendasi.create', ['pageTitle' => 'Tambah Rekomendasi']);
    }

    public function edit($id)
    {
        $rekomendasi = DummyDataService::getRekomendasiPembelajaran()->firstWhere('id', (int)$id);
        abort_if(!$rekomendasi, 404);
        return view('admin.rekomendasi.edit', ['pageTitle' => 'Edit Rekomendasi', 'rekomendasi' => $rekomendasi]);
    }
}