<?php

namespace App\Http\Controllers\Restaurant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Restaurant\ProductCategory;

use App\Helpers\Environment\SystemModulesHelper;

class ProductCategoryController extends Controller
{
  //* Constructor
    public function __construct() {
        $this->middleware(['auth', 'role:administrador']);
    }

  //* Basic CRUD
    public function index() {
      //- Avoid on disabled Module
        if (!SystemModulesHelper::getModuleStatus('restaurant'))
            return view('errors.403');

      //- Table Data
        if(request()->ajax()){
            return datatables()->of(ProductCategory::latest()->get())
                ->addColumn('created_at', function($data){
                    return date("d-m-Y, H:i:s", strtotime($data->created_at));
                })
                ->addColumn('updated_at', function($data){
                    return date("d-m-Y, H:i:s", strtotime($data->updated_at));
                })
                ->addColumn('action', function($data){

                    $extra_attribute = (in_array($data->category_code, ["SCP-01"])) ? 'disabled' : ''; // Disable Amenities

                    $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-ms"><i class="fa fa-edit"></i></button>';
                    $button .= '&nbsp;&nbsp;';
                    $button .= '<button type="button" '.$extra_attribute.' name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-ms"><i class="fa fa-trash"></i></button>';
                    return $button;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

      //- View Data
        return view('restaurant.product-categories.index');
    }

    public function store(Request $request) {
        $form_data = array(
            'category_name' => $request->titulo
        );
        ProductCategory::Create($form_data);

        return response()->json(['success' => 'Registrado con éxito']);
    }

    public function edit($id) {
        if(request()->ajax()){
            $data = ProductCategory::findOrFail($id);
            return response()->json(['data' => $data]);
        }

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = array(
            'category_name' => $request->titulo
        );
        ProductCategory::whereId($request->hidden_id)->update($form_data);
        return response()->json(['success', 'Actualizado con éxito']);
    }

    public function destroy($id) {
        $data = ProductCategory::findOrFail($id);
        $data->delete();
    }
}
