<?php

namespace App\Http\Controllers;

use App\Http\Requests\StaticPageRequest;
use App\Model\StaticPage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class StaticPageController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:admin', 'admin.active']);
        $this->authorizeResource(StaticPage::class, 'static_page');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = StaticPage::query()
                ->filters($request);

            return StaticPage::makeDataTable($data);
        }

        return view('admin.staticpage.index');
    }

    public function trashed(Request $request)
    {
        $this->authorize('restore', StaticPage::class);

        if ($request->ajax()) {
            $data = StaticPage::onlyTrashed();

            return StaticPage::makeDataTable($data, trash: true);
        }

        return view('admin.staticpage.trashed');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.staticpage.create', [
            'static_page' => new StaticPage(),
            'unsluggable' => false
        ]);
    }

    public function reorder(Request $request) {
        $this->authorize('update', StaticPage::class);

        if ($request->ajax()) {
            foreach ($request->input('rows', []) as $key => $row) {
                StaticPage::find($row['id'])->update([
                    'position' => $row['position']
                ]);
            }

            return response()->noContent();
        }

        abort(403);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StaticPageRequest  $request
     * @param  \App\Model\StaticPage  $static_page
     * @return \Illuminate\Http\Response
     */
    public function store(StaticPageRequest $request, StaticPage $static_page)
    {
        $static_page->create(array_merge($request->validated(), [
            'slug' => Str::slug($request->slug ?: $request->title),
            'editor_content' => remove_break_new_lines(str_replace(['<p></p>', '<div></div>'], '<br>', $content = $request->input('editor_content'))),
            'plain_content' => strlen($content) ? html_entity_decode(strip_tags($content)) : '',
            'is_active' => $request->boolean('is_active'),
            'on_menu' => $request->boolean('on_menu'),
            'on_footer' => $request->boolean('on_footer'),
        ]));

        return redirect()->route('static-page.index')->withStatus(__('New page successfully created.'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Model\StaticPage  $static_page
     * @return \Illuminate\Http\Response
     */
    public function edit(StaticPage $static_page)
    {
        return view('admin.staticpage.edit', [
            'static_page' => $static_page,
            'unsluggable' => in_array($static_page->id, StaticPage::unDeletedPages())
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\StaticPageRequest  $request
     * @param  \App\Model\StaticPage  $static_page
     * @return \Illuminate\Http\Response
     */
    public function update(StaticPageRequest $request, StaticPage $static_page)
    {
        $static_page->update(array_merge($request->validated(), [
            'slug' => in_array($static_page->id, StaticPage::unDeletedPages()) ? $static_page->slug : Str::slug($request->slug ?: $request->title),
            'editor_content' => remove_break_new_lines(str_replace(['<p></p>', '<div></div>'], '<br>', $content = $request->input('editor_content'))),
            'plain_content' => strlen($content) ? html_entity_decode(strip_tags($content)) : '',
            'is_active' => $request->boolean('is_active'),
            'on_menu' => $request->boolean('on_menu'),
            'on_footer' => $request->boolean('on_footer'),
        ]));

        return redirect()->route('static-page.index')->withStatus(__("Page #$static_page->id successfully updated."));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Model\StaticPage  $static_page
     * @return \Illuminate\Http\Response
     */
    public function destroy(StaticPage $static_page)
    {
        $redirect = redirect()->route('static-page.index');

        if (in_array($static_page->id, StaticPage::unDeletedPages())) {
            return $redirect->withStatus(__("Page #$static_page->id can't be deleted."));
        }

        $static_page->delete();

        return $redirect->withStatus(__("Page #$static_page->id successfully deleted."));
    }

    public function restore($id)
    {
        $redirect = redirect()->route('static-page.trashed');

        $page = StaticPage::onlyTrashed()->findOrFail($id);

        $this->authorize('restore', $page);

        if ($page->trashed()) {
            $page->restore();

            return $redirect->withStatus(__("Page #$page->id successfully restored."));
        }

        return $redirect->withErrors(__("Page #$page->id cannot be restored."));
    }

    public function menus()
    {
        $this->authorize('create', StaticPage::class);

        abort(404);

        return view('admin.staticpage.menus', [
            'menus' => StaticPage::with('children')->whereNull('parent_id')->orderBy('on_menu_position')->get()
        ]);
    }

    public function menusUpdate(Request $request)
    {
        abort(404);

        $this->authorize('create', StaticPage::class);

        $processed_ids = [];

        foreach (json_decode($request->get('menus', '[]')) as $order => $obj) {
            $array = (array) $obj;

            if (intval(key($array)) === 0) {
                $parent_id = null;
            } else {
                $parent_id = intval(key($array));
            }

            $page_id = current($array);

            if (!in_array($page_id, $processed_ids)) {
                StaticPage::where('id', $page_id)->update([
                    'on_menu_position' => $order,
                    'parent_id' => $parent_id
                ]);

                array_push($processed_ids, $page_id);
            }
        }

        return redirect()->route('static-page.menus')->withStatus(__('All menus are successfully updated.'));
    }
}
