<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class EmployeeTransfer extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'employee_id',
        'from_company_id',
        'to_company_id',
        'from_department_id',
        'to_department_id',
        'from_position',
        'to_position',
        'from_salary',
        'to_salary',
        'transfer_date',
        'effective_date',
        'transfer_type',
        'return_date',
        'reason',
        'status',
        'requested_by',
        'approved_by',
        'approved_at',
        'approval_notes',
    ];

    protected $casts = [
        'from_salary' => 'decimal:2',
        'to_salary' => 'decimal:2',
        'transfer_date' => 'date',
        'effective_date' => 'date',
        'return_date' => 'date',
        'approved_at' => 'datetime',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['*'])
            ->logOnlyDirty();
    }

    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }

    public function fromCompany()
    {
        return $this->belongsTo(Company::class, 'from_company_id');
    }

    public function toCompany()
    {
        return $this->belongsTo(Company::class, 'to_company_id');
    }

    public function fromDepartment()
    {
        return $this->belongsTo(Department::class, 'from_department_id');
    }

    public function toDepartment()
    {
        return $this->belongsTo(Department::class, 'to_department_id');
    }

    public function requester()
    {
        return $this->belongsTo(User::class, 'requested_by');
    }

    public function approver()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function complete()
    {
        if ($this->status !== 'approved') {
            return false;
        }

        $employee = $this->employee;
        $employee->update([
            'company_id' => $this->to_company_id,
            'department_id' => $this->to_department_id,
            'position' => $this->to_position,
            'salary' => $this->to_salary ?? $employee->salary,
        ]);

        $this->update(['status' => 'completed']);

        return true;
    }
}
