<?php

namespace App\Filament\Resources\ReturnRequestResource\Pages;

use App\Filament\Resources\ReturnRequestResource;
use Filament\Resources\Pages\CreateRecord;
use App\Models\Order;

class CreateReturnRequest extends CreateRecord
{
    protected static string $resource = ReturnRequestResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $order = Order::find($data['order_id']);
        if ($order) {
            $data['user_id'] = $order->user_id;
        }

        return $data;
    }

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

        // Log order history
        $record->order->histories()->create([
            'user_id'     => auth()->id(),
            'action'      => 'return_requested',
            'from_status' => $record->order->status,
            'to_status'   => $record->order->status,
            'notes'       => 'Return request #' . $record->id . ' opened manually by administrator.',
        ]);
    }
}
