<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::latest()->paginate(6);

        return view('pages.blog', compact('posts'));
    }

    public function create()
    {
        return view('pages.blog-create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'excerpt' => 'nullable|string|max:2000',
            'content' => 'required|string',
            'image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:10240',
        ]);

        if ($request->hasFile('image')) {
            $data['image_path'] = $request->file('image')->store('posts', 'public');
        }

        Post::create($data);

        return redirect()->route('blog')->with('success', 'Blog post published successfully.');
    }

    public function show(Post $post)
    {
        return view('pages.blog-show', compact('post'));
    }

    public function destroy(Post $post)
    {
        if ($post->image_path) {
            \Illuminate\Support\Facades\Storage::disk('public')->delete($post->image_path);
        }
        
        $post->delete();

        return redirect()->route('blog')->with('success', 'Blog post deleted successfully.');
    }
}
