<?php

namespace App\Http\Controllers\Hotel;

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

use App\Models\Hotel\Source;

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

  //* Basic CRUD
    public function index() {
      //- Table Data
        if(request()->ajax()){
            return datatables()->of(Source::latest()->get())
                ->addColumn('source_name', function($data){
                    return ($data->id === 3)
                        ? __('entities')['hotel']['agency']
                        : $data->source_name;
                })
                ->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 === 3) ? 'disabled' : '';

                    $button = '<button '.$extra_attribute.' 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.sources.index');
    }

    public function store(Request $request) {
        $form_data = array(
            'source_name' => $request->nombre
        );
        Source::Create($form_data);
        return response()->json(['success' => 'Registrado con éxito']);
    }

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

        return view('errors.404');
    }

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

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