<?php

namespace App\Http\Resources\Employee;

use App\Http\Resources\BaseResource;
use Illuminate\Http\Request;

class EmployeeResource extends BaseResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'employee_code' => $this->employee_code,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'full_name' => trim("{$this->first_name} {$this->last_name}"),
            'email' => $this->email,
            'phone' => $this->phone,
            'alternate_phone' => $this->alternate_phone,
            'date_of_birth' => $this->formatDate($this->date_of_birth),
            'gender' => $this->gender,
            'marital_status' => $this->marital_status,
            'blood_group' => $this->blood_group,
            'address' => $this->address,
            'city' => $this->city,
            'state' => $this->state,
            'pincode' => $this->pincode,
            'department' => $this->department,
            'designation' => $this->designation,
            'date_of_joining' => $this->formatDate($this->date_of_joining),
            'date_of_leaving' => $this->formatDate($this->date_of_leaving),
            'reporting_to' => $this->reporting_to,
            'reporting_manager' => new EmployeeResource($this->whenLoaded('reportingManager')),
            'employment_type' => $this->employment_type,
            'shift' => $this->shift,
            'bank_name' => $this->when($request->user()?->role === 'superadmin', $this->bank_name),
            'bank_account_no' => $this->when($request->user()?->role === 'superadmin', $this->bank_account_no),
            'ifsc_code' => $this->when($request->user()?->role === 'superadmin', $this->ifsc_code),
            'pan_no' => $this->when($request->user()?->role === 'superadmin', $this->pan_no),
            'aadhar_no' => $this->when($request->user()?->role === 'superadmin', $this->aadhar_no),
            'pf_no' => $this->pf_no,
            'esi_no' => $this->esi_no,
            'basic_salary' => $this->when($request->user()?->role === 'superadmin', $this->formatCurrency($this->basic_salary)),
            'status' => $this->status,
            'status_badge' => $this->getStatusBadge($this->status ?? 'active'),
            'photo' => $this->photo,
            'years_of_service' => $this->calculateYearsOfService(),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }

    protected function calculateYearsOfService(): ?float
    {
        if (!$this->date_of_joining) {
            return null;
        }

        $endDate = $this->date_of_leaving ?? now();
        $startDate = $this->date_of_joining instanceof \Carbon\Carbon
            ? $this->date_of_joining
            : \Carbon\Carbon::parse($this->date_of_joining);

        return round($startDate->diffInYears($endDate), 1);
    }
}
