<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Page\PageBulkDestroyRequest;
use App\Http\Requests\Page\PageCreateRequest;
use App\Http\Requests\Page\PageUpdateRequest;
use App\Services\PageService;
use Laracasts\Flash\Flash;

class AdminPagesController extends Controller
{
    protected array $data;

    public function __construct(PageService $pageService)
    {
        $this->data['title'] = 'Pages';
        $this->pageService = $pageService;
    }

    public function index()
    {
        $searchTerm = request('search');
        $is_published = request('is_published');

        if ($searchTerm || $is_published) {
            $this->data['pages'] = $this->pageService->filter($searchTerm, $is_published, $perPage = 10);
        } else {
            $this->data['pages'] = $this->pageService->paginate($perPage = 10);
        }

        return view('admin.pages.index', $this->data);
    }

    public function create()
    {
        $this->data['title'] = 'Create Page';

        return view('admin.pages.create', $this->data);
    }

    public function store(PageCreateRequest $request)
    {
        $validateData = $request->validated();

        $page = $this->pageService->store($validateData);

        Flash::success('Page created successfully.');

        return redirect()->route('ch-admin.pages.edit', [$page->id]);
    }

    public function edit($id)
    {
        $this->data['title'] = 'Edit Page';

        $this->data['page'] = $this->pageService->find($id);

        return view('admin.pages.edit', $this->data);
    }

    public function update(PageUpdateRequest $request, $id)
    {
        $validateData = $request->validated();

        $this->data['productCategory'] = $this->pageService->update($validateData, $id);

        Flash::success('Page updated successfully.');

        return redirect()->back();
    }

    public function destroy($id)
    {
        try {
            $this->pageService->destroy($id);

            Flash::success('Page deleted successfully.');

            return redirect()->back();

        } catch (\Exception $e) {
            Flash::error('Error deleting page: ' . $e->getMessage());

            return redirect()->back();
        }
    }

    public function bulkDestroy(PageBulkDestroyRequest $request)
    {
        $validateData = $request->validated();

        try {
            $this->pageService->bulkDestroy($validateData);

            Flash::success('Pages deleted successfully.');

            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            Flash::error('Error deleting pages: ' . $e->getMessage());

            return response()->json(['success' => false]);
        }
    }
}
