<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\CategoryRequest;
use App\Models\StoreCategory;
use Illuminate\Http\Request;

class StoreCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
        $this->theme = template();
    }

    public function index(Request $request)
    {
        $search = $request->all();
        $data['categories'] = StoreCategory::own($this->user->id)->withcount(['activeProducts'])
            ->when(isset($search['name']), function ($query) use ($search) {
                $query->where('name', 'LIKE', '%' . $search['name'] . '%');
            })
            ->when(isset($search['status']), function ($query) use ($search) {
                if ($search['status'] == 'active') {
                    $query->where('status', 1);
                } else {
                    $query->where('status', 0);
                }
            })
            ->orderBy('id', 'desc')->paginate(basicControl()->paginate);
        return view($this->theme . 'user.store.category.index', $data);
    }

    public function store(CategoryRequest $request)
    {
        $storeCategory = new StoreCategory();
        $storeCategory->user_id = $this->user->id;
        $storeCategory->name = $request->name;
        $storeCategory->status = $request->status;

        $storeCategory->save();
        session()->flash('success', 'Created Successfully');
        return response()->json([
            'status' => 'success',
            'url' => route('user.store.category.index')
        ]);
    }

    public function update(CategoryRequest $request)
    {
        $storeCategory = StoreCategory::own($this->user->id)->find($request->id);
        $storeCategory->name = $request->name;
        $storeCategory->status = $request->status;

        $storeCategory->save();
        session()->flash('success', 'Updated Successfully');
        return response()->json([
            'status' => 'success',
            'url' => route('user.store.category.index')
        ]);
    }

    public function delete($id)
    {
        $storeCategory = StoreCategory::own($this->user->id)->with(['products'])->findOrFail($id);
        if (count($storeCategory->products) > 0) {
            return back()->with('error', 'This category has lot of menu items');
        }
        $storeCategory->delete();
        return back()->with('success', 'Deleted Successfully');
    }
}
