<?php

namespace App\Filament\Pages;

use Carbon\Carbon;
use App\Models\Sale;
use App\Models\Customer;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
use App\Models\CustomerPayment;
use App\Exports\CustomerStatementExport;
use Illuminate\Contracts\View\View;
use Filament\Forms\Components\Select;
use Filament\Forms\Contracts\HasForms;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Concerns\InteractsWithForms;
use Maatwebsite\Excel\Facades\Excel;
use Mpdf\Mpdf;

class CustomerStatementReport extends Page implements HasForms
{
    use InteractsWithForms;

    protected string $view = 'filament.pages.customer-statement-report';

    public ?array $data = [];

    public array $statement_data = [];

    protected static string|\UnitEnum|null $navigationGroup = 'customers';
    protected static ?int $navigationSort = 5;

    public function getTitle(): string
    {
        return __('filament/admin/reports.customer_statement');
    }

    public static function getNavigationLabel(): string
    {
        return __('filament/admin/reports.customer_statement');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('filament.navigation_groups.customers');
    }

    public function mount(): void
    {
        $this->form->fill([
            'from_date' => now()->startOfMonth(),
            'to_date' => now()->endOfMonth(),
        ]);
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->statePath('data')
            ->components([
                Section::make(__('filament/admin/reports.filters'))
                    ->columns(4)
                    ->schema([
                        Select::make('customer_id')
                            ->label(__('filament/admin/reports.customer'))
                            ->placeholder(__('filament/admin/reports.select_customer'))
                            ->options(Customer::pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->required()
                            ->live()
                            ->afterStateUpdated(function ($set) {
                                $set('farm_id', null);
                            }),

                        Select::make('farm_id')
                            ->label(__('filament/admin/farm_resource.farm'))
                            ->placeholder(__('filament/admin/farm_resource.select_farm'))
                            ->options(function ($get) {
                                $customerId = $get('customer_id');
                                if (!$customerId) {
                                    return [];
                                }
                                return \App\Models\Farm::where('customer_id', $customerId)
                                    ->pluck('name', 'id');
                            })
                            ->searchable()
                            ->preload()
                            ->visible(fn($get) => !empty($get('customer_id'))),

                        DatePicker::make('from_date')
                            ->label(__('filament/admin/reports.from_date'))
                            ->native(false),

                        DatePicker::make('to_date')
                            ->label(__('filament/admin/reports.to_date'))
                            ->native(false),
                    ]),
            ]);
    }

    public function generateStatement(): void
    {
        $customer_id = $this->data['customer_id'] ?? null;

        if (!$customer_id) {
            $this->statement_data = [];
            return;
        }

        $customer = Customer::findOrFail($customer_id);
        $farm_id = $this->data['farm_id'] ?? null;
        $from_date = isset($this->data['from_date']) ? Carbon::parse($this->data['from_date']) : null;
        $to_date = isset($this->data['to_date']) ? Carbon::parse($this->data['to_date'])->endOfDay() : Carbon::now();

        // حساب الرصيد الافتتاحي
        $opening_balance_query = Sale::where('customer_id', $customer_id);

        if ($farm_id) {
            $opening_balance_query->where('farm_id', $farm_id);
        }

        if ($from_date) {
            $opening_balance_query->where('created_at', '<', $from_date);
        }

        $opening_balance = $opening_balance_query->sum('remaining_amount');
        
        // جلب الفواتير
        $sales_query = Sale::where('customer_id', $customer_id);

        if ($farm_id) {
            $sales_query->where('farm_id', $farm_id);
        }

        if ($from_date) {
            $sales_query->where('created_at', '>=', $from_date);
        }
        
        $sales_query->where('created_at', '<=', $to_date);
        
        $sales = $sales_query->with('items')->orderBy('created_at')->get();

        // جلب المدفوعات
        $payments_query = CustomerPayment::where('customer_id', $customer_id)
            ->where('status', 'confirmed');
        
        if ($from_date) {
            $payments_query->where('created_at', '>=', $from_date);
        }
        
        $payments_query->where('created_at', '<=', $to_date);
        
        $payments = $payments_query->orderBy('created_at')->get();

        // بناء تفاصيل البيان
        $details = [];
        $current_balance = $opening_balance;

        foreach ($sales as $sale) {
            $details[] = [
                'type' => 'sale',
                'date' => $sale->created_at->format('Y-m-d'),
                'invoice_number' => $sale->id,
                'description' => 'فاتورة مبيعات',
                'subtotal' => $sale->subtotal,
                'discount' => $sale->discount_amount,
                'tax' => $sale->tax_amount,
                'total' => $sale->total_amount,
                'paid' => $sale->paid_amount,
                'remaining' => $sale->remaining_amount,
                'items' => $sale->items,
                'balance' => $current_balance + $sale->total_amount,
                'payment_status' => $sale->payment_status,
            ];
            $current_balance += $sale->total_amount;
        }

        foreach ($payments as $payment) {
            $details[] = [
                'type' => 'payment',
                'date' => $payment->created_at->format('Y-m-d'),
                'description' => 'سداد من العميل',
                'amount' => -$payment->amount,
                'payment_method' => $payment->payment_method,
                'balance' => $current_balance - $payment->amount,
            ];
            $current_balance -= $payment->amount;
        }

        usort($details, function ($a, $b) {
            return strtotime($a['date']) - strtotime($b['date']);
        });

        $this->statement_data = [
            'customer' => $customer,
            'from_date' => $from_date?->format('Y-m-d'),
            'to_date' => $to_date->format('Y-m-d'),
            'opening_balance' => $opening_balance,
            'closing_balance' => $current_balance,
            'total_sales' => $sales->sum('total_amount'),
            'total_paid' => $payments->sum('amount'),
            'details' => $details,
        ];
    }

    public function exportExcel()
    {
        if (empty($this->statement_data)) {
            return;
        }

        $customer = $this->statement_data['customer'];
        $fileName = 'customer_statement_' . $customer->id . '_' . now()->format('Y-m-d') . '.xlsx';

        return Excel::download(
            new CustomerStatementExport(
                $this->statement_data,
                $customer,
                $this->statement_data['from_date'],
                $this->statement_data['to_date']
            ),
            $fileName
        );
    }

    public function exportPdf()
    {
        if (empty($this->statement_data)) {
            return;
        }

        $html = view('reports.pdf.customer-statement', [
            'data' => $this->statement_data,
        ])->render();

        $mpdf = new Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'orientation' => 'L',
            'margin_left' => 10,
            'margin_right' => 10,
            'margin_top' => 10,
            'margin_bottom' => 10,
            'default_font' => 'dejavusans'
        ]);

        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;
        $mpdf->SetDirectionality('rtl');

        $mpdf->WriteHTML($html);

        $customer = $this->statement_data['customer'];
        $fileName = 'customer_statement_' . $customer->id . '_' . now()->format('Y-m-d') . '.pdf';

        return response()->streamDownload(function () use ($mpdf) {
            echo $mpdf->Output('', 'S');
        }, $fileName);
    }
}
