<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class BlogPostController extends Controller
{
    public function index()
    {
        $posts = BlogPost::latest()->paginate(10);
        return view('admin.posts.index', ['posts' => $posts]);
    }

    public function create()
    {
        return view('admin.posts.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category' => 'required|string|max:100',
            'excerpt' => 'required|string|max:500',
            'content' => 'required|string',
            'read_time' => 'nullable|string|max:50',
            'image' => 'nullable|string',
        ]);

        BlogPost::create([
            'title' => $request->title,
            'slug' => Str::slug($request->title) . '-' . rand(100, 999),
            'category' => $request->category,
            'excerpt' => $request->excerpt,
            'content' => $request->content,
            'read_time' => $request->read_time ?? '5 min read',
            'image' => $request->image ?? 'images/blog/b1.svg',
            'is_published' => $request->has('is_published'),
        ]);

        return redirect()->route('admin.posts.index')->with('success', 'Blog article published!');
    }

    public function edit(BlogPost $post)
    {
        return view('admin.posts.edit', ['post' => $post]);
    }

    public function update(Request $request, BlogPost $post)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category' => 'required|string|max:100',
            'excerpt' => 'required|string|max:500',
            'content' => 'required|string',
            'read_time' => 'nullable|string|max:50',
            'image' => 'nullable|string',
        ]);

        $post->update([
            'title' => $request->title,
            'category' => $request->category,
            'excerpt' => $request->excerpt,
            'content' => $request->content,
            'read_time' => $request->read_time ?? $post->read_time,
            'image' => $request->image ?? $post->image,
            'is_published' => $request->has('is_published'),
        ]);

        return redirect()->route('admin.posts.index')->with('success', 'Blog article updated!');
    }

    public function destroy(BlogPost $post)
    {
        $post->delete();
        return redirect()->route('admin.posts.index')->with('success', 'Blog post deleted.');
    }
}
