<?php

namespace App\Models;

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

class IntercompanyLoan extends Model
{
    use HasFactory, SoftDeletes, LogsActivity;

    protected $fillable = [
        'loan_number',
        'lender_company_id',
        'borrower_company_id',
        'principal_amount',
        'outstanding_balance',
        'interest_rate',
        'interest_type',
        'disbursement_date',
        'maturity_date',
        'term_months',
        'payment_frequency',
        'status',
        'purpose',
        'terms_conditions',
        'approved_by',
        'approved_at',
        'requested_by',
        'rejected_by',
        'rejected_at',
        'rejection_reason',
        'due_date',
        'payment_method',
        'bank_account_id',
        'is_super_admin_lender',
        'super_admin_bank_account_id',
    ];

    protected $casts = [
        'principal_amount' => 'decimal:2',
        'outstanding_balance' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'disbursement_date' => 'date',
        'maturity_date' => 'date',
        'approved_at' => 'datetime',
        'is_super_admin_lender' => 'boolean',
    ];

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

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

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

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

    public function repayments()
    {
        return $this->hasMany(LoanRepayment::class, 'loan_id');
    }

    public function bankAccount()
    {
        return $this->belongsTo(BankAccount::class);
    }

    public function superAdminBankAccount()
    {
        return $this->belongsTo(SuperAdminBankAccount::class, 'super_admin_bank_account_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($loan) {
            if (!$loan->loan_number) {
                $loan->loan_number = 'LOAN-' . date('Y') . '-' . str_pad(
                    static::whereYear('created_at', date('Y'))->count() + 1,
                    5,
                    '0',
                    STR_PAD_LEFT
                );
            }
            
            // Debug: Log what interest_type is being set
            \Log::info('Model creating - interest_type before fix:', ['interest_type' => $loan->interest_type]);
            
            // Force interest_type to 'simple' to avoid enum issues
            if ($loan->interest_type === 'fixed') {
                \Log::info('Converting fixed to simple');
                $loan->interest_type = 'simple';
            }
            
            \Log::info('Model creating - interest_type after fix:', ['interest_type' => $loan->interest_type]);
        });
    }

    public function calculateMonthlyPayment()
    {
        if ($this->payment_frequency === 'bullet') {
            return 0;
        }

        $rate = $this->interest_rate / 100 / 12;
        $n = $this->term_months;
        $p = $this->principal_amount;

        if ($rate == 0) {
            return $p / $n;
        }

        return $p * ($rate * pow(1 + $rate, $n)) / (pow(1 + $rate, $n) - 1);
    }

    public function generateRepaymentSchedule()
    {
        $schedule = [];
        $balance = $this->principal_amount;
        $monthlyPayment = $this->calculateMonthlyPayment();
        $startDate = $this->disbursement_date;

        for ($i = 1; $i <= $this->term_months; $i++) {
            $dueDate = $startDate->copy()->addMonths($i);
            $interestPayment = $balance * ($this->interest_rate / 100 / 12);
            $principalPayment = $monthlyPayment - $interestPayment;
            $balance -= $principalPayment;

            $schedule[] = [
                'payment_number' => $i,
                'due_date' => $dueDate,
                'principal_amount' => round($principalPayment, 2),
                'interest_amount' => round($interestPayment, 2),
                'total_amount' => round($monthlyPayment, 2),
                'remaining_balance' => round($balance, 2),
            ];
        }

        return $schedule;
    }
}
