<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class LoanInstallment extends Model
{
    use HasFactory;

    protected $fillable = [
        'loan_id',
        'installment_number',
        'due_date',
        'principal_amount',
        'interest_amount',
        'total_amount', // ✅ আপনার টেবিলে এই নামে আছে
        'amount', // ✅ যোগ করুন যদি না থাকে
        'paid_amount', // ✅ যোগ করুন
        'payment_date',
        'late_fee',
        'status',
        'collected_by',
        'payment_method',
        'transaction_id',
        'remarks',
        'description', // ✅ যোগ করুন
    ];

    protected $casts = [
        'due_date' => 'date',
        'payment_date' => 'date',
        'principal_amount' => 'decimal:2',
        'interest_amount' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'amount' => 'decimal:2', // ✅ যোগ করুন
        'paid_amount' => 'decimal:2', // ✅ যোগ করুন
        'late_fee' => 'decimal:2',
    ];

    protected $appends = [
        'installment_in_bangla',
        'status_in_bangla',
        'is_overdue',
        'overdue_days',
        'total_paid',
        'formatted_amount', // ✅ যোগ করুন
        'formatted_total_amount', // ✅ যোগ করুন
    ];

    // Boot method
    protected static function boot()
    {
        parent::boot();

        // যদি amount ফিল্ড খালি থাকে কিন্তু total_amount থাকে
        static::creating(function ($installment) {
            if (empty($installment->amount) && !empty($installment->total_amount)) {
                $installment->amount = $installment->total_amount;
            }
            
            if (empty($installment->total_amount) && !empty($installment->amount)) {
                $installment->total_amount = $installment->amount;
            }
            
            // paid_amount সেট করুন
            if ($installment->status == 'paid' && empty($installment->paid_amount)) {
                $installment->paid_amount = $installment->amount;
            }
        });

        static::updating(function ($installment) {
            // status paid হলে paid_amount সেট করুন
            if ($installment->status == 'paid' && empty($installment->paid_amount)) {
                $installment->paid_amount = $installment->amount;
                $installment->payment_date = now();
            }
        });
    }

    // রিলেশনশিপ: ঋণ
    public function loan()
    {
        return $this->belongsTo(Loan::class);
    }

    // রিলেশনশিপ: সংগ্রহকারী
    public function collector()
    {
        return $this->belongsTo(User::class, 'collected_by');
    }

    // Accessor for amount (compatibility)
    public function getAmountAttribute()
    {
        // যদি amount attribute না থাকে, total_amount রিটার্ন করুন
        if (isset($this->attributes['amount'])) {
            return (float) $this->attributes['amount'];
        }
        
        return (float) $this->total_amount;
    }

    // Setter for amount
    public function setAmountAttribute($value)
    {
        $this->attributes['amount'] = (float) $value;
        // total_amount ও আপডেট করুন
        $this->attributes['total_amount'] = (float) $value;
    }

    // Setter for total_amount
    public function setTotalAmountAttribute($value)
    {
        $this->attributes['total_amount'] = (float) $value;
        // amount ও আপডেট করুন
        $this->attributes['amount'] = (float) $value;
    }

    // মোট পরিশোধ
    public function getTotalPaidAttribute()
    {
        $paid = (float) $this->paid_amount;
        $lateFee = (float) $this->late_fee;
        return $paid + $lateFee;
    }

    // ফরম্যাটেড amount
    public function getFormattedAmountAttribute()
    {
        return number_format((float) $this->amount, 2);
    }

    // ফরম্যাটেড total_amount
    public function getFormattedTotalAmountAttribute()
    {
        return number_format((float) $this->total_amount, 2);
    }

    // বিলম্ব ফি গণনা
    public function calculateLateFee()
    {
        if ($this->status == 'paid' || ($this->due_date && $this->due_date >= now())) {
            return 0;
        }
        
        if (!$this->due_date) {
            return 0;
        }
        
        $daysLate = now()->diffInDays($this->due_date);
        $lateFee = 0;
        
        if ($daysLate > 0) {
            // প্রতিদিন ১০ টাকা বিলম্ব ফি
            $lateFee = $daysLate * 10;
        }
        
        $this->late_fee = $lateFee;
        $this->save();
        
        return $lateFee;
    }

    // কিস্তি পরিশোধ
    public function markAsPaid($paymentData = [])
    {
        DB::beginTransaction();
        
        try {
            $this->status = 'paid';
            $this->payment_date = now();
            $this->paid_amount = $this->amount;
            
            if (!empty($paymentData)) {
                $this->fill($paymentData);
            }
            
            // বিলম্ব ফি গণনা
            $this->calculateLateFee();
            
            $this->save();
            
            // ঋণের স্ট্যাটাস আপডেট
            if ($this->loan) {
                $this->loan->recalculateBalances();
            }
            
            DB::commit();
            
            return $this;
            
        } catch (\Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    // কিস্তি বাংলায়
    public function getInstallmentInBanglaAttribute()
    {
        $numbers = [
            '1' => 'প্রথম',
            '2' => 'দ্বিতীয়',
            '3' => 'তৃতীয়',
            '4' => 'চতুর্থ',
            '5' => 'পঞ্চম',
            '6' => 'ষষ্ঠ',
            '7' => 'সপ্তম',
            '8' => 'অষ্টম',
            '9' => 'নবম',
            '10' => 'দশম',
            '11' => 'একাদশ',
            '12' => 'দ্বাদশ'
        ];
        
        return $numbers[$this->installment_number] ?? $this->installment_number . 'তম';
    }

    // স্ট্যাটাস বাংলায়
    public function getStatusInBanglaAttribute()
    {
        $statuses = [
            'pending' => 'বকেয়া',
            'paid' => 'পরিশোধিত',
            'partially_paid' => 'আংশিক পরিশোধিত',
            'overdue' => 'মেয়াদোত্তীর্ণ'
        ];
        
        return $statuses[$this->status] ?? $this->status;
    }

    // মেয়াদোত্তীর্ণ কিনা
    public function getIsOverdueAttribute()
    {
        if (!$this->due_date || $this->status == 'paid') {
            return false;
        }
        
        return $this->due_date < now() && $this->status == 'pending';
    }

    // মেয়াদোত্তীর্ণ দিন
    public function getOverdueDaysAttribute()
    {
        if (!$this->is_overdue || !$this->due_date) {
            return 0;
        }
        
        return now()->diffInDays($this->due_date);
    }

    // স্ট্যাটাস ক্লাস
    public function getStatusClassAttribute()
    {
        $classes = [
            'pending' => 'badge bg-warning',
            'paid' => 'badge bg-success',
            'partially_paid' => 'badge bg-info',
            'overdue' => 'badge bg-danger',
        ];
        
        return $classes[$this->status] ?? 'badge bg-light';
    }

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

    // Scope for paid installments
    public function scopePaid($query)
    {
        return $query->where('status', 'paid');
    }

    // Scope for overdue installments
    public function scopeOverdue($query)
    {
        return $query->where('status', 'pending')
                    ->where('due_date', '<', now());
    }

    // Get next due installment
    public static function getNextDueForLoan($loanId)
    {
        return self::where('loan_id', $loanId)
            ->where('status', 'pending')
            ->where('due_date', '>', now())
            ->orderBy('due_date', 'asc')
            ->first();
    }
}