<?php

namespace App\Http\Controllers\Hotel;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

use App\Models\Hotel\RoomGroup;

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

  //* Basic CRUD
    public function index() {
      //- Table Data
        if(request()->ajax()){
            return datatables()->of(RoomGroup::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 = ($data->id === 1) ? 'disabled' : ''; // Disable Unassigned Group

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

      //- View Data
        return view('hotel.room-groups.index');
    }

    public function store(Request $request) {
        $form_data = array(
            'name' => $request->titulo,
            'color'  => $request->color
        );
        RoomGroup::Create($form_data);

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

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

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = array(
            'name' => $request->titulo,
            'color'  => $request->color
        );
        RoomGroup::whereId($request->hidden_id)->update($form_data);

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

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