<?php

namespace App\Livewire\Tables;

use App\Models\ActivityLog;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder;
use PowerComponents\LivewirePowerGrid\Column;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Traits\WithExport; 
use PowerComponents\LivewirePowerGrid\Components\SetUp\Exportable; 
use Spatie\Activitylog\Models\Activity;


final class ActivityLogTable extends PowerGridComponent
{
    use WithExport;
    public string $tableName = 'activity-log-table';
    public bool $canDownload;

    public bool $showFilters = false;
    public function boot(): void
    {
        config(['livewire-powergrid.filter' => 'outside']);
        //權限設定
        $this->canDownload=true;
    }

    public function setUp(): array
    {
        if($this->canDownload ){
            $this->showCheckBox();
        }
        $actions = [];
        if($this->canDownload){
            $actions[]=PowerGrid::exportable(fileName: $this->tableName.'-file') 
                ->type(Exportable::TYPE_XLS, Exportable::TYPE_CSV);
        }
        $header = PowerGrid::header()
            ->withoutLoading()
            ->showToggleColumns();
            //->showSoftDeletes()
            //->showSearchInput()
        $header->includeViewOnTop('livewire.headers.activity-log');
        $actions[]=$header;
        $actions[]=PowerGrid::footer()->showPerPage()->showRecordCount();     
        return $actions;
    }

    public function datasource(): Builder
    {
        return Activity::with(['causer'])->latest();
    }

    public function relationSearch(): array
    {
        return [];
    }

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('created_at_formatted', fn (Activity $model) => Carbon::parse($model->created_at)->format('Y-m-d H:i:s'))
            ->add('causer_name', fn (Activity $model) => optional($model->causer)->name)
            ->add('subject_type_label', fn (Activity $model) => class_basename($model->subject_type))
            ->add('subject_type')
            ->add('subject_id')
            ->add('description')
            ->add('changes_str', function (Activity $model) {
                    $old = $model->properties['old'] ?? [];
                    $new = $model->properties['attributes'] ?? [];

                    $changes = [];

                    foreach ($new as $key => $newValue) {
                        if (in_array($key, ['updated_at', 'created_at'])) continue;
                        $oldValue = $old[$key] ?? '(空)';
                        if ($newValue != $oldValue) {
                            $changes[] = "<strong>{$key}</strong>: {$oldValue} → {$newValue}";
                        }
                    }
                    //dd(implode('<br>', $changes));
                    return implode('<br>', $changes);
                })
            ;
            
    }

    public function columns(): array
    {
        $column=[];
        $column[]=Column::make('時間', 'created_at_formatted', 'created_at')->sortable()->searchable();
        $column[]=Column::make('操作者', 'causer_name')->sortable()->searchable()->bodyAttribute('whitespace-nowrap');
        $column[]=Column::make('模型', 'subject_type_label')->sortable()->searchable();
        $column[]=Column::make('模型 ID', 'subject_id')->sortable()->searchable();
        $column[]=Column::make('動作', 'description')->sortable()->searchable();
        $column[]=Column::make('變更內容', 'changes_str')->sortable(false)->searchable(false)->bodyAttribute('whitespace-normal text-sm text-gray-700');
        return $column;
    }

    public function filters(): array
    {
        return [
            Filter::datetimepicker('created_at'),
            Filter::inputText('causer_name')->placeholder('操作者'),
            Filter::inputText('subject_type_label')->placeholder('模型'),
            Filter::number('subject_id'),
            Filter::inputText('description')->placeholder('動作'),
        ];
    }



    
}
