<?php

namespace App\Filament\Office\Resources\BLResource\Pages;

use Filament\Actions;
use App\Models\Office;
use Filament\Actions\Action;
use Illuminate\Database\Eloquent\Model;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use App\Filament\Office\Resources\BLResource;

class EditBL extends EditRecord
{
    protected static string $resource = BLResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('pdf')
                ->label('PDF')
                ->url(fn (?Model $record): string => route('shipping.bl.pdf', $record->bl))
                ->icon('heroicon-o-document')
                // ->color('success')
                ->openUrlInNewTab(),
            
            Action::make('print')
                ->url(fn (?Model $record): string => route('shipping.bl.print', $record->bl))
                ->icon('heroicon-o-printer')
                ->openUrlInNewTab(),
            Actions\DeleteAction::make(),
            Actions\ForceDeleteAction::make(),
            Actions\RestoreAction::make(),
        ];
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // set delivery agent based on selected country and city
        if (isset($data['final_destination_city_id'])) {
            $office = Office::where('city_id', $data['final_destination_city_id'])->first();
            $data['delivery_agent_id'] = $office?$office->id:null;
            // dd($data['delivery_agent_id']);
        }

        // set shipped_on_board and issue_date same as eta if empty
        $data['shipped_on_board'] = $data['shipped_on_board']?:$data['eta'];
        $data['issue_date'] = $data['issue_date']?:$data['eta'];
        // dd($data['eta'], $data['shipped_on_board'], $data['issue_date']);

        // set finalize by office user
        $data['final_by_user_id'] = null;
        if ($this->getRecord()->is_final == 0 && $data['is_final'] == 1) {
            $data['final_by_user_id'] = auth()->id();
        }
        
        // set last updated by office user
        $data['last_updated_by_user_id'] = auth()->id();
    
        return $data;
    }
    
    protected function getSavedNotification(): ?Notification
    {
        return Notification::make()
            ->success()
            ->title('Bill Of Lading updated')
            ->body('The Bill Of Lading has been saved successfully.');
    }
}
