<?php

namespace App\Livewire\Participants;

use App\Domain\Participant\Models\Participant;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class StatusTimeline extends Component
{
    public Participant $participant;

    public function mount(Participant $participant): void
    {
        $this->participant = $participant;
    }

    public function render()
    {
        $history = DB::table('audit_logs')
            ->where('auditable_type', Participant::class)
            ->where('auditable_id', $this->participant->id)
            ->whereRaw("new_values::text LIKE '%status%'")
            ->orderByDesc('created_at')
            ->limit(20)
            ->get()
            ->map(function ($log) {
                $old = json_decode($log->old_values, true);
                $new = json_decode($log->new_values, true);
                return [
                    'from' => $old['status'] ?? null,
                    'to' => $new['status'] ?? null,
                    'date' => $log->created_at,
                    'user' => DB::table('users')->where('id', $log->user_id)->value('name_ar') ?? '-',
                ];
            })
            ->filter(fn ($item) => $item['to'] !== null);

        return view('livewire.participants.status-timeline', [
            'history' => $history,
        ]);
    }
}
