<?php

namespace App\DataTables;

use App\Models\UsersPermission;
use App\Models\Stage;
use App\Models\Division;
use App\Models\Level;
use Carbon\Carbon;
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 UsersPermissionsDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('Action', 'admin.users.permissions.action')
            ->rawColumns([
                'Action',
                'details',
            ])
            ->setRowId(function ($record) {
                return 'row_' . $record->id;
            })
            ->editColumn('updated_at', function ($record) {
                return $record->updated_at ? with(new Carbon($record->updated_at))->format('Y-m-d H:i') : '';
            })
            ->editColumn('created_at', function ($record) {
                return $record->created_at ? with(new Carbon($record->created_at))->format('Y-m-d H:i') : '';
            })
            ->editColumn('details', function ($record) {
                $details = json_decode($record->details, true);
                $data = '';
                if (isset($details['stages'])) {
                    $stages = Stage::select('stages.title')->whereIn('id', $details['stages'])->get();
                    if (in_array(-1, $details['stages'])) {
                        $data = trans('general.all');
                    } else {
                        foreach ($stages as $value) {
                            $data .= $value->title . ', ';
                        }
                    }
                    
                } elseif (isset($details['divisions'])) {
                    $divisions = Division::select('divisions.title')->whereIn('id', $details['divisions'])->get();
                    if (in_array(-1, $details['divisions'])) {
                        $data = trans('general.all');
                    } else {
                        foreach ($divisions as $value) {
                            $data .= $value->title . ', ';
                        }
                    }

                } elseif (isset($details['levels'])) {
                    $levels = Level::select('levels.title')->whereIn('id', $details['levels'])->get();
                    if (in_array(-1, $details['levels'])) {
                        $data = trans('general.all');
                    } else {
                        foreach ($levels as $value) {
                            $data .= $value->title . ', ';
                        }
                    }
                }
                return '<div title="'.$data.'" class="" >'.mb_substr($data, 0, 35 ,"UTF-8"). (strlen($data) > 35 ? '...</div>' : '</div>') ;

            })
            ->editColumn('title', function ($record) {
                return trans('general.permissions.' . $record->code);
            })
            ->addIndexColumn();
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\UsersPermission $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(UsersPermission $model)
    {
        return $model->select(
            'permissions.title',
            'permissions.code',
            'users_permissions.id',
            'users_permissions.details',
            'users_permissions.created_at',
            'users_permissions.updated_at'
        )
            ->where('user_id', $this->id)
            ->join('permissions', 'permissions.id', '=', 'users_permissions.permission_id')
            ->orderBy('id', 'desc');
    }

    public function lang()
    {
        $langJson = [
            "sEmptyTable"     =>  trans('general.datatable.sEmptyTable'),
            "sInfo"           =>  trans('general.datatable.sInfo'),
            "sInfoEmpty"      =>  trans('general.datatable.sInfoEmpty'),
            "sInfoFiltered"   =>  trans('general.datatable.sInfoFiltered'),
            "sInfoPostFix"    =>  trans('general.datatable.sInfoPostFix'),
            "sInfoThousands"  =>  trans('general.datatable.sInfoThousands'),
            "sLengthMenu"     =>  trans('general.datatable.sLengthMenu'),
            "sLoadingRecords" =>  trans('general.datatable.sLoadingRecords'),
            "sProcessing"     =>  trans('general.datatable.sProcessing'),
            "sSearch"         =>  trans('general.datatable.sSearch'),
            "sZeroRecords"    =>  trans('general.datatable.sZeroRecords'),
            "sFirst"          =>  trans('general.datatable.sFirst'),
            "sLast"           =>  trans('general.datatable.sLast'),
            "sNext"           =>  trans('general.datatable.sNext'),
            "sPrevious"       =>  trans('general.datatable.sPrevious'),
            "sSortAscending"  =>  trans('general.datatable.sSortAscending'),
            "sSortDescending" =>  trans('general.datatable.sSortDescending'),
            "paginate" => [
                "first" => trans('general.datatable.sFirst'),
                "previous" => trans('general.datatable.sPrevious'),
                "next" => trans('general.datatable.sNext'),
                "last" => trans('general.datatable.sLast')
            ],
        ];
        return $langJson;
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
            ->setTableId('userspermissions-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom('Bfrtip')
            ->dom('<"d-flex justify-content-between align-items-center mx-0 row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between mx-0 row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>')
            ->orderBy(0)
            ->parameters([
                'responsive' => true,
                'autoWidth' => false,
                'lengthMenu' => [[15, 25, 50,], ['15', '25', '50',]],
                'language' => $this->lang(),
            ]);
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::computed('DT_RowIndex')->title('#')
                ->addClass('text-center'),
            Column::make('title')->title(trans('general.title')),
            Column::make('details')->title(trans('general.details')),
            Column::make('updated_at')->title(trans('general.updated-at')),
            Column::make('created_at')->title(trans('general.created-at')),
            Column::computed('Action')->title(trans('general.options'))
                ->exportable(false)
                ->printable(false)
                ->addClass('text-center')
                ->searchable(false),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'UsersPermissions_' . date('YmdHis');
    }
}
