<?php

namespace App\Filament\Reports;

use App\Models\Land;
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 Filament\Forms\Components\Select;
use Illuminate\Support\Carbon;
use App\Models\Setting;

class LandReport extends Report
{
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    public static function getNavigationLabel(): string
    {
        return "تقرير الأراضي";
    }
    protected static ?int $navigationSort = 3;
    public function getTitle(): string
    {
        return "تقرير الأراضي";
    }
    protected static ?string $navigationGroup = 'التقارير';

    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('name')
                                    ->label("اسم الأرض"),
                                Body\TextColumn::make('date')->date('D-d-M-Y')
                                    ->label("التاريخ"),
                                // Body\TextColumn::make('equip.name')
                                //     ->label("اسم المعدة"),
                                // Body\TextColumn::make('equip_work.hours_count')
                                //     ->label("عدد الساعات"),
                                Body\TextColumn::make('equip_work.total')
                                    ->label("إجمالي تكلفة المعدات")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('mony_export.monyType.name')
                                    ->label("نوع المصروف"),
                                Body\TextColumn::make('mony_export.value')
                                    ->label("قيمة المصروف")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                // Body\TextColumn::make('mony_import.monyType.name')
                                //     ->label("نوع الوارد"),

                                // Body\TextColumn::make('attendance_details')
                                //     ->label("تفاصيل الحضور")
                                //     ->formatStateUsing(function ($state) {
                                //         if (!is_array($state)) {
                                //             return '-';
                                //         }
                                //         return collect($state)->map(function ($attendance) {
                                //             return "نوع العمل: {$attendance['work_type']}, عدد الموظفين: {$attendance['employee_count']}";
                                //         })->implode('<br>');
                                //     })
                                //     ->html(),
                                Body\TextColumn::make('total_attendance_cost')
                                    ->label("إجمالي تكلفة العمالة")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                // Body\TextColumn::make('sales_products')
                                //     ->label("المنتجات المنصرفة")
                                //     ->formatStateUsing(function ($state) {
                                //         if (!is_array($state)) {
                                //             return '';
                                //         }
                                //         return collect($state)->map(function ($product) {
                                //             return "{$product['name']} (كمية: {$product['quantity']}, سعر: {$product['price']}, إجمالي: {$product['total']})";
                                //         })->implode('<br>');
                                //     })
                                //     ->html(),
                                Body\TextColumn::make('total_sales')
                                    ->label("إجمالي الأصناف")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('row_total')
                                    ->label("الإجمالي الكلي")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                    Body\TextColumn::make('mony_import.value')
                                    ->label("قيمة الوارد")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),

                                    Body\TextColumn::make('final')
                                    ->label("الربح")
                                    ->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                            ])
                            ->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);
    
                                $lands = Land::with([
                                    'equipWorks.equip',
                                    'monyExports.monyType',
                                    'monyImports.monyType', // Include mony imports
                                    'attendances.workType',
                                    'attendances.employees',
                                    'sales.products',
                                ])
                                    ->when(isset($filters['land_id']), function ($query) use ($filters) {
                                        $query->where('id', $filters['land_id']);
                                    })
                                    ->get();
    
                                $landData = [];
                                $totals = [
                                    'equip_work_total' => 0,
                                    'mony_export_value' => 0,
                                    'mony_import_value' => 0, // Add total mony import to totals
                                    'total_attendance_cost' => 0,
                                    'total_sales' => 0,
                                    'row_total' => 0,
                                    'final' => 0, // Add final to totals
                                ];
    
                                foreach ($lands as $land) {
                                    $dates = $land->equipWorks->pluck('date')
                                        ->merge($land->monyExports->pluck('date'))
                                        ->merge($land->monyImports->pluck('date')) // Include mony imports
                                        ->merge($land->attendances->pluck('date'))
                                        ->merge($land->sales->pluck('date'))
                                        ->unique()
                                        ->map(fn($date) => Carbon::parse($date))
                                        ->sort();
    
                                    foreach ($dates as $date) {
                                        $totalAttendanceCost = $land->attendances
                                            ->where('date', $date->toDateString())
                                            ->sum(function ($attendance) {
                                                $relatedLandsCount = $attendance->lands->count() ?: 1;
                                                return (
                                                    $attendance->employees->count() * Setting::latest()->first()->daily_price
                                                ) / $relatedLandsCount;
                                            });
    
                                        $attendanceDetails = $land->attendances
                                            ->where('date', $date->toDateString())
                                            ->map(function ($attendance) {
                                                return [
                                                    'work_type' => $attendance->workType->name ?? 'غير محدد',
                                                    'employee_count' => $attendance->employees->count(),
                                                ];
                                            });
    
                                        $equipTotal = $land->equipWorks->where('date', $date->toDateString())->sum(function ($work) {
                                            $relatedLandsCount = $work->lands->count() ?: 1;
                                            return ($work->hours_count * $work->hour_price) / $relatedLandsCount;
                                        });
    
                                        $monyExportValue = $land->monyExports->where('date', $date->toDateString())->sum(function ($export) {
                                            $relatedLandsCount = $export->lands->count() ?: 1;
                                            return $export->value / $relatedLandsCount;
                                        });
    
                                        $monyImportValue = $land->monyImports->where('date', $date->toDateString())->sum(function ($import) {
                                            $relatedLandsCount = $import->lands->count() ?: 1;
                                            return $import->value / $relatedLandsCount;
                                        });
    
                                        $salesProducts = $land->sales->flatMap(function ($sale) use ($date) {
                                            if ($sale->date == $date->toDateString()) {
                                                $relatedLandsCount = $sale->lands->count() ?: 1;
                                                return $sale->products->map(function ($product) use ($relatedLandsCount) {
                                                    return [
                                                        'name' => $product->name,
                                                        'quantity' => $product->pivot->quantity,
                                                        'price' => $product->pivot->price,
                                                        'total' => $product->pivot->total / $relatedLandsCount,
                                                    ];
                                                });
                                            }
                                            return [];
                                        });
    
                                        $totalSales = $land->sales->where('date', $date->toDateString())->sum(function ($sale) {
                                            $relatedLandsCount = $sale->lands->count() ?: 1;
                                            return $sale->products->sum('pivot.total') / $relatedLandsCount;
                                        });
    
                                        $rowTotal = $equipTotal + $monyExportValue + $totalAttendanceCost + $totalSales;
    
                                        // Calculate final value (total mony import minus row total)
                                        $final = $monyImportValue - $rowTotal;
    
                                        $landData[] = [
                                            'name' => $land->name,
                                            'date' => $date->toDateString(),
                                            'equip.name' => $land->equipWorks->where('date', $date->toDateString())->pluck('equip.name')->implode(', '),
                                            'equip_work.hours_count' => $land->equipWorks->where('date', $date->toDateString())->sum('hours_count'),
                                            'equip_work.total' => $equipTotal,
                                            'mony_export.monyType.name' => $land->monyExports->where('date', $date->toDateString())->pluck('monyType.name')->implode(', '),
                                            'mony_export.value' => $monyExportValue,
                                            'mony_import.monyType.name' => $land->monyImports->where('date', $date->toDateString())->pluck('monyType.name')->implode(', '),
                                            'mony_import.value' => $monyImportValue,
                                            'total_attendance_cost' => $totalAttendanceCost,
                                            'attendance_details' => $land->attendances
                                                ->where('date', $date->toDateString())
                                                ->map(function ($attendance) {
                                                    return [
                                                        'work_type' => $attendance->workType->name ?? 'غير محدد',
                                                        'employee_count' => $attendance->employees->count(),
                                                    ];
                                                })->values()->toArray(),
                                            'sales_products' => $salesProducts,
                                            'total_sales' => $totalSales,
                                            'row_total' => $rowTotal,
                                            'final' => $final,
                                        ];
    
                                        $totals['equip_work_total'] += $equipTotal;
                                        $totals['mony_export_value'] += $monyExportValue;
                                        $totals['mony_import_value'] += $monyImportValue;
                                        $totals['total_attendance_cost'] += $totalAttendanceCost;
                                        $totals['total_sales'] += $totalSales;
                                        $totals['row_total'] += $rowTotal;
                                        $totals['final'] += $final;
                                    }
                                }
    
                                $landData[] = [
                                    'name' => 'الإجمالي',
                                    'date' => null,
                                    'equip.name' => null,
                                    'equip_work.hours_count' => null,
                                    'equip_work.total' => $totals['equip_work_total'],
                                    'mony_export.monyType.name' => null,
                                    'mony_export.value' => $totals['mony_export_value'],
                                    'mony_import.monyType.name' => null,
                                    'mony_import.value' => $totals['mony_import_value'],
                                    'total_attendance_cost' => $totals['total_attendance_cost'],
                                    'attendance_details' => [],
                                    'sales_products' => [],
                                    'total_sales' => $totals['total_sales'],
                                    'row_total' => $totals['row_total'],
                                    'final' => $totals['final'],
                                ];
    
                                return collect($landData);
                            }),
                    ]),
            ]);
    }
    public function footer(Footer $footer): Footer
    {
        return $footer
            ->schema([
                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('land_id')
                    ->label("اسم الأرض")
                    ->options(Land::pluck('name', 'id'))
                    ->searchable()
                    ->preload()
                // ->multiple()
                ,
            ]);
    }
}
