<?php

namespace App\Filament\Resources\ProcessOrderResource\Pages;

use App\Filament\Resources\ProcessOrderResource;
use App\Models\ProcessOrder;
use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;

class EditProcessOrder extends EditRecord
{
    protected static string $resource = ProcessOrderResource::class;

    protected function beforeSave(): void
    {
        $plantId = $this->data['plant_id'] ?? null;
        $processOrder = $this->data['process_order'] ?? null;
        $extraQty = (float) ($this->data['updated_order_quantity'] ?? 0);
        $extraQtyRaw = $this->data['updated_order_quantity'] ?? '';

        if (!preg_match('/^\d+(\.\d{1,3})?$/', $extraQtyRaw)) {
            Notification::make()
                ->title('Invalid Quantity')
                ->body('Only positive numbers with up to 3 decimal places are allowed.')
                ->danger()
                ->send();

            $this->halt(); // stop save
        }

        if ($extraQty < 0)
        {
            Notification::make()
                ->title('Invalid Quantity')
                ->body('Negative values are not allowed.')
                ->danger()
                ->send();

            $this->halt();
        }

        if ($extraQty > 0) {

            $order = ProcessOrder::where('plant_id', $plantId)
                ->where('process_order', $processOrder)
                ->first();

            if ($order) {

                $baseQty = (float) $order->order_quantity;
                $maxAllowed = $baseQty * 0.10;

                $maxFinalQty = $baseQty + $maxAllowed;

                if ($extraQty > $maxFinalQty) {
                    Notification::make()
                        ->title('Limit Exceeded')
                        ->body("You can only increase the order by 10% (Max allowed: {$maxFinalQty}).")
                        ->danger()
                        ->send();

                    $this->halt(); // stops save
                }

                ProcessOrder::where('plant_id', $plantId)
                    ->where('process_order', $processOrder)
                    ->update([
                        'updated_order_quantity' => $extraQty,
                        'updated_by' => Filament::auth()->user()?->name,
                    ]);
            }
        }
    }


    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make(),
            Actions\DeleteAction::make(),
            Actions\ForceDeleteAction::make(),
            Actions\RestoreAction::make(),
        ];
    }
}
