<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        return view('pages.admin.blog.index', [
            'posts' => Post::with('author')->latest()->get(),
        ]);
    }

    public function create()
    {
        return view('pages.admin.blog.form', [
            'post'       => null,
            'categories' => Post::categories(),
        ]);
    }

    public function store(Request $request)
    {
        $data = $this->validated($request);
        $data['slug']      = Post::makeSlug($data['title']);
        $data['author_id'] = auth()->id();

        Post::create($data);

        return redirect()->route('admin.blog.index')
                         ->with('success', 'Post criado com sucesso.');
    }

    public function edit(Post $post)
    {
        return view('pages.admin.blog.form', [
            'post'       => $post,
            'categories' => Post::categories(),
        ]);
    }

    public function update(Request $request, Post $post)
    {
        $data = $this->validated($request, $post);
        $data['slug'] = Post::makeSlug($data['title'], $post->id);

        $post->update($data);

        return redirect()->route('admin.blog.index')
                         ->with('success', 'Post atualizado.');
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return redirect()->route('admin.blog.index')
                         ->with('success', 'Post excluído.');
    }

    public function togglePublish(Post $post)
    {
        $post->update([
            'published_at' => $post->isPublished() ? null : now(),
        ]);
        return back()->with('success', $post->isPublished() ? 'Post publicado.' : 'Post despublicado.');
    }

    private function validated(Request $request, ?Post $post = null): array
    {
        $data = $request->validate([
            'title'       => 'required|string|max:255',
            'category'    => 'required|string',
            'cover_emoji' => 'nullable|string|max:10',
            'cover_url'   => 'nullable|url|max:500',
            'excerpt'     => 'nullable|string|max:400',
            'content'     => 'required|string',
            'publish'     => 'nullable|boolean',
        ]);

        $data['published_at'] = $request->boolean('publish')
            ? ($post?->published_at ?? now())
            : null;

        unset($data['publish']);
        return $data;
    }
}
