<?php

namespace App\Http\Controllers;

use App\Http\Resources\PostResource;
use App\Models\Post;
use App\Http\Requests\StorePostRequest;
use Inertia\Inertia;

class PostController extends Controller
{
    public function index(){
//        sleep(3);

        $posts = Post::with(['user'])->get()->sortByDesc('created_at');

        return Inertia::render('Posts/Index',[
            'posts'=>PostResource::collection($posts),
            'can'=>[
                'post_create'=>auth()->user()->can('create',Post::class)
            ],
            'now'=>now(),
        ]);
    }

    public function store(StorePostRequest $request){

//        abort(403);

        auth()->user()->posts()->create($request->validated());

        return redirect()->route('posts.index')
            ->with('success','Post created successfully');

//        return redirect()->route('posts.index')->with('message',[
//            'type' => 'success',
//            'body' => 'Post created successfully',
//        ]);
    }
}
