<?php

namespace App\DataTables;

use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\Html\Builder;
use Yajra\DataTables\Services\DataTable;

class SettingDataTable extends DataTable
{
    public function ajax(): JsonResponse
    {
        $query = $this->query();

        return DataTables::of($query)
            ->addColumn('value', function (Setting $row) {
                return e(strlen($row->value) > 80 ? substr($row->value, 0, 80).'...' : $row->value);
            })
            ->addColumn('operations', function (Setting $row) {
                $edit = '';
                if (auth()->user()->can('settings.manage')) {
                    $edit = '<button class="btn btn-sm btn-primary js-edit-setting" data-key="'.e($row->key).'">Edit</button>';
                }

                return $edit;
            })
            ->rawColumns(['operations'])
            ->make(true);
    }

    public function query()
    {
        $query = Setting::select('settings.*');

        return $this->applyScopes($query);
    }

    public function html(): Builder
    {
        return $this->builder()
            ->setTableId('settings-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->orderBy(0);
    }

    protected function getColumns(): array
    {
        return [
            ['data' => 'key', 'title' => 'Key'],
            ['data' => 'group', 'title' => 'Group'],
            ['data' => 'value', 'title' => 'Value'],
            ['data' => 'operations', 'title' => 'Actions', 'orderable' => false, 'searchable' => false],
        ];
    }

    protected function filename(): string
    {
        return 'settings_'.date('YmdHis');
    }
}
