<?php

namespace App\DataTables;

use App\Helpers\IConstants;
use App\Models\User;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;

class UserDataTable extends DataTable
{
  /**
   * Build DataTable class.
   *
   * @param mixed $query Results from query() method.
   * @return \Yajra\DataTables\DataTableAbstract
   */
  public function dataTable($query)
  {
    $dataTable = new EloquentDataTable($query);
    $dataTable->addColumn('action', 'users.datatables_actions');
  
    $dataTable->addColumn('role', function (User $user) {
        return '<span class="badge  bg-label-success">' . $user->roles->pluck('name', 'name')->first() . '</span>';
      })
      ->toJson();
      $dataTable->addColumn('branch_id', function (User $user) {
        return $user->branch->name??'';
      })
      ->toJson();
    $dataTable->rawColumns(['role', 'branch_id','action']);
    return $dataTable;
  }

  /**
   * Get query source of dataTable.
   *
   * @param \App\Models\User $model
   * @return \Illuminate\Database\Eloquent\Builder
   */
  public function query(User $model)
  {
    if(auth()->user()->hasRole(IConstants::ROLE_SUPER_ADMIN)){
      return $model->newQuery()->with(['branch'])->whereHas('roles', function ($query) {
        return $query->where('name','!=', IConstants::ROLE_SUPER_ADMIN);
      })->orderBy('id','DESC');
    }else{
      $model = $model->newQuery()->whereHas('roles', function ($query) {
        return $query->where('name','!=', IConstants::ROLE_SUPER_ADMIN)->where('name','!=', IConstants::ROLE_ADMIN)->orderBy('id','DESC');
      });
      if(auth()->user()->branch_id){
        $model = $model->where('branch_id',auth()->user()->branch_id)->orderBy('id','DESC');
      }
      return $model;
    }
    
  }

  /**
   * Optional method if you want to use html builder.
   *
   * @return \Yajra\DataTables\Html\Builder
   */
  public function html()
  {
    return $this->builder()
      ->columns($this->getColumns())
      ->minifiedAjax()
      ->addAction(['width' => '120px', 'printable' => false])
      ->parameters([
        'dom' => 'Bfrtip',
        'stateSave' => true,
        'order' => [[0, 'desc']],
        'initComplete' => 'function(settings, json) {
          $(".dataTables_wrapper").css("overflow", "auto");
            }',
        'buttons' => [
          // Enable Buttons as per your need
          //                    ['extend' => 'create', 'className' => 'btn btn-default btn-sm no-corner',],
          //                    ['extend' => 'export', 'className' => 'btn btn-default btn-sm no-corner',],
          //                    ['extend' => 'print', 'className' => 'btn btn-default btn-sm no-corner',],
          //                    ['extend' => 'reset', 'className' => 'btn btn-default btn-sm no-corner',],
          //                    ['extend' => 'reload', 'className' => 'btn btn-default btn-sm no-corner',],
        ],
      ]);
  }

  /**
   * Get columns.
   *
   * @return array
   */
  protected function getColumns()
  {
    return [
      'id',
      'name',
      'email',
      //'country',
      //'phone',
      'branch_id' => ['title' => 'Branch'],
      'role',
    ];
  }

  /**
   * Get filename for export.
   *
   * @return string
   */
  protected function filename(): string
  {
    return 'users_datatable_' . time();
  }
}
