<?php

namespace App\Http\Controllers\Admin;

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

class PageController extends Controller
{
    public function index()
    {
        $pages = Page::latest()->paginate(15);
        return view('admin.pages.index', compact('pages'));
    }

    public function create()
    {
        return view('admin.pages.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'            => 'required|string|max:255',
            'slug'             => 'nullable|string|max:255|unique:pages,slug',
            'content'          => 'nullable|string',
            'meta_description' => 'nullable|string|max:300',
            'status'           => 'required|in:draft,published',
            'show_in_footer'   => 'boolean',
        ]);

        $validated['slug'] = $validated['slug']
            ? Str::slug($validated['slug'])
            : Page::generateSlug($validated['title']);

        $validated['show_in_footer'] = $request->boolean('show_in_footer');

        Page::create($validated);

        return redirect()->route('admin.pages.index')
            ->with('success', 'Halaman "' . $validated['title'] . '" berhasil dibuat.');
    }

    public function edit(Page $page)
    {
        return view('admin.pages.edit', compact('page'));
    }

    public function update(Request $request, Page $page)
    {
        $validated = $request->validate([
            'title'            => 'required|string|max:255',
            'slug'             => 'nullable|string|max:255|unique:pages,slug,' . $page->id,
            'content'          => 'nullable|string',
            'meta_description' => 'nullable|string|max:300',
            'status'           => 'required|in:draft,published',
            'show_in_footer'   => 'boolean',
        ]);

        $validated['slug'] = $validated['slug']
            ? Str::slug($validated['slug'])
            : Page::generateSlug($validated['title']);

        $validated['show_in_footer'] = $request->boolean('show_in_footer');

        $page->update($validated);

        return redirect()->route('admin.pages.index')
            ->with('success', 'Halaman "' . $validated['title'] . '" berhasil diperbarui.');
    }

    public function destroy(Page $page)
    {
        $title = $page->title;
        $page->delete();

        return redirect()->route('admin.pages.index')
            ->with('success', 'Halaman "' . $title . '" berhasil dihapus.');
    }
}
