<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Products\Category\ProductCategoryCreateRequest;
use App\Http\Requests\Products\Category\ProductCategoryDeleteRequest;
use App\Http\Requests\Products\Category\ProductCategoryUpdateRequest;
use App\Services\ProductCategoryService;
use Laracasts\Flash\Flash;

class AdminProductCategoriesController extends Controller
{
    protected $data = [];
    private $productCategoryService;

    public function __construct(ProductCategoryService $productCategoryService)
    {
        $this->data['title'] = 'Product Categories';

        $this->productCategoryService = $productCategoryService;
    }

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

        if ($searchTerm) {
            $this->data['productCategories'] = $this->productCategoryService->filter($searchTerm, $perPage = 10);
        } else {
            $this->data['productCategories'] = $this->productCategoryService->paginate($perPage = 10);
        }

        $this->data['allCategories'] = $this->productCategoryService->all();

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

    public function create()
    {
        $this->data['title'] = 'Add New Product Category';

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

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

        $productCategory = $this->productCategoryService->store($validateData);

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

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

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

        $this->data['productCategory'] = $this->productCategoryService->find($id);

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

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

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

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

        return redirect()->back();
    }

    public function destroy(ProductCategoryDeleteRequest $request)
    {
        $validateData = $request->validated();

        try {
            $this->productCategoryService->delete($validateData);

            Flash::success('Product Categories deleted successfully.');

            return response()->json(['success' => true]);
        } catch (\Exception $ex) {
            Flash::error('Failed to delete product categories: ' . $ex->getMessage());

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