<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Installment extends Model
{
    use HasFactory;

    protected $fillable = [
        'sale_id',
        'installment_no',
        'amount',
        'paid_amount',
        'due_amount',
        'due_date',
        'payment_date',
        'status',
        'late_fee',
        'grace_period_days',
        'notes'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'due_amount' => 'decimal:2',
        'late_fee' => 'decimal:2',
        'due_date' => 'date',
        'payment_date' => 'date'
    ];

    protected $appends = ['is_overdue', 'days_overdue'];

    // Relationships
    public function sale()
    {
        return $this->belongsTo(Sale::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    // Accessors
    public function getIsOverdueAttribute()
    {
        if ($this->status === 'pending' || $this->status === 'partial') {
            $dueDateWithGrace = $this->due_date->addDays($this->grace_period_days);
            return now()->greaterThan($dueDateWithGrace);
        }
        return false;
    }

    public function getDaysOverdueAttribute()
    {
        if ($this->is_overdue) {
            $dueDateWithGrace = $this->due_date->addDays($this->grace_period_days);
            return now()->diffInDays($dueDateWithGrace);
        }
        return 0;
    }

    public function getLateFeeAmountAttribute()
    {
        if ($this->is_overdue) {
            $lateFeeRate = config('services.settings.late_fee_percentage', 2);
            return round(($this->amount * $lateFeeRate / 100) * $this->days_overdue, 2);
        }
        return 0;
    }

    // Methods
    public function markAsPaid($paymentDate = null)
    {
        $this->update([
            'status' => 'paid',
            'paid_amount' => $this->amount,
            'due_amount' => 0,
            'payment_date' => $paymentDate ?? now()
        ]);

        // Update sale payment status
        $this->sale->updatePaymentStatus();
    }

    public function addPayment($amount, $lateFee = 0)
    {
        $this->increment('paid_amount', $amount);
        $this->decrement('due_amount', $amount);
        
        if ($lateFee > 0) {
            $this->increment('late_fee', $lateFee);
        }

        // Update status
        if ($this->due_amount == 0) {
            $this->status = 'paid';
            $this->payment_date = now();
        } elseif ($this->paid_amount > 0) {
            $this->status = 'partial';
        }

        $this->save();

        // Update sale payment status
        $this->sale->updatePaymentStatus();
    }

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

    public function scopeOverdue($query)
    {
        return $query->where('status', 'pending')
            ->where('due_date', '<', now()->subDays($query->getModel()->grace_period_days ?? 7));
    }

    public function scopeDueThisMonth($query)
    {
        $startOfMonth = now()->startOfMonth();
        $endOfMonth = now()->endOfMonth();
        
        return $query->where('status', 'pending')
            ->whereBetween('due_date', [$startOfMonth, $endOfMonth]);
    }
}