<?php

namespace App\Filament\Reports;

use App\Models\Equip;
use App\Models\EquipWork;
use EightyNine\Reports\Components\Text;
use EightyNine\Reports\Report;
use EightyNine\Reports\Components\Body;
use EightyNine\Reports\Components\Footer;
use EightyNine\Reports\Components\Header;
use Filament\Forms\Form;
use Filament\Forms\Components\DatePicker;
use Illuminate\Support\Carbon;
use Filament\Forms\Components\Select;

class EquipWorkReport extends Report
{
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    public static function getNavigationLabel(): string
    {
        return "تقرير المعدات";
    }

    public function getTitle(): string
    {
        return "تقرير المعدات";
    }

    protected static ?int $navigationSort = 2;

    protected static ?string $navigationGroup = 'التقارير';

    private $totals = [
        'hours_count' => 0,
        'total' => 0,
    ];

    public function header(Header $header): Header
    {
        return $header
            ->schema([
                Header\Layout\HeaderRow::make()
                    ->schema([
                        Text::make("تقرير أعمال المعدات")
                            ->fontXl()
                            ->fontBold()
                            ->primary(),
                        Text::make("عرض تفاصيل أعمال المعدات")
                            ->fontSm()
                            ->secondary(),
                    ])
                    ->alignBottom(),
            ]);
    }

    function getCarbonInstancesFromDateString(?string $dateString): array
    {
        if (!$dateString) {
            return [null, null];
        }

        $dates = explode(" - ", $dateString);

        [$from, $to] = $dates;

        $from = Carbon::createFromFormat("d/m/Y", $from);
        $to = Carbon::createFromFormat("d/m/Y", $to);

        return [$from, $to];
    }

    public function body(Body $body): Body
    {
        return $body
            ->schema([
                Body\Layout\BodyColumn::make()
                    ->schema([
                        Body\Table::make()
                            ->columns([
                                Body\TextColumn::make('equip')
                                    ->label("نوع المعدة"),
                                Body\TextColumn::make('date')->date('D-d-M-Y')
                                    ->label("تاريخ العمل"),
                                Body\TextColumn::make('lands')
                                    ->label("اسم الأرض"),
                                Body\TextColumn::make('hours_count')
                                    ->label("عدد الساعات"),
                                Body\TextColumn::make('hour_price')
                                    ->label("سعر الساعة"),
                                Body\TextColumn::make('total')
                                    ->label("المجموع"),
                            ])
                            ->data(
                                function (?array $filters) {
                                    if (empty($filters['date']) && !empty($filters['from_date']) && !empty($filters['to_date'])) {
                                        $filters['date'] = Carbon::parse($filters['from_date'])->format('d/m/Y') . ' - ' . Carbon::parse($filters['to_date'])->format('d/m/Y');
                                    }

                                    [$startDate, $endDate] = $this->getCarbonInstancesFromDateString($filters['date'] ?? null);
    
                                    $equipWorks = EquipWork::with(['equip', 'lands'])
                                        ->when(isset($filters['date']), function ($query) use ($startDate, $endDate) {
                                            $query->whereBetween('date', [$startDate, $endDate]);
                                        })
                                        ->when(isset($filters['equip_id']), function ($query) use ($filters) {
                                            $query->whereIn('equip_id', (array)$filters['equip_id']);
                                        })
                                        ->get();
    
                                    // Calculate totals
                                    $this->totals = [
                                        'hours_count' => $equipWorks->sum('hours_count'),
                                        'total' => $equipWorks->sum('total'),
                                    ];
    
                                    // Transform equipWorks to table data
                                    $equipWorkData = $equipWorks->map(function ($equipWork) {
                                        return [
                                            'equip' => $equipWork->equip->type ?? 'N/A',
                                            'lands' => $equipWork->lands->pluck('name')->implode(', ') ?? 'N/A',
                                            'date' => $equipWork->date,
                                            'hours_count' => $equipWork->hours_count,
                                            'hour_price' => $equipWork->hour_price,
                                            'total' => $equipWork->hours_count * $equipWork->hour_price,
                                        ];
                                    });
    
                                    // Add totals as the last row
                                    $equipWorkData->push([
                                        'equip' => 'الإجمالي',
                                        'lands' => '',
                                        'date' => null,
                                        'hours_count' => $this->totals['hours_count'],
                                        'hour_price' => '',
                                        'total' => $this->totals['total'],
                                    ]);
    
                                    return $equipWorkData;
                                }
                            ),
                    ]),
            ]);
    }
    
    public function footer(Footer $footer): Footer
    {
        // $totalsText = "إجمالي عدد الساعات: {$this->totals['hours_count']} </br> الإجمالي: {$this->totals['total']}</br></br>";
    
        return $footer
            ->schema([
                // Text::make($totalsText), // Display totals in plain text
                Text::make("تاريخ التقرير: " . now()->format("d/m/Y H:i:s"))
                    ->subtitle(),
            ]);
    }
    

    public function filterForm(Form $form): Form
    {
        return $form
            ->schema([

                DatePicker::make('from_date')
                    ->label('من تاريخ')
                    ->native(false),

                DatePicker::make('to_date')
                    ->label('إلى تاريخ')
                    ->native(false),

                Select::make('equip_id')
                    ->label("اسم المعدة")
                    ->options(Equip::pluck('type', 'id'))
                    ->searchable()
                    ->preload()
                    ->multiple(),
            ]);
    }
}
