<?php

namespace App\DataTables;

use App\Models\ActivityLog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\Services\DataTable;

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

        return DataTables::of($query)
            ->addColumn('user', function (ActivityLog $row) {
                return $row->user ? $row->user->name : 'System';
            })
            ->addColumn('resource', function (ActivityLog $row) {
                return $row->resource_type ? class_basename($row->resource_type) : null;
            })
            ->addColumn('action', function (ActivityLog $row) {
                return e($row->action ?: $row->description);
            })
            ->addColumn('created_at', function (ActivityLog $row) {
                return $row->created_at->toDateTimeString();
            })
            ->addColumn('operations', function (ActivityLog $row) {
                $delete = '';
                if (auth()->user()->can('activity_log.delete')) {
                    $delete = '<button data-id="'.$row->id.'" class="btn btn-sm btn-danger js-delete-activity-log">Delete</button>';
                }

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

    public function query(): Builder
    {
        $query = ActivityLog::with('user')->select('activity_logs.*');

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

    public function html(): \Yajra\DataTables\Html\Builder
    {
        return $this->builder()
            ->setTableId('activity-logs-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->orderBy(0);
    }

    protected function getColumns(): array
    {
        return [
            ['data' => 'id', 'title' => 'ID'],
            ['data' => 'user', 'title' => 'User'],
            ['data' => 'resource', 'title' => 'Resource'],
            ['data' => 'action', 'title' => 'Action'],
            ['data' => 'created_at', 'title' => 'Created At'],
            ['data' => 'operations', 'title' => 'Actions', 'orderable' => false, 'searchable' => false],
        ];
    }

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