<?php

namespace App\Modules\HR\Payroll\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Modules\HR\Core\Models\Employee;
use App\Modules\HR\Payroll\Models\Loan;

class EmployeeLoan extends Model
{
    use HasFactory;

    protected $table = 'employee_loans';

    protected $fillable = [
        'employee_id',
        'loan_id',
        'loan_number',
        'application_date',
        'full_amount',
        'approved_amount',
        'interest_rate',
        'installment_amount',
        'repayment_period',
        'remarks',
        'status',
        'start_date',
        'end_date',
        'remaining_amount',
    ];

    protected $casts = [
        'full_amount' => 'decimal:2',
        'approved_amount' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'installment_amount' => 'decimal:2',
        'remaining_amount' => 'decimal:2',
    ];

    /* ================= Relationships ================= */

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

    public function loan(): BelongsTo
    {
        return $this->belongsTo(Loan::class);
    }

    /* ================= Accessors & Mutators ================= */

    public function getStatusBadgeAttribute()
    {
        $badges = [
            'pending' => 'warning',
            'approved' => 'info',
            'active' => 'success',
            'completed' => 'secondary',
            'rejected' => 'danger',
        ];

        return $badges[$this->status] ?? 'secondary';
    }

    /* ================= Scopes ================= */

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeForEmployee($query, $employeeId)
    {
        return $query->where('employee_id', $employeeId);
    }

    /* ================= Helper Methods ================= */

    public function generateLoanNumber()
    {
        $year = now()->year;
        $lastLoan = static::where('loan_number', 'like', "LN-{$year}-%")
            ->orderBy('loan_number', 'desc')
            ->first();

        if ($lastLoan) {
            $lastNumber = (int) substr($lastLoan->loan_number, -5);
            $newNumber = str_pad($lastNumber + 1, 5, '0', STR_PAD_LEFT);
        } else {
            $newNumber = '00001';
        }

        return "LN-{$year}-{$newNumber}";
    }

    public function calculateInstallment()
    {
        if ($this->repayment_period > 0) {
            $principal = $this->approved_amount ?? $this->full_amount;
            $interest = ($principal * $this->interest_rate) / 100;
            $totalAmount = $principal + $interest;
            return round($totalAmount / $this->repayment_period, 2);
        }

        return 0;
    }

    public function updateRemainingAmount($paidAmount)
    {
        $this->remaining_amount = ($this->remaining_amount ?? $this->approved_amount) - $paidAmount;

        if ($this->remaining_amount <= 0) {
            $this->status = 'completed';
            $this->remaining_amount = 0;
        }

        $this->save();
    }
}
