<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\CategoryRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CategoryController extends Controller
{
    protected $categoryRepo;
    public function __construct(CategoryRepository $categoryRepository)
    {
        $this->categoryRepo = $categoryRepository;
    }


    public function index()
    {

        return $this->categoryRepo->indexPage();
    }

    public function createPage()
    {
        return $this->categoryRepo->createPage();

    }

    public function edit($id)
    {
        return $this->categoryRepo->editPage($id);

    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
        ]);
        $data = [
            'name'=>$request->name,
            'slug' => Str::slug($request->name),
        ];
        try {
            $this->categoryRepo->create($data);
            return redirect()->route('admin.category.list')->with('success', 'Category Successfully Added');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }

    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|max:255',
        ]);
        try {
            $this->categoryRepo->update($request->all(), $id);
            return redirect()->route('admin.category.list')->with('success', 'Category Successfully Updated');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());

        }

    }

    public function delete(Request $request)
    {
        $category = $this->categoryRepo->find($request->id);

        if ($category) {
            foreach ($category->products as $product) {
                $product->delete();
            }
            $this->categoryRepo->delete($request->id);
            return response()->json(['success' => 'Category and related products successfully deleted!']);
        } else {
            return response()->json(['error' => 'Category not found!'], 404);
        }
    }

}
