<?php

namespace App\Filament\Reports;

use App\Models\Employee;
use App\Models\MonyExport;
use App\Models\Setting;
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;

class EmployeeSalaryReport extends Report
{
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    public static function getNavigationLabel(): string
    {
        return "تقرير مرتبات الموظفين";
    }
    protected static ?int $navigationSort = 1;

    protected static ?string $navigationGroup = 'التقارير';

    public function getTitle(): string
    {
        return "تقرير مرتبات الموظفين";
    }
    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);

        $from = Carbon::createFromFormat("d/m/Y", $from)->startOfDay();
        $to = Carbon::createFromFormat("d/m/Y", $to)->endOfDay();
        
        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('attendances_count')
                                    ->label("عدد الحضور الكامل"),
                                Body\TextColumn::make('attendances_half_day_count')
                                    ->label("عدد الحضور نصف يوم"),
                                Body\TextColumn::make('attendances_gamaeya_count')
                                    ->label("عدد الحضور جمعية"),
                                Body\TextColumn::make('totalEarnings')
                                    ->label("إجمالي المرتب")
                                    ->formatStateUsing(fn ($state) => number_format($state, 2)),
                                Body\TextColumn::make('breadAllowance')
                                    ->label("اجمالي العيش")
                                    ->formatStateUsing(fn ($state) => number_format($state, 2)),
                                Body\TextColumn::make('monyType7DeductionPerEmployeePerWeek')
                                    ->label("إجمالي جمعيه")
                                    ->formatStateUsing(fn ($state) => number_format($state, 2)),
                                Body\TextColumn::make('monyType8Deduction')
                                    ->label("إجمالي سلف")
                                    ->formatStateUsing(fn ($state) => number_format($state, 2)),
                                Body\TextColumn::make('totalDeductions')
                                    ->label("إجمالي الخصم")
                                    ->formatStateUsing(fn ($state) => number_format($state, 2)),
                                Body\TextColumn::make('netSalary')
                                    ->label("صافي المرتب")
                                    ->formatStateUsing(fn ($state) => number_format($state, 2)),
                            ])
                            ->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);
                                    $employeesQuery = Employee::with([
                                        'attendances' => function ($query) use ($startDate, $endDate) {
                                            $query->whereBetween('date', [$startDate, $endDate]);
                                        },
                                        'attendances_half_day' => function ($query) use ($startDate, $endDate) {
                                            $query->whereIn('attendance_id', function ($subQuery) use ($startDate, $endDate) {
                                                $subQuery->select('id')
                                                    ->from('attendances')
                                                    ->whereBetween('date', [$startDate, $endDate]);
                                            });
                                        },
                                        'attendances_gamaeya' => function ($query) use ($startDate, $endDate) {
                                            $query->whereIn('attendance_id', function ($subQuery) use ($startDate, $endDate) {
                                                $subQuery->select('id')
                                                    ->from('attendances')
                                                    ->whereBetween('date', [$startDate, $endDate]);
                                            });
                                        }
                                    ])->whereHas('attendances', function ($query) use ($startDate, $endDate) {
                                        $query->whereBetween('date', [$startDate, $endDate]);
                                    });
                                    
                                    
                                    
                                    // Apply employee filter only if set
                                    if (!empty($filters['employee_id'])) {
                                        $employeesQuery->whereIn('id', (array)$filters['employee_id']);
                                    }
    
                                    $employees = $employeesQuery->get();
    
                                    $employeeSalaries = [];
                                    $totals = [
                                        'attendances_count' => 0,
                                        'attendances_half_day_count' => 0,
                                        'attendances_gamaeya_count' => 0,
                                        'totalEarnings' => 0,
                                        'breadAllowance' => 0,
                                        'monyType7DeductionPerEmployeePerWeek' => 0,
                                        'monyType8Deduction' => 0,
                                        'totalDeductions' => 0,
                                        'netSalary' => 0,
                                    ];
    
                                    foreach ($employees as $employee) {
                                        $name = $employee->name;
                                        $totalEarnings1 = 0;
                                        $breadAllowance = 0;
                                        $monyType7Deductions = 0;
                                        $monyType8Deductions = 0;
    
                                        $dailyBreadAllowance = Setting::latest()->first()->bread_price ?? 0;
                                        $dailySalaryAllowance = Setting::latest()->first()->daily_price ?? 0;
    
                                        // Count attendances
                                        $attendancesCount = $employee->attendances->count();
                                        $attendancesHalfDayCount = $employee->attendances_half_day->count();
                                        $attendancesGamaeyaCount = $employee->attendances_gamaeya->count();
    
                                        $breadAllowance = $attendancesCount * $dailyBreadAllowance;
    
                                        foreach ($employee->attendances as $attendance) {
                                            $totalEarnings1 += $dailySalaryAllowance;
                                        }
                                        foreach ($employee->attendances_half_day as $attendance) {
                                            $totalEarnings1 += $dailySalaryAllowance / 2;
                                        }
    
                                        foreach ($employee->attendances_gamaeya as $attendance) {
                                            $gameyaPrice = Setting::latest()->first()->gameya_price ?? 0;
                                            $employeesOnThisDay = $attendance->employees_gamaeya->count();
                                            $monyType7Deductions += $employeesOnThisDay > 0 ? $gameyaPrice : 0;
                                        }
    
                                        $weekMonyExportValue = MonyExport::where('mony_type_id', 7)
                                            ->where('employee_id', $employee->id)
                                            ->when($startDate && $endDate, function ($query) use ($startDate, $endDate) {
                                                return $query->whereBetween('date', [$startDate, $endDate]);
                                            })
                                            ->sum('value');
    
                                        $monyType8Deductions += $weekMonyExportValue;
    
                                        $totalDeductions = $breadAllowance + $monyType8Deductions + $monyType7Deductions;
                                        $netSalary = $totalEarnings1 - $totalDeductions;
    
                                        $employeeSalaries[] = [
                                            'name' => $name,
                                            'attendances_count' => $attendancesCount,
                                            'attendances_half_day_count' => $attendancesHalfDayCount,
                                            'attendances_gamaeya_count' => $attendancesGamaeyaCount,
                                            'totalEarnings' => $totalEarnings1,
                                            'breadAllowance' => $breadAllowance,
                                            'monyType7DeductionPerEmployeePerWeek' => $monyType7Deductions,
                                            'monyType8Deduction' => $monyType8Deductions,
                                            'totalDeductions' => $totalDeductions,
                                            'netSalary' => $netSalary,
                                        ];
    
                                        // Accumulate totals
                                        $totals['attendances_count'] += $attendancesCount;
                                        $totals['attendances_half_day_count'] += $attendancesHalfDayCount;
                                        $totals['attendances_gamaeya_count'] += $attendancesGamaeyaCount;
                                        $totals['totalEarnings'] += $totalEarnings1;
                                        $totals['breadAllowance'] += $breadAllowance;
                                        $totals['monyType7DeductionPerEmployeePerWeek'] += $monyType7Deductions;
                                        $totals['monyType8Deduction'] += $monyType8Deductions;
                                        $totals['totalDeductions'] += $totalDeductions;
                                        $totals['netSalary'] += $netSalary;
                                    }
    
                                    // Add totals row
                                    $employeeSalaries[] = [
                                        'name' => 'الإجمالي',
                                        'attendances_count' => $totals['attendances_count'],
                                        'attendances_half_day_count' => $totals['attendances_half_day_count'],
                                        'attendances_gamaeya_count' => $totals['attendances_gamaeya_count'],
                                        'totalEarnings' => $totals['totalEarnings'],
                                        'breadAllowance' => $totals['breadAllowance'],
                                        'monyType7DeductionPerEmployeePerWeek' => $totals['monyType7DeductionPerEmployeePerWeek'],
                                        'monyType8Deduction' => $totals['monyType8Deduction'],
                                        'totalDeductions' => $totals['totalDeductions'],
                                        'netSalary' => $totals['netSalary'],
                                    ];
    
                                    return collect($employeeSalaries);
                                }
                            ),
                    ]),
            ]);
    }    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('employee_id')
                    ->label('العمال')
                    ->options(
                        Employee::all()->pluck('name', 'id')->toArray()
                    )
                    ->placeholder('إختر عامل')
                    ->preload()
                    ->multiple()
            ]);
    }
}
