<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Company;
use App\Models\PreSettings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class CategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:قائمة فئات الشركة', ['only' => ['index']]);
        $this->middleware('permission:اضافة فئة جديدة', ['only' => ['create', 'store']]);
        $this->middleware('permission: حذف فئة', ['only' => ['delete']]);
    }
    public function index()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $categories = $company->categories;
        return view('client.categories.index', compact('company', 'company_id', 'categories'));
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        return view('client.categories.create', compact('company_id', 'company'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'category_name' => 'required',
            'category_type' => 'required',
        ]);
        $data = $request->all();
        $company_id = $data['company_id'];
        $category = Category::create($data);
        return response()->json(['message'=>"تم إضافة الفئة بنجاح",'status'=>true]);

    }

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $category = Category::findOrFail($id);
        return view('client.categories.edit', compact('category', 'company_id', 'company'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'category_name' => 'required',
            'category_type' => 'required',
        ]);
        $input = $request->all();
        $category = Category::findOrFail($request->id);
        $category->update($input);
        return response()->json(['message'=>"تم تعديل الفئة بنجاح",'status'=>true]);

    }

    public function delete(Request $request)
    {
        Category::findOrFail($request->id)->delete();
        return response()->json(['message'=>"تم حذف الفئة بنجاح",'status'=>true]);
    }
}
