<?php

namespace App\Http\Controllers\Restaurant;

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

use App\Models\Restaurant\Table;

use App\Helpers\Environment\SystemModulesHelper;

class TableController 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(Table::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){
                    $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" 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.tables.index");
    }

    public function store(Request $request) {
        $form_data = array(
            'table_name' => $request->titulo
        );
        Table::create($form_data);

        return response()->json(['success' => 'Exito' ]);
    }

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

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = array(
            'table_name' => $request->titulo
        );
        Table::whereId($request->hidden_id)->update($form_data);

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

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