<?php

namespace App\Controllers\Admin;

use App\Core\YouTube;
use App\Models\GaleriVideoModel;

class GaleriVideoController extends AdminController
{
    public function index(): void
    {
        $this->adminView('galeri/video/index', [
            'daftarVideo' => (new GaleriVideoModel())->all(),
        ]);
    }

    public function create(): void
    {
        $this->adminView('galeri/video/form', ['video' => null]);
    }

    public function store(): void
    {
        $this->verifyCsrf();

        $urlVideo = trim($_POST['url_video'] ?? '');

        (new GaleriVideoModel())->insert([
            'judul'     => trim($_POST['judul'] ?? ''),
            'url_video' => $urlVideo,
            'thumbnail' => YouTube::thumbnailUrl($urlVideo),
            'deskripsi' => trim($_POST['deskripsi'] ?? ''),
        ]);

        $this->setFlash('success', 'Video berhasil ditambahkan.');
        $this->redirect('admin/galeri-video');
    }

    public function edit(string $id): void
    {
        $video = (new GaleriVideoModel())->find((int) $id);

        if (!$video) {
            $this->setFlash('error', 'Video tidak ditemukan.');
            $this->redirect('admin/galeri-video');
            return;
        }

        $this->adminView('galeri/video/form', ['video' => $video]);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();

        $urlVideo = trim($_POST['url_video'] ?? '');

        (new GaleriVideoModel())->update((int) $id, [
            'judul'     => trim($_POST['judul'] ?? ''),
            'url_video' => $urlVideo,
            'thumbnail' => YouTube::thumbnailUrl($urlVideo),
            'deskripsi' => trim($_POST['deskripsi'] ?? ''),
        ]);

        $this->setFlash('success', 'Video berhasil diperbarui.');
        $this->redirect('admin/galeri-video');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();

        (new GaleriVideoModel())->delete((int) $id);

        $this->setFlash('success', 'Video berhasil dihapus.');
        $this->redirect('admin/galeri-video');
    }
}
