<?php

namespace App\Filament\Resources\OrderResource\Pages;

use App\Enums\OrderAttributes;
use App\Filament\Resources\OrderResource;
use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\ProductService;
use App\Models\ProductSize;
use App\Models\ServiceFile;
use App\Models\ServiceType;
use Filament\Resources\Pages\CreateRecord;

class CreateOrder extends CreateRecord
{
    protected static string $resource = OrderResource::class;

    protected function handleRecordCreation(array $data): Order
    {
        // Attributes
        foreach (OrderAttributes::cases() as $case) {
            $data[$case->name] = false;
        }

        $data['order_attributes'] = array_filter($data['order_attributes']);

        foreach ($data['order_attributes'] as $attribute) {
            $data[OrderAttributes::from($attribute)->name] = true;
        }

        unset($data['order_attributes']);

        $order = Order::create($data);

        // Create Order Products
        foreach ($data['order_products'] as $product) {
            $orderProduct = OrderProduct::create([
                'sku'          => $product['sku'],
                'product_name' => $product['product_name'],
                'color'        => $product['color'],
                'order_id'     => $order->id,
            ]);

            $sizes = ['xs', 's', 'm', 'l', 'xl', '2xl', '3xl', 'osfa'];

            foreach ($sizes as $size) {
                if ($product[$size] > 0) {
                    ProductSize::create([
                        'amount'           => $product[$size],
                        'size'             => $size,
                        'order_product_id' => $orderProduct->id,
                    ]);
                }
            }
        }

        // ProductServices and ServiceFiles
        foreach ($data['services'] as $service) {
            $serviceFile = ServiceFile::create([
                'name'         => strtoupper($service['serviceFileName']) ?? '',
                'code'         => strtoupper($service['serviceFileCode']) ?? '',
                'width'        => $service['serviceFileWidth'] ?? null,
                'height'       => $service['serviceFileHeight'] ?? null,
                'setup_number' => $service['serviceFileSetupNumber'] ?? null,
            ]);

            ProductService::create([
                'service_type_id' => ServiceType::findOrFail($service['serviceType'])->id ?? null,
                'placement'       => strtoupper($service['placement']) ?? null,
                'notes'           => strtoupper($service['notes']) ?? null,
                'amount'          => $service['amount'] ?? null,
                'amount_price'    => $service['amount_price'] ?? null,
                'total_price'     => $service['total_price'] ?? null,
                'service_file_id' => $serviceFile->id,
                'order_id'        => $order->id,
            ]);
        }

        return $order;
    }
}
