<?php

namespace App\Http\Controllers\Admin\Settings\Pages;

use App\Http\Controllers\Controller;
use App\Models\FrontendSection;
use App\Models\Page;
use App\Services\ModalIndexQuey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PageController extends Controller
{
    public function index()
    {
        adminUserHasPermission(permission: 'read');

        $buttons = [
            [
                'label' => __('Create New Page'),
                'icon' => 'ph ph-plus-bold',
                'type' => 'modal',
                'id' => 'page_add_modal_id',
                'href' => route('admin.settings.pages.create'),
            ],
        ];

        $pages = ModalIndexQuey::get(model: Page::query());

        $columns = [
            [
                'label' => '#',
                'header_class' => 'lg:w-[200px]',
                'key' => 'id',
            ],
            [
                'label' => __('Title|Name'),
                'key' => 'name',
                'is_sortable' => true,
                'render' => function ($page) {
                    return '<a href="'.route('admin.settings.pages.edit', $page).'" class="flex flex-col items-start gap-3">
                      <span>'.$page->title.'</span>
                    <div>
                        <span class="text-xs">@'.$page->slug.'</span>
                    </div>
                </a>';
                },
            ],
            [
                'label' => __('Status'),
                'key' => 'status',
                'is_sortable' => true,
                'render' => function ($page) {
                    $color = $page->status == 'active' ? 'success' : 'danger';

                    return '<span class="status '.$color.' capitalize">'.__($page->status).'</span>';
                },
            ],
            [
                'label' => __('Action'),
                'render' => function ($page) {
                    $action_buttons = [
                        [
                            'label' => __('Edit Sections'),
                            'icon' => 'ph ph-list',
                            'type' => 'link',
                            'href' => route('admin.settings.pages.edit', $page->id),
                        ],
                        [
                            'label' => __('Setup Seo'),
                            'icon' => 'ph ph-gear',
                            'type' => 'link',
                            'href' => route('admin.settings.pages.seo.index', $page->id),
                        ],
                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'modal',
                            'row' => $page,
                            'id' => 'page-edit-modal',
                            'href' => route('admin.settings.pages.update', $page->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'class' => 'form-submit-delete',
                            'href' => route('admin.settings.pages.destroy', $page->id),
                        ],
                        [
                            'label' => $page->status == 'active' ? __('InActive') : __('Active'),
                            'icon' => $page->status == 'active' ? 'ph ph-toggle-left' : 'ph ph-toggle-right',
                            'type' => 'link',
                            'href' => route('admin.settings.page.change-status', $page->id),
                        ],
                    ];

                    return view('admin.components.table-action', compact('action_buttons'))->render();
                },
            ],
        ];

        return view('admin.pages.settings.manage-pages.index', compact('columns', 'pages', 'buttons'));
    }

    public function store(Request $request)
    {
        adminUserHasPermission(permission: 'create');

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:pages',
        ]);

        Page::create($validated);

        Cache::forget('pages_list');

        return response()->json(['message' => __('Page created successfully'), 'reload' => true]);
    }

    public function edit(Page $page)
    {
        adminUserHasPermission(permission: 'edit');
        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-left',
                'type' => 'link',
                'link' => route('admin.settings.pages.index'),
            ],
            [
                'label' => __('Seo Setup'),
                'icon' => 'ph ph-gear',
                'type' => 'link',
                'link' => route('admin.settings.pages.seo.index', $page),
            ],
        ];

        $page = $page->load('sections');

        $sections = FrontendSection::all();

        return view('admin.pages.settings.manage-pages.edit', compact('page', 'sections', 'buttons'));
    }

    public function update(Request $request, Page $page)
    {
        adminUserHasPermission(permission: 'edit');

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:pages,slug,'.$page->id,
        ]);

        if ($page->is_default) {
            return response()->json(['message' => __('You can not update default page')]);
        }

        $page->update($validated);

        Cache::forget('pages_list');

        return response()->json(['message' => __('Page updated successfully')]);
    }

    public function destroy(Page $page)
    {
        adminUserHasPermission(permission: 'delete');

        if ($page->is_default) {
            return response()->json(['message' => __('You can not delete default page')]);
        }

        $page->delete();

        Cache::forget('pages_list');

        return response()->json(['message' => __('Page deleted successfully')]);
    }

    public function changeStatus(Page $page)
    {
        adminUserHasPermission(permission: 'edit');

        $count = Page::where('id', '!=', $page->id)->where('status', 'active')->count();

        if ($count == 2) {
            return back()->with('error', __('You can only have 2 active pages'));
        }

        if ($page->is_default) {
            return back()->with('error', __('You can not change status of default page'));
        }

        $page->update([
            'status' => $page->status == 'active' ? 'inactive' : 'active',
        ]);

        Cache::forget('pages_list');

        return back()->withSuccess(__('Status changed successfully'));
    }

    public function updateSection(Request $request, Page $page)
    {
        adminUserHasPermission(permission: 'edit');

        if ($page->is_default) {
            return response()->json(['message' => __('You can not update default page')]);
        }

        $request->validate([
            'sections' => 'required|array',
            'sections.*.id' => 'required|exists:frontend_sections,id',
            'sections.*.order' => 'required|numeric',
        ]);

        $sectionsData = collect($request->sections)->mapWithKeys(function ($section) {
            return [$section['id'] => ['order' => $section['order']]];
        })->all();

        $page->sections()->sync($sectionsData);

        Cache::forget('pages_list');

        return response()->json(['message' => __('Page sections updated successfully')]);
    }
}
