<?php

namespace App\DataTables;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTablesEditor;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;

class UserDataTableEditor extends DataTablesEditor
{
  protected $model = User::class;
  // protected $uploadDir = '';
  // protected $disk = 'modelliRicevute';

  protected $messages = [
    'nome.required' => 'Il nome è richiesto',
    'cognome.required' => 'Il cognome è richiesto',
    'email.required' => 'L\'email è richiesta',
    'ruolo.required' => 'Il ruolo è richiesto',
  ];

  /**
  * Get create action validation rules.
  *
  * @return array
  */
  public function createRules(): array
  {
    return [
      'nome'  => 'required',
      'cognome' => 'required',
      'email' => 'required',
      'ruolo_id' => 'required|exists:roles,id'
    ];
  }

  public function createMessages(): array{
    return $this->messages;
  }

  /**
  * Get edit action validation rules.
  *
  * @param Model $model
  * @return array
  */
  public function editRules(Model $model): array
  {
    return [
      'nome'  => 'required',
      'cognome' => 'required',
      'email' => 'required',
      'ruolo_id' => 'required|exists:roles,id'
    ];
  }

  public function editMessages(): array{
    return $this->messages;
  }

  /**
  * Get remove action validation rules.
  *
  * @param Model $model
  * @return array
  */
  public function removeRules(Model $model): array
  {
    return [];
  }

  public function creating(Model $model, array $data): array
  {
    // $model->roles()->sync([$data['ruolo_id']]);
    $this->tempRoleId = $data['ruolo_id'];
    $data['password'] = Hash::make(Str::random(8));
    return $data;
  }

  public function created(Model $model, array $data): Model
  {
    $model->roles()->sync([$this->tempRoleId]);
    return $model;
  }

  public function updating(Model $model, array $data): array
  {
    // dd($data['ruolo']);
    $model->roles()->sync([$data['ruolo_id']]);
    if(isset($data['password'])){
      $data['password'] = Hash::make($data['password']);
    }
    return $data;
  }

  public function messages(): array
  {
    return $this->messages;
  }

}
