<?php

namespace App\Http\Controllers\Admin;

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

class PageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = Page::get();
            return datatables($query)->toJson();
        }
        return view('admin.page.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.page.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {

        $attributes =  $request->validate([
            'title' => 'required|string|max:100',
            'slug' => 'required|string|max:255',
            'status' => 'required|in:active,not_active',
            'content' => 'required|string',
        ]);

        Page::create($attributes);

        return to_route('pages.index')->with('success', __('trans.alert.success.done_create', ['name' => 'Page']));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Page $page)
    {
        return view('admin.page.edit', compact('page'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Page $page)
    {
        $attributes =  $request->validate([
            'title' => 'required|string|max:100',
            'slug' => 'required|string|max:255',
            'status' => 'required|in:active,not_active',
            'content' => 'required|string',
        ]);

        $page->update($attributes);

        return to_route('pages.index')->with('success', __('trans.alert.success.done_update', ['name' => 'Page']));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Page $page)
    {
        $page->delete();
        return to_route('pages.index')->with('success', __('trans.alert.success.done_delete', ['name' => 'Page']));
    }
}
