<?php

namespace App\Filament\Reports;

use App\Models\Customer;
use App\Models\MonyImport;
use App\Models\MonyExport;
use App\Models\Sale;
use App\Models\Purchase;
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;

class AllCustomersReport extends Report
{
    protected static ?string $navigationIcon = 'heroicon-o-users';

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

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

    protected static ?int $navigationSort = 7;

    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("customer_name")->label("اسم العميل"),
                                Body\TextColumn::make("initial_balance")->label("الرصيد الأولي"),
                                Body\TextColumn::make("total_sales")->label("إجمالي المبيعات"),
                                Body\TextColumn::make("total_purchases")->label("إجمالي المشتريات"),
                                Body\TextColumn::make("total_mony_imports")->label("إجمالي الواردات النقدية"),
                                Body\TextColumn::make("total_mony_exports")->label("إجمالي الصادرات النقدية"),
                                Body\TextColumn::make("final_balance")->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');
                                    }

                                    [$from, $to] = $this->getCarbonInstancesFromDateString($filters['date'] ?? null);

                                    if (!$from || !$to) {
                                        return collect([]); // Ensure valid date range
                                    }

                                    $customers = Customer::all();
                                    $totals = [
                                        'initial_balance' => 0,
                                        'total_sales' => 0,
                                        'total_purchases' => 0,
                                        'total_mony_imports' => 0,
                                        'total_mony_exports' => 0,
                                        'final_balance' => 0,
                                    ];

                                    $data = $customers->map(function ($customer) use ($from, $to, &$totals) {
                                        // ابدأ بالرصيد الأولي من سجل العميل
                                        $initialBalance = $customer->first_mony ?? 0;

                                        // أضف جميع المعاملات قبل تاريخ البداية
                                        // المبيعات (العميل مدين)
                                        $salesTotal = Sale::where('customer_id', $customer->id)
                                            ->where('date', '<', $from)
                                            ->with('products')
                                            ->get()
                                            ->reduce(fn($carry, $sale) => $carry + $sale->products->sum('pivot.total'), 0);

                                        // المشتريات (العميل دائن)
                                        $purchasesTotal = Purchase::where('customer_id', $customer->id)
                                            ->where('date', '<', $from)
                                            ->with('products')
                                            ->get()
                                            ->reduce(fn($carry, $purchase) => $carry + $purchase->products->sum('pivot.total'), 0);

                                        // الواردات النقدية (العميل يدفع = يقل رصيده)
                                        $monyImportsTotal = MonyImport::where('customer_id', $customer->id)
                                            ->where('date', '<', $from)
                                            ->sum('value');

                                        // الصادرات النقدية (نعطي العميل = يزداد رصيده)
                                        $monyExportsTotal = MonyExport::where('customer_id', $customer->id)
                                            ->where('date', '<', $from)
                                            ->sum('value');

                                        // الحساب النهائي للرصيد الأولي (يتراكم من جميع المعاملات السابقة)
                                        $initialBalance = $initialBalance + $salesTotal - $purchasesTotal - $monyImportsTotal + $monyExportsTotal;

                                        $salesTotalInRange = Sale::where('customer_id', $customer->id)
                                            ->whereBetween('date', [$from, $to])
                                            ->with('products')
                                            ->get()
                                            ->reduce(fn($carry, $sale) => $carry + $sale->products->sum('pivot.total'), 0);

                                        $purchasesTotalInRange = Purchase::where('customer_id', $customer->id)
                                            ->whereBetween('date', [$from, $to])
                                            ->with('products')
                                            ->get()
                                            ->reduce(fn($carry, $purchase) => $carry + $purchase->products->sum('pivot.total'), 0);

                                        $monyImportsTotalInRange = MonyImport::where('customer_id', $customer->id)
                                            ->whereBetween('date', [$from, $to])
                                            ->sum('value');

                                        $monyExportsTotalInRange = MonyExport::where('customer_id', $customer->id)
                                            ->whereBetween('date', [$from, $to])
                                            ->sum('value');

                                        $finalBalance = $initialBalance +
                                            $salesTotalInRange -
                                            $purchasesTotalInRange -
                                            $monyImportsTotalInRange +
                                            $monyExportsTotalInRange;

                                        $totals['initial_balance'] += $initialBalance;
                                        $totals['total_sales'] += $salesTotalInRange;
                                        $totals['total_purchases'] += $purchasesTotalInRange;
                                        $totals['total_mony_imports'] += $monyImportsTotalInRange;
                                        $totals['total_mony_exports'] += $monyExportsTotalInRange;
                                        $totals['final_balance'] += $finalBalance;

                                        return [
                                            'customer_name' => $customer->name,
                                            'initial_balance' => $initialBalance,
                                            'total_sales' => $salesTotalInRange,
                                            'total_purchases' => $purchasesTotalInRange,
                                            'total_mony_imports' => $monyImportsTotalInRange,
                                            'total_mony_exports' => $monyExportsTotalInRange,
                                            'final_balance' => $finalBalance,
                                        ];
                                    });

                                    $data->push([
                                        'customer_name' => 'الإجمالي',
                                        'initial_balance' => $totals['initial_balance'],
                                        'total_sales' => $totals['total_sales'],
                                        'total_purchases' => $totals['total_purchases'],
                                        'total_mony_imports' => $totals['total_mony_imports'],
                                        'total_mony_exports' => $totals['total_mony_exports'],
                                        'final_balance' => $totals['final_balance'],
                                    ]);

                                    return $data;
                                }
                            ),
                    ]),
            ]);
    }

    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)
                    ->required(),

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