<?php

namespace App\Http\Controllers\Modules;

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

use App\Models\Modules\Shift;

use App\Helpers\Environment\SystemModulesHelper;

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

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

      //- Table Data
        if(request()->ajax()){
            return datatables()->of(Shift::latest()->get())
                ->addColumn('work_starts_at', function($data){
                    return Carbon::createFromFormat('H:i:s', $data->work_starts_at)->format('H:i');
                })
                ->addColumn('work_ends_at', function($data){
                    return Carbon::createFromFormat('H:i:s', $data->work_ends_at)->format('H:i');
                })
                ->addColumn('action', function($data){

                    $extra_attribute = ($data->id === 1) ? 'disabled' : ''; // Disable Shift

                    $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 type="button" '.$extra_attribute.' 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('modules.shifts.index');
    }

    public function store(Request $request) {
        $form_data = array(
            'name' => $request->name,
            'work_starts_at'  => $request->start,
            'work_ends_at'  => $request->end,
        );
        Shift::Create($form_data);

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

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

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = array(
            'name' => $request->name,
            'work_starts_at'  => $request->start,
            'work_ends_at'  => $request->end,
        );
        Shift::whereId($request->hidden_id)->update($form_data);

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

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