<?php

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

use App\Filament\Resources\Manage\Journalists\JournalistResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Enums\Width;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class ManageJournalists extends ManageRecords
{
    protected static ?string $title = 'Jurnalis';

    protected static string $resource = JournalistResource::class;

    protected function getHeaderActions(): array
    {
        if (auth()->user()->hasRole('Perusahaan') && ! auth()->user()->company?->partnerMedia) {
            return [];
        }

        return [
            CreateAction::make()
                ->label('Tambah')
                ->modalHeading('Tambah Jurnalis')
                ->modalSubmitActionLabel('Simpan')
                ->modalCancelActionLabel('Batal')
                ->extraModalFooterActions(fn (CreateAction $action): array => [
                    $action->makeModalSubmitAction('createAnother', arguments: ['another' => true])
                        ->label('Simpan dan Tambah Lagi'),
                ])
                ->modalWidth(Width::Large)
                ->using(function (array $data, string $model): Model {
                    $data['partner_media_id'] = auth()->user()->company?->partnerMedia?->id;

                    $journalist = $model::create($data);

                    $documents = [
                        'press_card_docs',
                        'ukw_certificate_docs',
                    ];

                    foreach ($documents as $field) {
                        if (empty($data[$field])) {
                            continue;
                        }

                        foreach ((array) $data[$field] as $filePath) {
                            $fullPath = Storage::disk(config('filesystems.default'))->path($filePath);

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

                            $journalist
                                ->addMediaFromDisk($filePath, config('filesystems.default'))
                                ->preservingOriginal()
                                ->withCustomProperties([
                                    'feature' => 'journalists',
                                    'date' => now()->toDateString(),
                                    'doc_type' => str($field)
                                        ->replace('_docs', '')
                                        ->slug('-'),
                                ])
                                ->toMediaCollection('journalists');
                        }
                    }

                    return $journalist;
                }),
        ];
    }
}
