<?php

namespace App\Filament\Resources\TillResource\Pages;

use App\Filament\Resources\TillResource;
use App\Models\Sales\Till;
use App\Services\AuditLog;
use Filament\Resources\Pages\EditRecord;

class EditTill extends EditRecord
{
    protected static string $resource = TillResource::class;

    /**
     * Snapshot of the audited fields as they were before this save, so
     * afterSave() can emit the same from/to diff TillController::update()
     * builds. Captured in beforeSave() (not afterSave()) because $this->record
     * is already mutated by the time the save completes.
     *
     * @var array<string, mixed>
     */
    protected array $originalAttributes = [];

    protected function mutateFormDataBeforeSave(array $data): array
    {
        if (filled($data['branch_id'] ?? null)) {
            TillResource::assertBranchAccessible((int) $data['branch_id']);
        }

        return $data;
    }

    protected function beforeSave(): void
    {
        /** @var Till $till */
        $till = $this->record;

        $this->originalAttributes = $till->only([
            'identifier', 'name', 'branch_id', 'is_active',
        ]);
    }

    protected function afterSave(): void
    {
        /** @var Till $till */
        $till = $this->record;

        $changes = [];
        foreach ($this->originalAttributes as $field => $old) {
            if ($old !== $till->{$field}) {
                $changes[$field] = ['from' => $old, 'to' => $till->{$field}];
            }
        }

        AuditLog::record('till.updated', $till, [
            'name' => $till->name,
            'changed' => array_keys($changes),
            'changes' => $changes,
            'description' => 'Updated till "'.$till->name.'"'
                .(! empty($changes) ? ' — changed: '.implode(', ', array_keys($changes)) : '').'.',
        ]);
    }
}
