<?php

namespace App\Filament\Widgets;

use App\Models\DonorFinancialPortfolio;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Tables;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Support\HtmlString;

class FinancialPortfoliosSummaryByTagsTable extends BaseWidget
{
    use HasWidgetShield;

    protected static bool $isLazy = true;

    protected int|string|array $columnSpan = 'full';

    public function getHeading(): string
    {
        return __('pages.financial_portfolios_dashboard').' - '.__('widgets.balance_by_tags');
    }

    public function getTableHeading(): string
    {
        return __('pages.financial_portfolios_dashboard').' - '.__('widgets.balance_by_tags');
    }

    public function table(Tables\Table $table): Tables\Table
    {
        return $table
            ->query(
                DonorFinancialPortfolio::query()
                    ->selectRaw('
                        tags.name as tag_name,
                        SUM(donor_financial_portfolios.balance) as total_balance,
                        MIN(donor_financial_portfolios.id) as id
                    ')
                    ->join(
                        'donor_financial_portfolio_tag',
                        'donor_financial_portfolios.id',
                        '=',
                        'donor_financial_portfolio_tag.donor_financial_portfolio_id'
                    )
                    ->join('tags', 'tags.id', '=', 'donor_financial_portfolio_tag.tag_id')
                    ->groupBy('tags.name')
            )
            ->defaultSort('tag_name')
            ->columns([
                Tables\Columns\TextColumn::make('tag_name')
                    ->label(__('donor_financial_portfolio.tag'))
                    ->icon('heroicon-m-tag')
                    ->sortable(),

                Tables\Columns\TextColumn::make('total_balance')
                    ->label(__('donor_financial_portfolio.balance'))
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->numeric(2)
                    ->sortable(),
            ])
            // empty state text
            ->emptyStateHeading(__('widgets.no_portfolios'));
    }
}
