<?php

namespace App\Livewire\HR;

use App\Domain\HR\Enums\CompensationStatus;
use App\Domain\HR\Enums\CompensationType;
use App\Domain\HR\Models\Trainer;
use App\Domain\HR\Models\TrainerCompensation;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('تعويضات المدرب')]
class TrainerCompensations extends Component
{
    use WithPagination;

    public Trainer $trainer;

    #[Url]
    public string $typeFilter = '';

    #[Url]
    public string $statusFilter = '';

    #[Url]
    public string $dateFrom = '';

    #[Url]
    public string $dateTo = '';

    // Summary stats
    public int $totalEarnings = 0;
    public int $totalPenalties = 0;
    public int $netAmount = 0;
    public int $sessionsCount = 0;

    public function mount(Trainer $trainer): void
    {
        $this->authorize('payroll.manage');
        $this->trainer = $trainer;
        $this->dateFrom = now()->startOfMonth()->format('Y-m-d');
        $this->dateTo = now()->format('Y-m-d');
        $this->loadSummary();
    }

    public function updatedDateFrom(): void
    {
        $this->resetPage();
        $this->loadSummary();
    }

    public function updatedDateTo(): void
    {
        $this->resetPage();
        $this->loadSummary();
    }

    public function updatedTypeFilter(): void
    {
        $this->resetPage();
    }

    public function updatedStatusFilter(): void
    {
        $this->resetPage();
    }

    public function loadSummary(): void
    {
        $baseQuery = TrainerCompensation::where('trainer_id', $this->trainer->id)
            ->whereNotIn('status', [CompensationStatus::Cancelled->value]);

        if ($this->dateFrom) {
            $baseQuery->where('date', '>=', $this->dateFrom);
        }
        if ($this->dateTo) {
            $baseQuery->where('date', '<=', $this->dateTo);
        }

        $all = $baseQuery->get();
        $this->totalEarnings = $all->filter(fn ($c) => $c->type->isEarning())->sum('amount');
        $this->totalPenalties = $all->filter(fn ($c) => ! $c->type->isEarning())->sum('amount');
        $this->netAmount = $this->totalEarnings - $this->totalPenalties;
        $this->sessionsCount = $all->whereIn('type', [CompensationType::SessionPay, CompensationType::Substitute])->count();
    }

    public function approveRecord(int $id): void
    {
        $record = TrainerCompensation::findOrFail($id);
        if ($record->status === CompensationStatus::Pending) {
            $record->update([
                'status'      => CompensationStatus::Approved,
                'approved_by' => auth()->id(),
                'approved_at' => now(),
            ]);
            session()->flash('success', __('تم اعتماد السجل'));
            $this->loadSummary();
        }
    }

    public function disputeRecord(int $id): void
    {
        $record = TrainerCompensation::findOrFail($id);
        if (in_array($record->status, [CompensationStatus::Pending, CompensationStatus::Approved])) {
            $record->update(['status' => CompensationStatus::Disputed]);
            session()->flash('success', __('تم تسجيل الاعتراض'));
            $this->loadSummary();
        }
    }

    public function render()
    {
        $query = TrainerCompensation::where('trainer_id', $this->trainer->id)
            ->with('session')
            ->latest('date');

        if ($this->typeFilter) {
            $query->where('type', $this->typeFilter);
        }
        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }
        if ($this->dateFrom) {
            $query->where('date', '>=', $this->dateFrom);
        }
        if ($this->dateTo) {
            $query->where('date', '<=', $this->dateTo);
        }

        return view('livewire.hr.trainer-compensations', [
            'compensations' => $query->paginate(20),
            'types'         => CompensationType::cases(),
            'statuses'      => CompensationStatus::cases(),
        ]);
    }
}
