<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    //
    public function index(){
        //get all categories
        $categories = Category::orderBy("created_at", "DESC")->get();
        return view('admin.category')->with("categories", $categories);
    }

    public function store(Request $request){
        //validate
        $request->validate([
            'name' => 'required',
            'takeaway' => 'required',
        ]);

        $slug = strtolower(preg_replace('/\s+/', '_', $request->name));
        if($request->sort == null) {
            $sort = 0;
        }else{
            $sort = $request->sort;
        }
        try{
            Category::create([
                "name" => $request->name,
                "description" => $request->description,
                "slug" => $slug,
                "takeaway" => $request->takeaway,
                "sort" => $sort,
            ]);
            return redirect()->back()->with("success", "Category Added");
        }catch(Exception $e){
       
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }

    }

    public function editModal($id){
        $category = Category::find($id);
        $view = view('modals.category.edit-category', compact('category'))->render();
        return response()->json(['html'=>$view]);
    }

    public function deleteModal($id){
        $category = Category::find($id);
        $view = view('modals.category.delete-category', compact('category'))->render();
        return response()->json(['html'=>$view]);
    }


    public function update(Request $request){
        //validate
        $request->validate([
            'name' => 'required',
            'takeaway' => 'required',
        ]);

        $slug = strtolower(preg_replace('/\s+/', '_', $request->name));
        if($request->sort == null){
            $sort = 0;
        }else{
            $sort = $request->sort;
        }
        try{
            Category::where("id", $request->id)->update(
                [
                    'name' => $request->name,
                    'description' => $request->description,
                    'slug' => $slug,
                    'takeaway' => $request->takeaway,
                    "sort" => $sort,
                ]
            );
            return redirect()->back()->with("success", "Category Updated");
        }catch(Exception $e){
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }
    }

    public function delete(Request $request){
        try {
            Category::where("id", $request->id)->delete();
            return redirect()->back()->with("success", "Category Deleted");
        } catch (Exception $e) {
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }
    }
}
