<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use function current_user;
use function current_user_has_role;


class PostController extends Controller
{
    /**
     * GET ALL POSTS (Admin only)
     */
    public function index()
    {
        if (!current_user_has_role('Admin')) {
            return response()->json(['message' => 'Access denied'], 403);
        }
        return response()->json(Post::with('user')->get());
    }

    /**
     * CREATE POST (Admin only)
     */
    public function store(Request $request)
    {
        if (!current_user_has_role('Admin')) {
            return response()->json(['message' => 'Access denied'], 403);
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required',
        ]);

        $post = Post::create([
            'user_id' => current_user()->id,
            'title' => $validated['title'],
            'content' => $validated['content']
        ]);

        return response()->json(['message' => 'Post created successfully', 'post' => $post], 201);
    }

    /**
     * VIEW POST (All logged-in users)
     */
    public function show($id)
    {
        $post = Post::find($id);
        if (!$post) return response()->json(['message' => 'Post not found'], 404);

        return response()->json($post);
    }

    /**
     * UPDATE POST (Admin only)
     */
    public function update(Request $request, $id)
    {
        if (!current_user_has_role('Admin')) {
            return response()->json(['message' => 'Access denied'], 403);
        }

        $post = Post::find($id);
        if (!$post) return response()->json(['message' => 'Post not found'], 404);

        $validated = $request->validate([
            'title' => 'sometimes|string|max:255',
            'content' => 'sometimes',
        ]);

        $post->update($validated);

        return response()->json(['message' => 'Post updated successfully', 'post' => $post]);
    }

    /**
     * DELETE POST (Admin only)
     */
    public function destroy($id)
    {
        if (!current_user_has_role('Admin')) {
            return response()->json(['message' => 'Access denied'], 403);
        }

        $post = Post::find($id);
        if (!$post) return response()->json(['message' => 'Post not found'], 404);

        $post->delete();

        return response()->json(['message' => 'Post deleted successfully']);
    }
}
