<?php

namespace App\Filament\Resources\SubscriptionResource\Pages;

use App\Filament\Resources\SubscriptionResource;
use Filament\Resources\Pages\CreateRecord;

class CreateSubscription extends CreateRecord
{
    protected static string $resource = SubscriptionResource::class;

    protected function mutateFormDataBeforeCreate(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 afterCreate(): void
    {
        $record = $this->record;
        $data = $this->data;

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

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