<?php

namespace App\Filament\Pages;

use App\Models\Machine;
use App\Models\WorkOrder;
use App\Models\AdvanceExpense;
use App\Models\SparePartInstallation;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
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 BezhanSalleh\FilamentShield\Traits\HasPageShield;
use Filament\Support\Icons\Heroicon;

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

    protected string $view = 'filament.pages.machine-performance-report';

    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedChartBar;
    protected static ?string $navigationLabel = null;
    protected static ?int $navigationSort = 3;

    public static function getNavigationGroup(): string|null
    {
        return __('filament/admin/machine_performance_report.navigation_group');
    }

    public ?array $data = [];
    public array $rows = [];
    public array $summary = [];

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

    public function form(Schema $schema): Schema
    {
        return $schema
            ->statePath('data')
            ->components([
                Section::make(__('filament/admin/machine_performance_report.فلاترالتقرير'))
                    ->columns(3)
                    ->schema([
                        Select::make('machine_id')
                            ->label(__('filament/admin/machine_performance_report.المعدة'))
                            ->options(fn () => Machine::query()->where('is_active', true)->pluck('name', 'id')->toArray())
                            ->searchable()
                            ->preload(),

                        DatePicker::make('from_date')
                            ->label(__('filament/admin/machine_performance_report.منتاريخ'))
                            ->native(false)
                            ->required(),

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

    public function generateReport(): void
    {
        $machineId = $this->data['machine_id'] ?? null;
        $fromDate = $this->data['from_date'] ?? null;
        $toDate = $this->data['to_date'] ?? null;

        $machinesQuery = Machine::query()->where('is_active', true);

        if ($machineId) {
            $machinesQuery->where('id', $machineId);
        }

        $machines = $machinesQuery->get();

        $this->rows = $machines->map(function (Machine $machine) use ($fromDate, $toDate): array {
            // حساب الإيرادات من أوامر التشغيل
            $revenueQuery = WorkOrder::query()
                ->where('machine_id', $machine->id)
                ->whereIn('status', ['approved', 'invoiced']);

            if ($fromDate) {
                $revenueQuery->whereDate('order_date', '>=', $fromDate);
            }

            if ($toDate) {
                $revenueQuery->whereDate('order_date', '<=', $toDate);
            }

            $totalRevenue = (float) $revenueQuery->get()->sum(function ($workOrder) {
                return $workOrder->workOrderLines->sum('amount');
            });

            // حساب التكاليف من المصروفات
            $expensesQuery = AdvanceExpense::query()
                ->where('machine_id', $machine->id);

            if ($fromDate) {
                $expensesQuery->whereDate('expense_date', '>=', $fromDate);
            }

            if ($toDate) {
                $expensesQuery->whereDate('expense_date', '<=', $toDate);
            }

            $totalExpenses = (float) $expensesQuery->sum('amount');

            // حساب تكلفة قطع الغيار
            $sparePartsQuery = SparePartInstallation::query()
                ->where('machine_id', $machine->id);

            if ($fromDate) {
                $sparePartsQuery->whereDate('installation_date', '>=', $fromDate);
            }

            if ($toDate) {
                $sparePartsQuery->whereDate('installation_date', '<=', $toDate);
            }

            $totalSpareParts = (float) $sparePartsQuery->get()->sum(function ($installation) {
                return ($installation->installed_qty ?? 0) * ($installation->unit_cost ?? 0);
            });

            $totalCost = $totalExpenses + $totalSpareParts;
            $netProfit = $totalRevenue - $totalCost;
            $profitMargin = $totalRevenue > 0 ? ($netProfit / $totalRevenue) * 100 : 0;

            return [
                'machine_code' => $machine->code ?? '-',
                'machine_name' => $machine->name ?? '-',
                'machine_type' => $machine->type ?? '-',
                'total_revenue' => $totalRevenue,
                'total_expenses' => $totalExpenses,
                'spare_parts_cost' => $totalSpareParts,
                'total_cost' => $totalCost,
                'net_profit' => $netProfit,
                'profit_margin' => $profitMargin,
            ];
        })->toArray();

        // حساب الإجماليات
        $this->summary = [
            'total_machines' => count($this->rows),
            'total_revenue' => array_sum(array_column($this->rows, 'total_revenue')),
            'total_cost' => array_sum(array_column($this->rows, 'total_cost')),
            'total_profit' => array_sum(array_column($this->rows, 'net_profit')),
            'avg_profit_margin' => count($this->rows) > 0 
                ? array_sum(array_column($this->rows, 'profit_margin')) / count($this->rows) 
                : 0,
        ];
    }

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

    public static function canAccess(): bool
    {
        return auth()->check();
    }
    public static function getNavigationLabel(): string
    {
        return __('filament/admin/machine_performance_report.navigation_label');
    }

}
