<?php

namespace App\Filament\Resources\Manage\Cooperations\Pages;

use App\Filament\Actions\BackAction;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Filament\Support\CheerfulNotification;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Storage;

class CreateCooperation extends CreateRecord
{
    protected static string $resource = CooperationResource::class;

    protected static ?string $title = 'Tambah Kerja Sama';

    protected function getHeaderActions(): array
    {
        return [
            BackAction::make()
                ->url(ListCooperations::getUrl()),
        ];
    }

    protected function getCreatedNotification(): ?Notification
    {
        return CheerfulNotification::create();
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

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

        if (empty($data['proposal_template'])) {
            return;
        }

        $filePath = collect($data['proposal_template'])->first();

        $fullPath = Storage::disk(config('filesystems.default'))->path($filePath);

        if (! file_exists($fullPath)) {
            return;
        }

        $record
            ->addMediaFromDisk($filePath, config('filesystems.default'))
            ->preservingOriginal()
            ->withCustomProperties([
                'feature' => 'cooperations',
                'date' => now()->toDateString(),
                'doc_type' => 'proposal-template',
            ])
            ->toMediaCollection('cooperations');

        // Notify selected partners
        $record->load('partnerMedia.company.user');
        $record->partnerMedia->each(function ($media) use ($record) {
            $partnerUser = $media->company?->user;
            if ($partnerUser) {
                $partnerUser->notify(new BroadcastNotification([
                    'title' => 'Ada Penawaran Kerja Sama Baru! 🤝✨',
                    'body' => "Halo! Admin baru saja menawarkan kerja sama \"{$record->title}\" untuk media {$media->name}. Yuk, cek detailnya dan berikan tanggapanmu! 😊",
                    'action' => [
                        Action::make('view')
                            ->label('Lihat')
                            ->url(CooperationResource::getUrl('view', ['record' => $record->id])),
                    ],
                ]));
            }
        });
    }
}
