| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 | <?php
namespace App\Filament\Resources\CurrencyResource\Pages;
use App\Filament\Resources\CurrencyResource;
use App\Models\Banking\Account;
use App\Models\Setting\Currency;
use Filament\Pages\Actions;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class EditCurrency extends EditRecord
{
    protected static string $resource = CurrencyResource::class;
    protected function getActions(): array
    {
        return [
            Actions\DeleteAction::make(),
        ];
    }
    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }
    protected function mutateFormDataBeforeSave(array $data): array
    {
        $data['company_id'] = Auth::user()->currentCompany->id;
        $data['enabled'] = (bool)$data['enabled'];
        $data['updated_by'] = Auth::id();
        return $data;
    }
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        return DB::transaction(function () use ($record, $data) {
            $currentCompanyId = auth()->user()->currentCompany->id;
            $recordId = $record->id;
            $enabled = (bool)($data['enabled'] ?? false);
            // If the record is enabled, disable all other records for the same company
            if ($enabled === true) {
                $this->disableExistingRecord($currentCompanyId, $recordId);
            }
            // If the record is disabled, ensure at least one record remains enabled
            elseif ($enabled === false) {
                $this->ensureAtLeastOneEnabled($currentCompanyId, $recordId, $enabled);
            }
            $data['enabled'] = $enabled;
            return parent::handleRecordUpdate($record, $data);
        });
    }
    protected function disableExistingRecord(int $companyId, int $recordId): void
    {
        $existingEnabledAccount = Currency::where('company_id', $companyId)
            ->where('enabled', true)
            ->where('id', '!=', $recordId)
            ->first();
        if ($existingEnabledAccount !== null) {
            $existingEnabledAccount->enabled = false;
            $existingEnabledAccount->save();
        }
    }
    protected function ensureAtLeastOneEnabled(int $companyId, int $recordId, bool &$enabled): void
    {
        $enabledAccountsCount = Currency::where('company_id', $companyId)
            ->where('enabled', true)
            ->where('id', '!=', $recordId)
            ->count();
        if ($enabledAccountsCount === 0) {
            $enabled = true;
        }
    }
}
 |