<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\Video;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class VideoController extends Controller
{
    public function index()
    {
        $settings = Setting::whereIn('key', [
            'video_section_active',
        ])->pluck('value', 'key');

        $videos = Video::orderBy('sort_order')->orderBy('id')->get();

        return view('admin.settings.video', compact('settings', 'videos'));
    }

    public function storeSettings(Request $request)
    {
        Setting::updateOrCreate(
            ['key' => 'video_section_active'],
            ['value' => $request->has('video_section_active') ? '1' : '0']
        );

        return back()->with('success', 'Pengaturan video berhasil disimpan.');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'source_type' => 'required|in:youtube,upload',
            'youtube_id' => 'required_if:source_type,youtube|nullable|string|max:255',
            'video_file' => 'required_if:source_type,upload|nullable|file|mimetypes:video/mp4,video/webm|max:51200',
        ]);

        $data = [
            'title' => $request->title,
            'description' => $request->description,
            'source_type' => $request->source_type,
            'youtube_id' => $request->source_type === 'youtube' ? $request->youtube_id : null,
            'sort_order' => Video::max('sort_order') + 1,
            'is_active' => true,
        ];

        if ($request->source_type === 'upload' && $request->hasFile('video_file')) {
            $data['file_path'] = $request->file('video_file')->store('videos', 'public');
        }

        Video::create($data);

        return back()->with('success', 'Video berhasil ditambahkan.');
    }

    public function update(Request $request, Video $video)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
        ]);

        $video->update([
            'title' => $request->title,
            'description' => $request->description,
            'is_active' => $request->boolean('is_active'),
        ]);

        return back()->with('success', 'Video berhasil diperbarui.');
    }

    public function destroy(Video $video)
    {
        if ($video->file_path) {
            Storage::disk('public')->delete($video->file_path);
        }

        $video->delete();

        return back()->with('success', 'Video berhasil dihapus.');
    }
}
