<?php

namespace App\Http\Controllers\Api\Admin;

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

class PageController extends Controller
{
    /**
     * List all pages.
     */
    public function index()
    {
        $pages = Page::orderBy('created_at', 'desc')->get();

        return response()->json(['data' => $pages]);
    }

    /**
     * Create page.
     */
    public function store(Request $request)
    {
        $request->validate([
            'title_ar' => 'required|string|max:255',
            'title_en' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:pages,slug',
            'content_ar' => 'nullable|string',
            'content_en' => 'nullable|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

        $slug = $request->slug ?? Str::slug($request->title_en ?: $request->title_ar);
        $originalSlug = $slug;
        $counter = 1;
        while (Page::where('slug', $slug)->exists()) {
            $slug = $originalSlug . '-' . $counter++;
        }

        $page = Page::create([
            'title_ar' => $request->title_ar,
            'title_en' => $request->title_en,
            'slug' => $slug,
            'content_ar' => $request->content_ar,
            'content_en' => $request->content_en,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'is_active' => $request->boolean('is_active', true),
        ]);

        return response()->json([
            'message' => 'تم إنشاء الصفحة بنجاح',
            'data' => $page,
        ], 201);
    }

    /**
     * Show single page.
     */
    public function show(Page $page)
    {
        return response()->json(['data' => $page]);
    }

    /**
     * Update page.
     */
    public function update(Request $request, Page $page)
    {
        $request->validate([
            'title_ar' => 'sometimes|required|string|max:255',
            'title_en' => 'sometimes|required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:pages,slug,' . $page->id,
            'content_ar' => 'nullable|string',
            'content_en' => 'nullable|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

        $page->update($request->all());

        return response()->json([
            'message' => 'تم تحديث الصفحة بنجاح',
            'data' => $page,
        ]);
    }

    /**
     * Delete page.
     */
    public function destroy(Page $page)
    {
        $page->delete();

        return response()->json([
            'message' => 'تم حذف الصفحة بنجاح',
        ]);
    }
}
