<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Post::with('user:id,name')
            ->where('is_published', true)
            ->latest('published_at')
            ->get();
    }

    /**
     * Display all posts (including drafts) for the admin dashboard.
     */
    public function adminIndex()
    {
        return Post::with('user:id,name')->latest()->get();
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'slug' => ['required', 'string', 'max:255', 'unique:posts,slug'],
            'excerpt' => ['nullable', 'string', 'max:255'],
            'featured_image' => ['nullable', 'string', 'max:500'],
            'content' => ['nullable', 'string'],
            'is_published' => ['boolean'],
        ]);

        $data['user_id'] = $request->user()->id;
        $data['published_at'] = ($data['is_published'] ?? false) ? now() : null;

        return response()->json(Post::create($data), 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $slug)
    {
        return Post::with('user:id,name')
            ->where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();
    }

    /**
     * Display the specified resource (including drafts) for the admin dashboard.
     */
    public function adminShow(Post $post)
    {
        return $post->load('user:id,name');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Post $post)
    {
        $data = $request->validate([
            'title' => ['sometimes', 'string', 'max:255'],
            'slug' => ['sometimes', 'string', 'max:255', 'unique:posts,slug,' . $post->id],
            'excerpt' => ['nullable', 'string', 'max:255'],
            'featured_image' => ['nullable', 'string', 'max:500'],
            'content' => ['nullable', 'string'],
            'is_published' => ['boolean'],
        ]);

        if (($data['is_published'] ?? false) && ! $post->is_published) {
            $data['published_at'] = now();
        }

        $post->update($data);

        return $post;
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Post $post)
    {
        $post->delete();

        return response()->noContent();
    }
}
