<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Video;
use App\Models\Category;
use Illuminate\Http\Request;

class VideoController extends Controller
{
    public function index()
    {
        $videos = Video::with(['user', 'category'])->orderBy('created_at', 'desc')->paginate(20);
        return view('admin.videos.index', compact('videos'));
    }

    public function create()
    {
        $categories = Category::where('active', true)->orderBy('name')->get();
        return view('admin.videos.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'provider' => 'required|in:youtube,vimeo,upload,embed',
            'url' => 'required|string',
            'category_id' => 'nullable|exists:categories,id',
            'description' => 'nullable|string',
            'publish_on_site' => 'boolean',
            'push_notification' => 'boolean',
        ]);

        $video = new Video($validated);
        $video->user_id = auth()->id();
        $video->status = $request->status ?? 'draft';

        // Extrair provider_id se for YouTube
        if ($validated['provider'] === 'youtube' && preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/', $validated['url'], $matches)) {
            $video->provider_id = $matches[1];
            $video->thumbnail = "https://img.youtube.com/vi/{$matches[1]}/maxresdefault.jpg";
        }

        if ($request->status === 'published') {
            $video->published_at = now();
        }

        $video->save();

        return redirect()->route('admin.videos.index')
            ->with('success', 'Vídeo criado com sucesso!');
    }

    public function edit(Video $video)
    {
        $categories = Category::where('active', true)->orderBy('name')->get();
        return view('admin.videos.edit', compact('video', 'categories'));
    }

    public function update(Request $request, Video $video)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'provider' => 'required|in:youtube,vimeo,upload,embed',
            'url' => 'required|string',
            'category_id' => 'nullable|exists:categories,id',
            'description' => 'nullable|string',
            'status' => 'required|in:draft,published,archived',
        ]);

        $video->update($validated);

        if ($request->status === 'published' && !$video->published_at) {
            $video->published_at = now();
            $video->save();
        }

        return redirect()->route('admin.videos.index')
            ->with('success', 'Vídeo atualizado com sucesso!');
    }

    public function destroy(Video $video)
    {
        $video->delete();
        return redirect()->route('admin.videos.index')
            ->with('success', 'Vídeo excluído com sucesso!');
    }
}

