<?php

namespace App\DataTables;

use App\Models\User;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Support\Facades\Gate;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class UserDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query)
    {
        return datatables()
        ->eloquent($query)
            ->addIndexColumn()
            ->editColumn('name',function($staff){
                return $staff->name ?? "";
            })
            ->editColumn('role', function($staff) {
                return $staff->roles->isNotEmpty() ? $staff->roles->first()->name : '';
            })         
            ->editColumn('email',function($staff){
                return $staff->email  ?? "";
            })
            ->editColumn('phone',function($staff){
                return $staff->phone  ?? "";
            })
            ->editColumn('created_at', function ($staff) {
                return $staff->created_at->format('d-m-Y h:i A');
            })
            ->addColumn('action',function($staff){
                $action='<div>';
                if (Gate::check('staff_edit')) {
                    if (!($staff->hasRole(config('app.roleid.super_admin')))) {
                    $editIcon = view('components.svg-icon', ['icon' => 'edit'])->render();
                    $action .= '<button class="btn btn-icon btn-info edit-users-btn p-1" title="Edit" data-id="'.encrypt($staff->id).'" data-href="'.route('staff.edit', $staff->id).'">'.$editIcon.'</button>';
                    }
                }
                if (Gate::check('staff_edit')) {
                    $lockIcon = view('components.svg-icon', ['icon' => 'lock'])->render();
                    $action .= '<button class="btn btn-icon btn-dark edit-password-btn p-1" title="Edit Password" data-id="'.encrypt($staff->id).'" data-href="'.route('staff.password', $staff->id).'">'.$lockIcon.'</button>';
                    
                    if (!($staff->hasRole(config('app.roleid.super_admin')))) {
                        if($staff->is_active === 1){
                            $checkcircle = view('components.svg-icon', ['icon' => 'checkcircle'])->render();
                            $action .= "<a href='javascript:void(0)' title='Active User' class='active_inactive_user btn' data-active_inactive='Inactive' data-id='".encrypt($staff->id)."'>".$checkcircle."</a>";
                        }else{
                            $closecircle = view('components.svg-icon', ['icon' => 'closecircle'])->render();
                            $action .= "<a href='javascript:void(0)' title='inactive User' class='active_inactive_user btn' data-active_inactive='Active' data-id='".encrypt($staff->id)."'>".$closecircle."</a>";
                        }
                    }
                }
                if (Gate::check('staff_delete')) {
                    $deleteIcon = view('components.svg-icon', ['icon' => 'delete'])->render();
                    if (!($staff->hasRole(config('app.roleid.super_admin')))) {
                    $action .= '<form action="'.route('staff.destroy', $staff->id).'" method="POST" class="deleteForm">
                    <button title="'.trans('quickadmin.qa_delete').'" class="btn btn-icon btn-danger record_delete_btn btn-sm">'.$deleteIcon.'</button>
                    </form>';
                    }
                }
                $action .='</div>';
                return $action;
            })
            ->filterColumn('created_at', function ($query, $keyword) {
                $query->whereRaw("DATE_FORMAT(users.created_at,'%d-%m-%Y') like ?", ["%$keyword%"]); //date_format when searching using date
            })
            ->filterColumn('role', function ($query, $keyword) {
                $query->whereHas('roles', function ($q) use ($keyword) {
                    $q->where('roles.name', 'like', "%$keyword%");
                });
            })           
            ->orderColumn('role', function ($query, $order) {
                $query->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
                    ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
                    ->selectRaw('roles.name as role_name')
                    ->orderBy('role_name', $order);
            })           
            ->rawColumns(['action']);
    }

    /**
     * Get the query source of dataTable.
     */
    public function query(User $model): QueryBuilder
    {
        $query = $model->newQuery()->select(['users.*'])->with('roles');

        if (!(auth()->user()->hasRole(config('app.roleid.super_admin')))) {
            $query->whereNotIn('id', [1]);
        }
        return $this->applyScopes($query);
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        return $this->builder()
        ->setTableId('users-table')
        ->parameters([
            'responsive' => false,
            'pageLength' => 50,
        ])
        ->columns($this->getColumns())
        ->minifiedAjax()
        ->dom('frtip')
        ->orderBy(5)
        ->selectStyleSingle();
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [           
            Column::make('DT_RowIndex')->title(trans('quickadmin.qa_sn'))->orderable(false)->searchable(false),
            Column::make('name')->title(trans('quickadmin.users.fields.name')),
            Column::make('role')->title(trans('quickadmin.users.fields.role'))->orderable(true),
            Column::make('phone')->title(trans('quickadmin.users.fields.phone')),
            Column::make('email')->title(trans('quickadmin.users.fields.email')),
            Column::make('created_at')->title(trans('quickadmin.users.fields.created_at')),
            Column::computed('action')
            ->exportable(false)
            ->printable(false)
            ->width(60)
            ->addClass('text-center')->title(trans('quickadmin.qa_action')),
        ];
    }

    /**
     * Get the filename for export.
     */
    protected function filename(): string
    {
        return 'User_' . date('YmdHis');
    }
}
