<?php

namespace App\Livewire\HR;

use App\Domain\HR\Models\Employee;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('ملف الموظف')]
class EmployeeShow extends Component
{
    public Employee $employee;
    public string $activeTab = 'overview';

    public function mount(Employee $employee): void
    {
        $this->authorize('employees.list');
        $this->employee = $employee->load([
            'person',
            'user',
            'branch',
            'manager.person',
            'directReports.person',
            'trainer',
            'creator',
            'documents',
        ]);
    }

    public function delete(): void
    {
        $this->authorize('employees.delete');

        DB::transaction(function () {
            if ($this->employee->trainer) {
                $this->employee->trainer->update(['status' => 'inactive']);
            }

            if ($this->employee->user_id) {
                $user = \App\Models\User::find($this->employee->user_id);
                if ($user) {
                    if ($user->person_id) {
                        \App\Domain\Identity\Models\Person::where('id', $user->person_id)
                            ->update(['user_id' => null]);
                    }
                    $user->delete();
                }
            }

            $this->employee->delete();
        });

        session()->flash('success', __('تم حذف الموظف بنجاح'));
        $this->redirect(route('employees.list'), navigate: true);
    }

    public function render()
    {
        $person = $this->employee->person;

        // Tenure calculation
        $tenureYears = 0;
        $tenureMonths = 0;
        if ($this->employee->start_date) {
            $endDate = $this->employee->end_date ?? now();
            $tenureYears = $this->employee->start_date->diffInYears($endDate);
            $tenureMonths = $this->employee->start_date->diffInMonths($endDate) % 12;
        }

        // Direct reports count
        $directReportsCount = $this->employee->directReports->count();

        // Documents count
        $documentsCount = $this->employee->documents->count();

        // Monthly salary equivalent (convert based on frequency)
        $monthlySalary = $this->calculateMonthlySalary();

        // Is trainer
        $isTrainer = $this->employee->trainer !== null;

        return view('livewire.hr.employee-show', [
            'person' => $person,
            'tenureYears' => $tenureYears,
            'tenureMonths' => $tenureMonths,
            'directReportsCount' => $directReportsCount,
            'documentsCount' => $documentsCount,
            'monthlySalary' => $monthlySalary,
            'isTrainer' => $isTrainer,
        ]);
    }

    private function calculateMonthlySalary(): int
    {
        $salary = $this->employee->salary_amount ?? 0;
        $frequency = $this->employee->salary_frequency;

        if (!$frequency) {
            return $salary;
        }

        return match ($frequency->value) {
            'monthly' => $salary,
            'biweekly' => (int) round($salary * 2),
            'weekly' => (int) round($salary * 4.33),
            'daily' => (int) round($salary * 30),
            'hourly' => (int) round($salary * ($this->employee->working_hours_per_week ?? 40) * 4.33),
            default => $salary,
        };
    }
}
