<?php

namespace App\DataTables;

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

class AttivitaDataTableEditor extends DataTablesEditor
{
  protected $model = Attivita::class;
  protected string $uploadDir = '';
  protected string $disk = 'copertinaAttivita';

  protected $messages = [
    'nome.required' => 'Il nome è richiesto',
    'descrizione.required' => 'La descrizione è richiesta',
    'icona.required' => 'L\'icona è richiesta',
    'colore.required' => 'Il colore è richiesto',
    'tipo.required' => 'Il tipo è richiesto',
    'is_attiva.required' => 'Indicare una delle due opzioni',
  ];

  /**
  * Get create action validation rules.
  *
  * @return array
  */
  public function createRules(): array
  {
    return [
      'nome'  => 'required',
      'descrizione' => 'nullable',
      'icona' => 'nullable|string',
      'colore' => 'nullable|string',
      'tipo' => 'nullable|string',
      'is_attiva' => 'boolean',
    ];
  }

  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',
      'descrizione' => 'nullable',
      'icona' => 'nullable|string',
      'colore' => 'nullable|string',
      'tipo' => 'nullable|string',
      'is_attiva' => 'boolean',
    ];
  }

  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']]);
    $data['is_attiva'] = isset($data['is_attiva']) ? true : false;
    return $data;
  }

  public function updating(Model $model, array $data): array
  {
    // dd($data['ruolo']);
    // $model->roles()->sync([$data['ruolo_id']]);
    $data['is_attiva'] = isset($data['is_attiva']) ? true : false;
    return $data;
  }

  public function created(Model $model, array $data): Model
  {
    return $model;
  }

  public function upload(Request $request): JsonResponse
  {
    $this->action = 'upload';

    $field   = $request->input('uploadField');
    $storage = Storage::disk($this->disk);

    try {
      $rules      = $this->uploadRules();
      $fieldRules = ['upload' => data_get($rules, $field, [])];

      $this->validate($request, $fieldRules, $this->messages(), $this->attributes());

      $uploadedFile = $request->file('upload');
      $filename     = $this->getUploadedFilename($field, $uploadedFile);
      $id           = $storage->putFileAs($request->id, $uploadedFile, $filename);

      if (method_exists($this, 'uploaded')) {
        $id = $this->uploaded($id);
      }

      return response()->json([
        'action' => $this->action,
        'data'   => [],
        'files'  => [
          'files' => [
            $id => [
              'filename'      => $id,
              'original_name' => $uploadedFile->getClientOriginalName(),
              'size'          => $uploadedFile->getSize(),
              'directory'     => $request->id,
              'disk'          => $this->disk,
              'url'           => $storage->url($id),
            ],
          ],
        ],
        'upload' => [
          'id' => $id,
        ],
      ]);
    } catch (ValidationException $exception) {
      return response()->json([
        'action'      => $this->action,
        'data'        => [],
        'fieldErrors' => [
          [
            'name'   => $field,
            'status' => str_replace('upload', $field, $exception->errors()['upload'][0]),
          ],
        ],
      ]);
    }
  }

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

}
