<?php

namespace App\Filament\Resources\SubscriptionResource\Pages;

use App\Filament\Resources\SubscriptionResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;

class EditSubscription extends EditRecord
{
    protected static string $resource = SubscriptionResource::class;

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

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $record = $this->getRecord();

        // Load property types pivot data
        $record->load(['propertyTypes', 'facilities']);

        $data['subscription_properties'] = $record->propertyTypes->map(fn ($pt) => [
            'property_type_id' => $pt->id,
            'quantity' => $pt->pivot->quantity,
        ])->toArray();

        $data['subscription_facilities'] = $record->facilities->map(fn ($f) => [
            'additional_facility_id' => $f->id,
            'quantity' => $f->pivot->quantity,
            'unit_price' => $f->pivot->unit_price,
            'total_price' => $f->pivot->total_price,
        ])->toArray();

        return $data;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Remove virtual fields that are not in the subscriptions table
        unset($data['subscription_properties']);
        unset($data['subscription_facilities']);

        return $data;
    }

    protected function afterSave(): void
    {
        $record = $this->record;
        $data = $this->data;

        // Sync property types
        $propertySync = [];
        if (!empty($data['subscription_properties'])) {
            foreach ($data['subscription_properties'] as $prop) {
                if (!empty($prop['property_type_id'])) {
                    $propertySync[$prop['property_type_id']] = [
                        'quantity' => $prop['quantity'] ?? 0,
                    ];
                }
            }
        }
        $record->propertyTypes()->sync($propertySync);

        // Sync facilities
        $facilitySync = [];
        if (!empty($data['subscription_facilities'])) {
            foreach ($data['subscription_facilities'] as $fac) {
                if (!empty($fac['additional_facility_id'])) {
                    $facilitySync[$fac['additional_facility_id']] = [
                        'quantity' => $fac['quantity'] ?? 0,
                        'unit_price' => $fac['unit_price'] ?? 0,
                        'total_price' => $fac['total_price'] ?? 0,
                    ];
                }
            }
        }
        $record->facilities()->sync($facilitySync);
    }
}
