<?php

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

use App\Enums\ApprovalStatus;
use App\Enums\RoleEnum;
use App\Models\CooperationPayment;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class CooperationPaymentRelationManager extends RelationManager
{
    protected static ?string $recordTitleAttribute = 'description';

    protected static string $relationship = 'payments';

    protected static ?string $title = 'Pembayaran';

    public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
    {
        if (! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value)) {
            return false;
        }

        return $ownerRecord->cooperationMedia()
            ->whereHas('partnerMedia', function ($query) {
                $query->whereHas('company', function ($query) {
                    $query->where('user_id', auth()->id());
                });
            })
            ->where('status', ApprovalStatus::ACCEPTED)
            ->exists();
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('amount')
                    ->label('Nominal')
                    ->money('IDR', decimalPlaces: 0),

                TextColumn::make('payment_date')
                    ->label('Tanggal Bayar')
                    ->date('l, d F Y'),

                TextColumn::make('description')
                    ->label('Keterangan')
                    ->limit(50),

                ImageColumn::make('payment_proof')
                    ->label('Bukti Pembayaran')
                    ->getStateUsing(fn (CooperationPayment $record): ?string => optional($record->cooperationMedia->getMedia('cooperations')->where('custom_properties.doc_type', 'payment-proof')->sortByDesc('created_at')->first())->getPathRelativeToRoot())
                    ->disk(config('filesystems.default')),
            ])
            ->filters([])
            ->headerActions([])
            ->recordActions([])
            ->emptyStateIcon(Heroicon::CreditCard)
            ->emptyStateDescription('Belum ada data pembayaran.')
            ->defaultSort('created_at', 'desc')
            ->modifyQueryUsing(function ($query) {
                $user = auth()->user();

                return $query->whereHas('cooperationMedia.partnerMedia.company', function ($q) use ($user) {
                    $q->where('user_id', $user->id);
                });
            });
    }
}
