<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class PageController extends Controller
{
    /**
     * List all pages
     */
    public function index(Request $request): JsonResponse
    {
        $query = Page::query()->orderBy('order')->orderBy('created_at', 'desc');

        // Optional: Filter by template if we want to separate "Contracts"
        if ($request->has('template')) {
            $query->where('template', $request->template);
        }

        $pages = $query->get();

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

    /**
     * Get single page
     */
    public function show(int $id): JsonResponse
    {
        $page = Page::findOrFail($id);
        return response()->json($page);
    }

    /**
     * Create new page
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:pages',
            'template' => 'required|string', // 'contract', 'content', etc.
            'sections' => 'nullable|array',
            'published' => 'boolean',
            'order' => 'integer',
        ]);

        $page = Page::create($validated);

        return response()->json($page, 201);
    }

    /**
     * Update page
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $page = Page::findOrFail($id);

        $validated = $request->validate([
            'title' => 'sometimes|string|max:255',
            'slug' => 'sometimes|string|max:255|unique:pages,slug,' . $id,
            'template' => 'sometimes|string',
            'sections' => 'nullable|array',
            'published' => 'boolean',
            'order' => 'integer',
        ]);

        $page->update($validated);

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

    /**
     * Delete page
     */
    public function destroy(int $id): JsonResponse
    {
        $page = Page::findOrFail($id);
        $page->delete();

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