<?php

namespace App\Filament\Pages;

use Carbon\Carbon;
use App\Models\Sale;
use Filament\Pages\Page;
use App\Models\SaleReturn;
use App\Models\CashMovement;
use Filament\Schemas\Schema;
use App\Models\CustomerPayment;
use Illuminate\Contracts\View\View;
use Filament\Support\Icons\Heroicon;
use Filament\Forms\Contracts\HasForms;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Concerns\InteractsWithForms;
use App\Exports\IncomeAnalysisExport;
use Maatwebsite\Excel\Facades\Excel;
use Mpdf\Mpdf;
use BezhanSalleh\FilamentShield\Traits\HasPageShield;

class IncomeAnalysisReport extends Page implements HasForms
{
    use InteractsWithForms;
    use HasPageShield;

    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedChartBar;

    protected string $view = 'filament.pages.income-analysis-report';

    protected static ?int $navigationSort = 9;

    public ?array $data = [];

    public ?array $report_data = null;

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

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

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

    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()
                    ->columns(2)
                    ->schema([
                        DatePicker::make('from_date')
                            ->label(__('filament/admin/reports.from_date'))
                            ->native(false),

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

    public function generateReport(): void
    {
        $formData = $this->form->getState();
        $from_date = !empty($formData['from_date']) ? Carbon::parse($formData['from_date'])->startOfDay() : null;
        $to_date = !empty($formData['to_date']) ? Carbon::parse($formData['to_date'])->endOfDay() : Carbon::now()->endOfDay();

        if ($from_date && $to_date->lt($from_date)) {
            \Filament\Notifications\Notification::make()
                ->title(__('filament/admin/income_analysis_report.تاريخالنهايةيجبأنيكونبعدأويساويتاريخالبداية'))
                ->warning()
                ->send();
            $this->report_data = [];
            return;
        }

        // 1. مدفوعات العملاء (CustomerPayment)
        $customer_payments_query = CustomerPayment::where('status', 'confirmed');
        if ($from_date) {
            $customer_payments_query->where('created_at', '>=', $from_date);
        }
        $customer_payments_query->where('created_at', '<=', $to_date);
        $customer_payments = $customer_payments_query->sum('amount');
        $customer_payments_count = $customer_payments_query->count();

        // 2. المدفوع في فواتير البيع (Sale.paid_amount)
        $sale_payments_query = Sale::query();
        if ($from_date) {
            $sale_payments_query->where('created_at', '>=', $from_date);
        }
        $sale_payments_query->where('created_at', '<=', $to_date);
        $sale_payments = $sale_payments_query->sum('paid_amount');
        $sale_payments_count = $sale_payments_query->where('paid_amount', '>', 0)->count();

        // 3. المسترد للعملاء في مرتجعات البيع (SaleReturn.paid_amount) - يخصم من الإيرادات
        $sale_return_refunds_query = SaleReturn::query();
        if ($from_date) {
            $sale_return_refunds_query->where('created_at', '>=', $from_date);
        }
        $sale_return_refunds_query->where('created_at', '<=', $to_date);
        $sale_return_refunds = $sale_return_refunds_query->sum('paid_amount');
        $sale_return_refunds_count = $sale_return_refunds_query->where('paid_amount', '>', 0)->count();

        // 4. حركات نقدية واردة (CashMovement where movement_type = 'in')
        $cash_in_query = CashMovement::where('movement_type', 'in');
        if ($from_date) {
            $cash_in_query->where('date', '>=', $from_date);
        }
        $cash_in_query->where('date', '<=', $to_date);
        $cash_in = $cash_in_query->sum('amount');
        $cash_in_count = $cash_in_query->count();

        // حساب الإجمالي
        $total_income = $customer_payments + $sale_payments + $cash_in - $sale_return_refunds;

        $this->report_data = [
            'from_date' => $from_date?->format('Y-m-d'),
            'to_date' => $to_date->format('Y-m-d'),
            'income' => [
                'customer_payments' => [
                    'amount' => $customer_payments,
                    'count' => $customer_payments_count,
                ],
                'sale_payments' => [
                    'amount' => $sale_payments,
                    'count' => $sale_payments_count,
                ],
                'sale_return_refunds' => [
                    'amount' => $sale_return_refunds,
                    'count' => $sale_return_refunds_count,
                ],
                'cash_in' => [
                    'amount' => $cash_in,
                    'count' => $cash_in_count,
                ],
            ],
            'summary' => [
                'total_income' => $total_income,
                'total_transactions' => $customer_payments_count + $sale_payments_count + $cash_in_count - $sale_return_refunds_count,
            ],
        ];
    }

    public function exportExcel()
    {
        if (empty($this->report_data)) {
            $this->generateReport();
        }

        return Excel::download(
            new IncomeAnalysisExport($this->report_data, $this->data['from_date'], $this->data['to_date']),
            'income-analysis-' . now()->format('Y-m-d') . '.xlsx'
        );
    }

    public function exportPdf()
    {
        if (empty($this->report_data)) {
            $this->generateReport();
        }

        $mpdf = new Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'orientation' => 'L',
            'default_font' => 'dejavusans',
            'autoScriptToLang' => true,
            'autoLangToFont' => true,
        ]);

        $mpdf->SetDirectionality('rtl');

        $html = view('reports.pdf.income-analysis', [
            'data' => $this->report_data,
        ])->render();

        $mpdf->WriteHTML($html);

        return response()->streamDownload(function () use ($mpdf) {
            echo $mpdf->Output('', 'S');
        }, 'income-analysis-' . now()->format('Y-m-d') . '.pdf');
    }
}
