<?php
require_once __DIR__ . '/BaseModel.php';

/**
 * Sale Installment Management Class
 */
class SaleInstallment extends BaseModel {
    protected $tableName = 'sale_installments';
    protected $tenantColumn = null;
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Get overdue installments
     */
    public function getOverdueInstallments($saleId = null) {
        $sql = "SELECT si.*, s.unit_id, s.buyer_id, u.unit_number, p.name as property_name,
                       b.first_name, b.last_name, b.email, b.phone 
                FROM sale_installments si 
                INNER JOIN unit_sales s ON si.sale_id = s.id 
                INNER JOIN units u ON s.unit_id = u.id 
                INNER JOIN properties p ON u.property_id = p.id 
                INNER JOIN users b ON s.buyer_id = b.id 
                WHERE si.status = 'pending' AND si.due_date < CURDATE()";
        
        $params = [];
        if ($saleId) {
            $sql .= " AND si.sale_id = ?";
            $params[] = $saleId;
        }
        
        $sql .= " ORDER BY si.due_date ASC";
        
        $result = $this->db->query($sql, $params);
        $installments = [];
        
        while ($row = $result->fetch_assoc()) {
            $installments[] = $row;
        }
        
        return $installments;
    }
    
    /**
     * Calculate penalty for overdue installment
     */
    public function calculatePenalty($installmentId) {
        $installment = $this->getById($installmentId);
        
        if (!$installment || $installment['status'] === 'paid') {
            return 0.00;
        }
        
        $dueDate = new DateTime($installment['due_date']);
        $today = new DateTime();
        
        if ($today <= $dueDate) {
            return 0.00;
        }
        
        $daysOverdue = $today->diff($dueDate)->days;
        $penaltyRate = $installment['penalty_rate'] ?? 0.00;
        
        if ($penaltyRate > 0) {
            $penalty = ($installment['amount'] * $penaltyRate / 100) * $daysOverdue;
            return round($penalty, 2);
        }
        
        return 0.00;
    }
}
?>
