<?php

namespace App\Http\Controllers\Hotel;

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

use App\Models\Hotel\Regimen;

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

  //* Basic CRUD
    public function index() {
      //- Table Data
        if(request()->ajax()){
            return datatables()->of(Regimen::latest()->get())
                ->addColumn('regimen_status', function($data){
                    return __('neutral_words')[$data->regimen_status];
                })
                ->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 = $data->id === 1 ? "disabled" : "";

                    $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
        $regiment_length = Regimen::all()->count();
        $regimens = Regimen::all();
        return view('hotel.regimens.index', compact(['regimens','regiment_length']));
    }

    public function store(Request $request) {
        $form_data = array(
            'regimen_name' => $request->titulo,
            'regimen_code' => $request->codigo,
            'regimen_status'=> $request->estatus
        );
        Regimen::Create($form_data);

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

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

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = array(
            'regimen_name' => $request->titulo,
            'regimen_code' => $request->codigo,
            'regimen_status'=> $request->estatus
        );
        Regimen::whereId($request->hidden_id)->update($form_data);

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

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