<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\GaleriVideoModel;

class Video extends BaseController
{
    protected $videoModel;

    public function __construct()
    {
        $this->videoModel = new GaleriVideoModel();
    }

    public function index()
    {
        return view('admin/video/index', [
            'title' => 'Galeri Video',
            'items' => $this->videoModel
                ->orderBy('id', 'DESC')
                ->findAll(),
        ]);
    }

    public function create()
    {
        return view('admin/video/form', [
            'title'  => 'Tambah Video',
            'item'   => null,
            'errors' => session()->getFlashdata('errors'),
        ]);
    }
    public function store()
    {
        $rules = [
            'judul'        => 'required',
            'link_youtube' => 'required|valid_url',
            'tahun'        => 'permit_empty',
        ];
    
        if (! $this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors());
        }
    
        $this->videoModel->insert([
            'judul'        => $this->request->getPost('judul'),
            'link_youtube' => $this->request->getPost('link_youtube'),
            'tahun'        => $this->request->getPost('tahun'),
        ]);
    
        return redirect()->to(base_url('admin/video'))
            ->with('msg', 'Video berhasil ditambahkan');
    }

    public function delete($id)
    {
        $this->videoModel->delete($id);

        return redirect()->to(base_url('admin/video'))
            ->with('success', 'Video berhasil dihapus');
    }
}
