<?php

namespace App\Filament\Resources\CustomerResource\Pages;

use App\Filament\Resources\CustomerResource;
use App\Models\Customers\Customer;
use App\Services\AuditLog;
use Filament\Resources\Pages\EditRecord;

/**
 * Ported from CustomerController::update(), including its from/to diff over
 * the same six audited fields.
 */
class EditCustomer extends EditRecord
{
    protected static string $resource = CustomerResource::class;

    /** @var array<string, mixed> */
    protected array $originalAttributes = [];

    protected function getHeaderActions(): array
    {
        return [];
    }

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

        $this->originalAttributes = $customer->only([
            'business_name', 'phone', 'nic', 'email', 'city_id', 'assigned_user_id',
        ]);
    }

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

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

        AuditLog::record('customer.updated', $customer, [
            'name' => $customer->business_name,
            'changed' => array_keys($changes),
            'changes' => $changes,
        ]);
    }

    protected function getRedirectUrl(): string
    {
        return CustomerResource::getUrl('index');
    }
}
