<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache; 

class PageController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Page::query();
        if ($search = $request->input('search')) {
            $query->where('title', 'like', "%{$search}%");
        }
        $pages = $query->orderBy('created_at', 'desc')->paginate(10);
        return response()->json($pages);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
            'status' => 'required|in:draft,published',
        ]);
        $data['slug'] = Str::slug($data['title']);

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

        Cache::forget('footer_pages'); 

        session()->flash('success', 'Page created successfully.');
        
        return response()->json($page, 201);
    }

    public function update(Request $request, Page $page): JsonResponse
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
            'status' => 'required|in:draft,published',
        ]);
        $data['slug'] = Str::slug($data['title']);

        $page->update($data);

        Cache::forget('footer_pages');

        session()->flash('success', 'Page updated successfully.');

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

    public function destroy(Page $page): JsonResponse
    {
        $page->delete();

        Cache::forget('footer_pages');

        return response()->json(null, 204);
    }
}