<?php
/**
 * Mortgage Calculator Widget for Havenlytics
 *
 * @package HvnlyNab\Database\Custom_Widgets\All_Widgets
 * @since 2.0.0
 */

namespace HvnlyNab\Database\Custom_Widgets\All_Widgets;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class Hvnly_Mortgage_Calculator_Widget
 * 
 * Enhanced mortgage calculator widget with advanced options
 * Fully sanitized following WordPress.org standards
 */
class Hvnly_Mortgage_Calculator_Widget extends \WP_Widget {

    /**
     * Constructor
     */
    public function __construct() {
        $widget_ops = array(
            'classname' => 'hvnly-property-single__widget hvnly-property-single__widget--mortgage',
            'description' => __('Display an advanced mortgage calculator for properties.', 'havenlytics'),
            'customize_selective_refresh' => true,
        );
        
        parent::__construct(
            'hvnly_mortgage_calculator',
            __('Havenlytics: Mortgage Calculator', 'havenlytics'),
            $widget_ops
        );
    }

    /**
     * Get currency settings from helper class
     *
     * @return array
     */
    private function get_currency_settings() {
        $currency_settings = HVNLY_NAB()->Helper->get_currency_settings();
        
        return array(
            'currency_code' => $currency_settings['hvnly_currencyType'] ?? 'USD',
            'currency_symbol' => HVNLY_NAB()->Helper->get_current_currency_symbol(),
            'currency_position' => $currency_settings['hvnly_currencyPositionType'] ?? 'LEFT',
            'thousand_separator' => $currency_settings['hvnly_thousandSeparator'] ?? ',',
            'decimal_separator' => $currency_settings['hvnly_decimalSeparator'] ?? '.',
            'number_of_decimals' => intval($currency_settings['hvnly_numberOfDecimals'] ?? 0),
            'enable_large_format' => $currency_settings['hvnly_EnabledCurrencyFormat'] ?? true,
            'thousand_text' => $currency_settings['hvnly_thousandText'] ?? 'K',
            'million_text' => $currency_settings['hvnly_millionText'] ?? 'M',
            'billion_text' => $currency_settings['hvnly_billionText'] ?? 'B',
        );
    }

    /**
     * Format price using helper class
     *
     * @param float $price
     * @return string
     */
    private function format_price($price) {
        return HVNLY_NAB()->Helper->format_price($price);
    }

    /**
     * Extract numeric value from formatted price
     *
     * @param string $formatted_price
     * @return float
     */
    private function extract_numeric_price($formatted_price) {
        // Remove currency symbol and any non-numeric characters except decimal points and commas
        $cleaned = preg_replace('/[^0-9.,]/', '', $formatted_price);
        
        // Handle different decimal separators
        if (strpos($cleaned, ',') !== false && strpos($cleaned, '.') !== false) {
            // Format like 1,450,000.00 or 1.450.000,00
            if (strpos($cleaned, ',') > strpos($cleaned, '.')) {
                // European format: 1.450.000,00
                $cleaned = str_replace('.', '', $cleaned);
                $cleaned = str_replace(',', '.', $cleaned);
            } else {
                // US format: 1,450,000.00
                $cleaned = str_replace(',', '', $cleaned);
            }
        } elseif (strpos($cleaned, ',') !== false) {
            // Could be US format with commas only or European format with commas as decimals
            if (preg_match('/,\d{2}$/', $cleaned)) {
                // Commas at the end likely are decimal separators
                $cleaned = str_replace(',', '.', $cleaned);
            } else {
                // Commas are thousand separators
                $cleaned = str_replace(',', '', $cleaned);
            }
        }
        
        return floatval($cleaned);
    }

    /**
     * Widget frontend display
     *
     * @param array $args Widget arguments
     * @param array $instance Widget instance
     */
    public function widget($args, $instance) {
        // Only show on single property pages
        if (!is_singular('hvnly_property')) {
            return;
        }

        // Sanitize and validate instance values
        $instance = $this->sanitize_instance($instance);
        
        // Get instance values with defaults
        $title = !empty($instance['title']) ? $instance['title'] : __('Mortgage Calculator', 'havenlytics');
        $default_interest_rate = isset($instance['default_interest_rate']) ? floatval($instance['default_interest_rate']) : 4.5;
        $show_advanced = !empty($instance['show_advanced']);
        $default_term = !empty($instance['default_term']) ? absint($instance['default_term']) : 30;
        $default_down_payment_percent = !empty($instance['default_down_payment_percent']) ? absint($instance['default_down_payment_percent']) : 10;
        
        // Additional field visibility settings
        $show_property_tax = !empty($instance['show_property_tax']);
        $show_home_insurance = !empty($instance['show_home_insurance']);
        $show_hoa_fees = !empty($instance['show_hoa_fees']);
        $show_pmi = !empty($instance['show_pmi']);
        $show_closing_costs = !empty($instance['show_closing_costs']);
        $show_amortization = !empty($instance['show_amortization']);
        $show_currency_selector = !empty($instance['show_currency_selector']);
        
        // Get property price using helper class
        $property_id = get_the_ID();
        $price_value = get_post_meta($property_id, '_hvnly_property_price', true);
        
        // Get currency settings from helper class
        $currency_settings = $this->get_currency_settings();
        $currency_symbol = $currency_settings['currency_symbol'];
        $currency_position = strtolower($currency_settings['currency_position']);
        
        // Get formatted price
        $formatted_price = $this->format_price($price_value);
        
        // Extract numeric price for calculations
        $numeric_price = HVNLY_NAB()->Helper->safe_price_to_float($price_value);
        
        // Calculate default down payment
        $default_down_payment = $numeric_price * ($default_down_payment_percent / 100);
        
        // Calculate default tax (1% of property price as estimate) - only if field is enabled
        $default_tax = $show_property_tax ? $numeric_price * 0.01 : 0;
        
        // Default insurance (0.35% of property price) - only if field is enabled
        $default_insurance = $show_home_insurance ? $numeric_price * 0.0035 : 0;
        
        // Default HOA fees - only if field is enabled
        $default_hoa = 0;
        
        // Default PMI rate (0.5% of loan amount if down payment < 20%) - only if field is enabled
        $default_pmi_rate = 0.5;
        
        // Default closing costs (3% of loan amount) - only if field is enabled
        $default_closing_costs = $show_closing_costs ? $numeric_price * 0.03 : 0;

        // Security: Escape all output
        echo wp_kses_post($args['before_widget']);
        
        // Widget title with escaping
        $widget_title = esc_html($title);
        echo wp_kses_post($args['before_title'] . $widget_title . $args['after_title']);
        ?>
        
        <!-- Currency Display (if enabled) -->
        <?php if ($show_currency_selector) : ?>
        <div class="hvnly-mortgage-currency-selector" style="margin-bottom: var(--hvnly-space-md);">
            <label for="<?php echo esc_attr($this->get_field_id('currency')); ?>" style="display: block; margin-bottom: var(--hvnly-space-xs); font-size: var(--hvnly-font-size-sm);">
                <?php esc_html_e('Currency:', 'havenlytics'); ?>
            </label>
            <select class="hvnly-property-single__form-input hvnly-mortgage-currency-select" 
                    id="hvnlyCurrency_<?php echo esc_attr($this->id); ?>" 
                    data-widget-id="<?php echo esc_attr($this->id); ?>">
                <option value="<?php echo esc_attr($currency_symbol); ?>" selected>
                    <?php echo esc_html($currency_settings['currency_code'] . ' (' . $currency_symbol . ')'); ?>
                </option>
            </select>
            <small><?php esc_html_e('Currency is synchronized with global settings', 'havenlytics'); ?></small>
        </div>
        <?php endif; ?>

        <!-- Price Display (Auto-filled from property) -->
        <div class="hvnly-mortgage-price-display">
            <span class="hvnly-mortgage-price-label"><?php esc_html_e('Property Price', 'havenlytics'); ?></span>
            <span class="hvnly-mortgage-price-value" id="hvnlyPropertyPrice_<?php echo esc_attr($this->id); ?>" 
                  data-currency="<?php echo esc_attr($currency_symbol); ?>"
                  data-position="<?php echo esc_attr($currency_position); ?>">
                <?php echo wp_kses_post($formatted_price); ?>
            </span>
        </div>
        
        <!-- Down Payment with Percentage Toggle -->
        <div class="hvnly-mortgage-downpayment">
            <div class="hvnly-mortgage-downpayment-header">
                <span><?php esc_html_e('Down Payment', 'havenlytics'); ?></span>
                <span class="hvnly-mortgage-downpayment-percent" id="hvnlyDownPaymentPercent_<?php echo esc_attr($this->id); ?>">
                    <?php echo absint($default_down_payment_percent); ?>%
                </span>
            </div>
            <div class="hvnly-mortgage-downpayment-inputs">
                <div class="hvnly-mortgage-amount-input">
                    <span class="currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                    <input type="number" 
                           class="hvnly-property-single__form-input" 
                           id="hvnlyDownPaymentAmount_<?php echo esc_attr($this->id); ?>" 
                           value="<?php echo esc_attr(round($default_down_payment)); ?>" 
                           step="1000" 
                           min="0"
                           data-widget-id="<?php echo esc_attr($this->id); ?>">
                </div>
                <div class="hvnly-mortgage-slider-input">
                    <input type="range" 
                           id="hvnlyDownPaymentSlider_<?php echo esc_attr($this->id); ?>" 
                           min="0" 
                           max="50" 
                           value="<?php echo esc_attr($default_down_payment_percent); ?>" 
                           step="1"
                           data-widget-id="<?php echo esc_attr($this->id); ?>">
                </div>
            </div>
        </div>
        
        <!-- Loan Term with Visual Buttons -->
        <div class="hvnly-mortgage-term-section">
            <span class="hvnly-mortgage-term-label"><?php esc_html_e('Loan Term', 'havenlytics'); ?></span>
            <div class="hvnly-mortgage-term-buttons">
                <button type="button" class="hvnly-mortgage-term-btn <?php echo $default_term === 30 ? 'active' : ''; ?>" 
                        data-term="30" data-widget-id="<?php echo esc_attr($this->id); ?>">
                    <?php esc_html_e('30 yrs', 'havenlytics'); ?>
                </button>
                <button type="button" class="hvnly-mortgage-term-btn <?php echo $default_term === 20 ? 'active' : ''; ?>" 
                        data-term="20" data-widget-id="<?php echo esc_attr($this->id); ?>">
                    <?php esc_html_e('20 yrs', 'havenlytics'); ?>
                </button>
                <button type="button" class="hvnly-mortgage-term-btn <?php echo $default_term === 15 ? 'active' : ''; ?>" 
                        data-term="15" data-widget-id="<?php echo esc_attr($this->id); ?>">
                    <?php esc_html_e('15 yrs', 'havenlytics'); ?>
                </button>
                <button type="button" class="hvnly-mortgage-term-btn <?php echo $default_term === 10 ? 'active' : ''; ?>" 
                        data-term="10" data-widget-id="<?php echo esc_attr($this->id); ?>">
                    <?php esc_html_e('10 yrs', 'havenlytics'); ?>
                </button>
            </div>
        </div>
        
        <!-- Interest Rate -->
        <div class="hvnly-mortgage-interest">
            <div class="hvnly-mortgage-interest-header">
                <span><?php esc_html_e('Interest Rate', 'havenlytics'); ?></span>
                <span class="hvnly-mortgage-market-rate"><?php esc_html_e('Market Rate', 'havenlytics'); ?></span>
            </div>
            <div class="hvnly-mortgage-interest-input">
                <input type="number" 
                       class="hvnly-property-single__form-input" 
                       id="hvnlyInterestRate_<?php echo esc_attr($this->id); ?>" 
                       value="<?php echo esc_attr($default_interest_rate); ?>" 
                       step="0.125" 
                       min="0.1" 
                       max="15"
                       data-widget-id="<?php echo esc_attr($this->id); ?>">
                <span class="percent-symbol">%</span>
            </div>
        </div>
        
        <!-- Advanced Options Toggle (only if any advanced fields are enabled) -->
        <?php if ($show_advanced && ($show_property_tax || $show_home_insurance || $show_hoa_fees || $show_pmi || $show_closing_costs)) : ?>
        <button type="button" class="hvnly-mortgage-advanced-toggle" id="hvnlyToggleAdvanced_<?php echo esc_attr($this->id); ?>" data-widget-id="<?php echo esc_attr($this->id); ?>">
            <svg class="hvnly-icon hvnly-icon-sm" id="hvnlyAdvancedIcon_<?php echo esc_attr($this->id); ?>">
                <use xlink:href="#hvnly-chevron-right"></use>
            </svg>
            <?php esc_html_e('Advanced Options', 'havenlytics'); ?>
        </button>
        
        <!-- Advanced Options Panel -->
        <div class="hvnly-mortgage-advanced-panel" id="hvnlyAdvancedPanel_<?php echo esc_attr($this->id); ?>">
            <?php if ($show_property_tax) : ?>
            <!-- Property Tax -->
            <div class="hvnly-property-single__form-group" style="margin-bottom: var(--hvnly-space-md);">
                <label class="hvnly-mortgage-field-label">
                    <?php esc_html_e('Annual Property Tax', 'havenlytics'); ?>
                </label>
                <div class="hvnly-mortgage-input-with-symbol">
                    <span class="currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                    <input type="number" 
                           class="hvnly-property-single__form-input hvnly-mortgage-input-with-padding" 
                           id="hvnlyPropertyTax_<?php echo esc_attr($this->id); ?>" 
                           value="<?php echo esc_attr(round($default_tax)); ?>" 
                           step="500" 
                           min="0"
                           data-widget-id="<?php echo esc_attr($this->id); ?>">
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($show_home_insurance) : ?>
            <!-- Home Insurance -->
            <div class="hvnly-property-single__form-group" style="margin-bottom: var(--hvnly-space-md);">
                <label class="hvnly-mortgage-field-label">
                    <?php esc_html_e('Annual Home Insurance', 'havenlytics'); ?>
                </label>
                <div class="hvnly-mortgage-input-with-symbol">
                    <span class="currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                    <input type="number" 
                           class="hvnly-property-single__form-input hvnly-mortgage-input-with-padding" 
                           id="hvnlyHomeInsurance_<?php echo esc_attr($this->id); ?>" 
                           value="<?php echo esc_attr(round($default_insurance)); ?>" 
                           step="100" 
                           min="0"
                           data-widget-id="<?php echo esc_attr($this->id); ?>">
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($show_hoa_fees) : ?>
            <!-- HOA Fees -->
            <div class="hvnly-property-single__form-group" style="margin-bottom: var(--hvnly-space-md);">
                <label class="hvnly-mortgage-field-label">
                    <?php esc_html_e('Monthly HOA Fees', 'havenlytics'); ?>
                </label>
                <div class="hvnly-mortgage-input-with-symbol">
                    <span class="currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                    <input type="number" 
                           class="hvnly-property-single__form-input hvnly-mortgage-input-with-padding" 
                           id="hvnlyHOA_<?php echo esc_attr($this->id); ?>" 
                           value="<?php echo esc_attr($default_hoa); ?>" 
                           step="50" 
                           min="0"
                           data-widget-id="<?php echo esc_attr($this->id); ?>">
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($show_pmi) : ?>
            <!-- PMI (Private Mortgage Insurance) -->
            <div class="hvnly-property-single__form-group" style="margin-bottom: var(--hvnly-space-md);">
                <label class="hvnly-mortgage-field-label">
                    <?php esc_html_e('PMI Rate (%)', 'havenlytics'); ?>
                    <span class="hvnly-mortgage-field-note"><?php esc_html_e('(if down payment < 20%)', 'havenlytics'); ?></span>
                </label>
                <input type="number" 
                       class="hvnly-property-single__form-input" 
                       id="hvnlyPMIRate_<?php echo esc_attr($this->id); ?>" 
                       value="<?php echo esc_attr($default_pmi_rate); ?>" 
                       step="0.1" 
                       min="0" 
                       max="5"
                       data-widget-id="<?php echo esc_attr($this->id); ?>">
                <span class="hvnly-input-suffix">%</span>
            </div>
            <?php endif; ?>
            
            <?php if ($show_closing_costs) : ?>
            <!-- Closing Costs -->
            <div class="hvnly-property-single__form-group" style="margin-bottom: var(--hvnly-space-md);">
                <label class="hvnly-mortgage-field-label">
                    <?php esc_html_e('Estimated Closing Costs', 'havenlytics'); ?>
                </label>
                <div class="hvnly-mortgage-input-with-symbol">
                    <span class="currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                    <input type="number" 
                           class="hvnly-property-single__form-input hvnly-mortgage-input-with-padding" 
                           id="hvnlyClosingCosts_<?php echo esc_attr($this->id); ?>" 
                           value="<?php echo esc_attr(round($default_closing_costs)); ?>" 
                           step="1000" 
                           min="0"
                           data-widget-id="<?php echo esc_attr($this->id); ?>">
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <!-- Results Section -->
        <div class="hvnly-property-single__mortgage-result">
            <div class="hvnly-mortgage-result-header">
                <span class="hvnly-mortgage-result-label"><?php esc_html_e('Monthly Payment', 'havenlytics'); ?></span>
                <span class="hvnly-property-single__mortgage-amount" id="hvnlyMonthlyPayment_<?php echo esc_attr($this->id); ?>">
                    <?php echo esc_html($currency_symbol); ?>0
                </span>
            </div>
            
            <!-- Detailed Breakdown -->
            <div class="hvnly-mortgage-breakdown">
                <div class="hvnly-mortgage-breakdown-item">
                    <span><?php esc_html_e('Principal & Interest', 'havenlytics'); ?></span>
                    <span id="hvnlyPrincipalInterest_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                
                <?php if ($show_property_tax) : ?>
                <div class="hvnly-mortgage-breakdown-item">
                    <span><?php esc_html_e('Property Tax', 'havenlytics'); ?></span>
                    <span id="hvnlyMonthlyTax_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                <?php endif; ?>
                
                <?php if ($show_home_insurance) : ?>
                <div class="hvnly-mortgage-breakdown-item">
                    <span><?php esc_html_e('Home Insurance', 'havenlytics'); ?></span>
                    <span id="hvnlyMonthlyInsurance_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                <?php endif; ?>
                
                <?php if ($show_hoa_fees) : ?>
                <div class="hvnly-mortgage-breakdown-item">
                    <span><?php esc_html_e('HOA Fees', 'havenlytics'); ?></span>
                    <span id="hvnlyMonthlyHOA_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                <?php endif; ?>
                
                <?php if ($show_pmi) : ?>
                <div class="hvnly-mortgage-breakdown-item">
                    <span><?php esc_html_e('PMI', 'havenlytics'); ?></span>
                    <span id="hvnlyMonthlyPMI_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Loan Summary -->
            <div class="hvnly-mortgage-summary">
                <div class="hvnly-mortgage-summary-item">
                    <span><?php esc_html_e('Loan Amount:', 'havenlytics'); ?></span>
                    <span id="hvnlyLoanAmount_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                <div class="hvnly-mortgage-summary-item">
                    <span><?php esc_html_e('Down Payment:', 'havenlytics'); ?></span>
                    <span id="hvnlyDisplayDownPayment_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0 (0%)</span>
                </div>
                <div class="hvnly-mortgage-summary-item">
                    <span><?php esc_html_e('Total Interest:', 'havenlytics'); ?></span>
                    <span id="hvnlyTotalInterest_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
                <div class="hvnly-mortgage-summary-item">
                    <span><?php esc_html_e('Total Payments:', 'havenlytics'); ?></span>
                    <span id="hvnlyTotalPayments_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
            </div>
            
            <?php if ($show_closing_costs) : ?>
            <!-- Closing Costs Summary -->
            <div class="hvnly-mortgage-closing-costs">
                <div class="hvnly-mortgage-summary-item">
                    <span><?php esc_html_e('Est. Closing Costs:', 'havenlytics'); ?></span>
                    <span id="hvnlyClosingCostsDisplay_<?php echo esc_attr($this->id); ?>"><?php echo esc_html($currency_symbol); ?>0</span>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Amortization Schedule (if enabled) -->
        <?php if ($show_amortization) : ?>
        <div class="hvnly-mortgage-amortization" style="margin-top: var(--hvnly-space-lg);">
            <button type="button" class="hvnly-mortgage-amortization-toggle" id="hvnlyAmortizationToggle_<?php echo esc_attr($this->id); ?>" data-widget-id="<?php echo esc_attr($this->id); ?>">
                <svg class="hvnly-icon hvnly-icon-sm"><use xlink:href="#hvnly-chevron-right"></use></svg>
                <?php esc_html_e('View Amortization Schedule', 'havenlytics'); ?>
            </button>
            <div class="hvnly-mortgage-amortization-panel" id="hvnlyAmortizationPanel_<?php echo esc_attr($this->id); ?>" style="display: none;">
                <div class="hvnly-mortgage-amortization-table-container">
                    <table class="hvnly-mortgage-amortization-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Year', 'havenlytics'); ?></th>
                                <th><?php esc_html_e('Principal Paid', 'havenlytics'); ?></th>
                                <th><?php esc_html_e('Interest Paid', 'havenlytics'); ?></th>
                                <th><?php esc_html_e('Balance', 'havenlytics'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="hvnlyAmortizationTable_<?php echo esc_attr($this->id); ?>">
                            <!-- Populated by JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Market Note -->
        <p class="hvnly-mortgage-note">
            *<?php esc_html_e('Estimated payment for informational purposes only. Actual rates may vary.', 'havenlytics'); ?>
        </p>

        <!-- JavaScript for calculator (sanitized and escaped) -->
        <script>
        (function($) {
            'use strict';
            
            $(document).ready(function() {
                // Initialize calculator for this widget instance
                if (typeof window.HvnlyMortgageCalculator === 'undefined') {
                    window.HvnlyMortgageCalculator = {};
                }
                
                var widgetId = <?php echo wp_json_encode($this->id); ?>;
                var propertyPrice = <?php echo wp_json_encode($numeric_price); ?>;
                var defaultDownPercent = <?php echo wp_json_encode($default_down_payment_percent); ?>;
                var defaultInterest = <?php echo wp_json_encode($default_interest_rate); ?>;
                var defaultTerm = <?php echo wp_json_encode($default_term); ?>;
                var currencySymbol = <?php echo wp_json_encode($currency_symbol); ?>;
                var currencyPosition = <?php echo wp_json_encode($currency_position); ?>;
                var showPropertyTax = <?php echo wp_json_encode($show_property_tax); ?>;
                var showHomeInsurance = <?php echo wp_json_encode($show_home_insurance); ?>;
                var showHoaFees = <?php echo wp_json_encode($show_hoa_fees); ?>;
                var showPmi = <?php echo wp_json_encode($show_pmi); ?>;
                var showClosingCosts = <?php echo wp_json_encode($show_closing_costs); ?>;
                var showAmortization = <?php echo wp_json_encode($show_amortization); ?>;
                
                // Store widget instance
                window.HvnlyMortgageCalculator[widgetId] = new HvnlyMortgageCalculatorInstance(
                    widgetId, propertyPrice, defaultDownPercent, defaultInterest, defaultTerm,
                    currencySymbol, currencyPosition, showPropertyTax, showHomeInsurance,
                    showHoaFees, showPmi, showClosingCosts, showAmortization
                );
            });
            
            /**
             * Mortgage Calculator Instance Class
             */
            class HvnlyMortgageCalculatorInstance {
                constructor(widgetId, propertyPrice, defaultDownPercent, defaultInterest, defaultTerm,
                            currencySymbol, currencyPosition, showPropertyTax, showHomeInsurance,
                            showHoaFees, showPmi, showClosingCosts, showAmortization) {
                    
                    this.widgetId = widgetId;
                    this.propertyPrice = parseFloat(propertyPrice) || 0;
                    this.currencySymbol = currencySymbol || '$';
                    this.currencyPosition = currencyPosition || 'left';
                    this.showPropertyTax = showPropertyTax;
                    this.showHomeInsurance = showHomeInsurance;
                    this.showHoaFees = showHoaFees;
                    this.showPmi = showPmi;
                    this.showClosingCosts = showClosingCosts;
                    this.showAmortization = showAmortization;
                    
                    // DOM Elements
                    this.downAmount = document.getElementById('hvnlyDownPaymentAmount_' + widgetId);
                    this.downSlider = document.getElementById('hvnlyDownPaymentSlider_' + widgetId);
                    this.downPercent = document.getElementById('hvnlyDownPaymentPercent_' + widgetId);
                    this.interestRate = document.getElementById('hvnlyInterestRate_' + widgetId);
                    this.termBtns = document.querySelectorAll('.hvnly-mortgage-term-btn[data-widget-id="' + widgetId + '"]');
                    
                    // Results elements
                    this.monthlyPayment = document.getElementById('hvnlyMonthlyPayment_' + widgetId);
                    this.principalInterest = document.getElementById('hvnlyPrincipalInterest_' + widgetId);
                    this.monthlyTax = document.getElementById('hvnlyMonthlyTax_' + widgetId);
                    this.monthlyInsurance = document.getElementById('hvnlyMonthlyInsurance_' + widgetId);
                    this.monthlyHOA = document.getElementById('hvnlyMonthlyHOA_' + widgetId);
                    this.monthlyPMI = document.getElementById('hvnlyMonthlyPMI_' + widgetId);
                    this.loanAmount = document.getElementById('hvnlyLoanAmount_' + widgetId);
                    this.displayDownPayment = document.getElementById('hvnlyDisplayDownPayment_' + widgetId);
                    this.totalInterest = document.getElementById('hvnlyTotalInterest_' + widgetId);
                    this.totalPayments = document.getElementById('hvnlyTotalPayments_' + widgetId);
                    this.closingCostsDisplay = document.getElementById('hvnlyClosingCostsDisplay_' + widgetId);
                    this.amortizationTable = document.getElementById('hvnlyAmortizationTable_' + widgetId);
                    
                    // Advanced options
                    this.propertyTax = document.getElementById('hvnlyPropertyTax_' + widgetId);
                    this.homeInsurance = document.getElementById('hvnlyHomeInsurance_' + widgetId);
                    this.hoaFees = document.getElementById('hvnlyHOA_' + widgetId);
                    this.pmiRate = document.getElementById('hvnlyPMIRate_' + widgetId);
                    this.closingCosts = document.getElementById('hvnlyClosingCosts_' + widgetId);
                    this.toggleBtn = document.getElementById('hvnlyToggleAdvanced_' + widgetId);
                    this.advancedPanel = document.getElementById('hvnlyAdvancedPanel_' + widgetId);
                    
                    // Amortization elements
                    this.amortizationToggle = document.getElementById('hvnlyAmortizationToggle_' + widgetId);
                    this.amortizationPanel = document.getElementById('hvnlyAmortizationPanel_' + widgetId);
                    
                    // Currency selector
                    this.currencySelect = document.getElementById('hvnlyCurrency_' + widgetId);
                    
                    // Current values
                    this.currentDownPayment = this.propertyPrice * (defaultDownPercent / 100);
                    this.currentDownPercent = defaultDownPercent;
                    this.currentInterestRate = defaultInterest;
                    this.currentTerm = defaultTerm;
                    
                    // Advanced values
                    this.currentPropertyTax = this.showPropertyTax ? (this.propertyPrice * 0.01) : 0;
                    this.currentHomeInsurance = this.showHomeInsurance ? (this.propertyPrice * 0.0035) : 0;
                    this.currentHoaFees = 0;
                    this.currentPmiRate = 0.5;
                    this.currentClosingCosts = this.showClosingCosts ? (this.propertyPrice * 0.03) : 0;
                    
                    // Initialize
                    this.bindEvents();
                    this.initAdvancedToggle();
                    this.initAmortizationToggle();
                    this.initCurrencySelector();
                    this.calculate();
                }
                
                bindEvents() {
                    // Down payment amount input
                    if (this.downAmount) {
                        this.downAmount.addEventListener('input', (e) => {
                            let value = parseFloat(e.target.value) || 0;
                            value = Math.min(value, this.propertyPrice);
                            this.currentDownPayment = value;
                            this.currentDownPercent = ((this.currentDownPayment / this.propertyPrice) * 100).toFixed(1);
                            if (this.downPercent) this.downPercent.textContent = this.currentDownPercent + '%';
                            if (this.downSlider) this.downSlider.value = this.currentDownPercent;
                            this.calculate();
                        });
                    }
                    
                    // Down payment slider
                    if (this.downSlider) {
                        this.downSlider.addEventListener('input', (e) => {
                            this.currentDownPercent = parseFloat(e.target.value);
                            this.currentDownPayment = (this.propertyPrice * (this.currentDownPercent / 100)).toFixed(0);
                            if (this.downPercent) this.downPercent.textContent = this.currentDownPercent + '%';
                            if (this.downAmount) this.downAmount.value = this.currentDownPayment;
                            this.calculate();
                        });
                    }
                    
                    // Loan term buttons
                    this.termBtns.forEach(btn => {
                        btn.addEventListener('click', (e) => {
                            this.termBtns.forEach(b => b.classList.remove('active'));
                            e.target.classList.add('active');
                            this.currentTerm = parseInt(e.target.dataset.term);
                            this.calculate();
                        });
                    });
                    
                    // Interest rate
                    if (this.interestRate) {
                        this.interestRate.addEventListener('input', (e) => {
                            this.currentInterestRate = parseFloat(e.target.value) || 4.5;
                            this.calculate();
                        });
                    }
                    
                    // Advanced inputs
                    if (this.propertyTax) {
                        this.propertyTax.addEventListener('input', (e) => {
                            this.currentPropertyTax = parseFloat(e.target.value) || 0;
                            this.calculate();
                        });
                    }
                    
                    if (this.homeInsurance) {
                        this.homeInsurance.addEventListener('input', (e) => {
                            this.currentHomeInsurance = parseFloat(e.target.value) || 0;
                            this.calculate();
                        });
                    }
                    
                    if (this.hoaFees) {
                        this.hoaFees.addEventListener('input', (e) => {
                            this.currentHoaFees = parseFloat(e.target.value) || 0;
                            this.calculate();
                        });
                    }
                    
                    if (this.pmiRate) {
                        this.pmiRate.addEventListener('input', (e) => {
                            this.currentPmiRate = parseFloat(e.target.value) || 0;
                            this.calculate();
                        });
                    }
                    
                    if (this.closingCosts) {
                        this.closingCosts.addEventListener('input', (e) => {
                            this.currentClosingCosts = parseFloat(e.target.value) || 0;
                            this.calculate();
                        });
                    }
                }
                
                initAdvancedToggle() {
                    if (this.toggleBtn && this.advancedPanel) {
                        this.toggleBtn.addEventListener('click', () => {
                            this.advancedPanel.classList.toggle('show');
                            this.toggleBtn.classList.toggle('active');
                            
                            const icon = this.toggleBtn.querySelector('svg use');
                            if (icon) {
                                const href = this.advancedPanel.classList.contains('show') ? '#hvnly-chevron-down' : '#hvnly-chevron-right';
                                icon.setAttribute('xlink:href', href);
                            }
                        });
                    }
                }
                
                initAmortizationToggle() {
                    if (this.amortizationToggle && this.amortizationPanel) {
                        this.amortizationToggle.addEventListener('click', () => {
                            const isVisible = this.amortizationPanel.style.display !== 'none';
                            this.amortizationPanel.style.display = isVisible ? 'none' : 'block';
                            
                            const icon = this.amortizationToggle.querySelector('svg use');
                            if (icon) {
                                const href = isVisible ? '#hvnly-chevron-right' : '#hvnly-chevron-down';
                                icon.setAttribute('xlink:href', href);
                            }
                            
                            if (!isVisible) {
                                this.updateAmortizationSchedule();
                            }
                        });
                    }
                }
                
                initCurrencySelector() {
                    if (this.currencySelect) {
                        this.currencySelect.addEventListener('change', (e) => {
                            this.currencySymbol = e.target.value;
                            this.updateCurrencyDisplay();
                        });
                    }
                }
                
                calculate() {
                    // Calculate loan amount
                    const loanAmount = this.propertyPrice - this.currentDownPayment;
                    
                    // Monthly principal & interest
                    const monthlyRate = this.currentInterestRate / 100 / 12;
                    const payments = this.currentTerm * 12;
                    
                    let monthlyPI = 0;
                    if (monthlyRate > 0 && loanAmount > 0) {
                        const factor = Math.pow(1 + monthlyRate, payments);
                        monthlyPI = loanAmount * monthlyRate * factor / (factor - 1);
                    } else if (loanAmount > 0) {
                        monthlyPI = loanAmount / payments;
                    }
                    
                    // Calculate total interest
                    const totalPayments = monthlyPI * payments;
                    const totalInterest = totalPayments - loanAmount;
                    
                    // Monthly tax, insurance, HOA
                    const monthlyTax = this.currentPropertyTax / 12;
                    const monthlyInsurance = this.currentHomeInsurance / 12;
                    const monthlyHOA = this.currentHoaFees;
                    
                    // Calculate PMI if down payment < 20%
                    let monthlyPMI = 0;
                    if (this.showPmi && this.currentDownPercent < 20) {
                        const pmiRateDecimal = this.currentPmiRate / 100 / 12;
                        monthlyPMI = loanAmount * pmiRateDecimal;
                    }
                    
                    // Total monthly payment
                    const totalMonthly = monthlyPI + monthlyTax + monthlyInsurance + monthlyHOA + monthlyPMI;
                    
                    // Update UI
                    this.updateDisplay({
                        monthlyPI,
                        monthlyTax,
                        monthlyInsurance,
                        monthlyHOA,
                        monthlyPMI,
                        totalMonthly,
                        loanAmount,
                        totalInterest,
                        totalPayments,
                        downPayment: this.currentDownPayment,
                        downPercent: this.currentDownPercent
                    });
                }
                
                updateDisplay(values) {
                    const formatCurrency = (val) => {
                        const rounded = Math.round(val);
                        if (this.currencyPosition === 'left') {
                            return this.currencySymbol + rounded.toLocaleString();
                        } else {
                            return rounded.toLocaleString() + this.currencySymbol;
                        }
                    };
                    
                    // Main monthly payment
                    if (this.monthlyPayment) this.monthlyPayment.textContent = formatCurrency(values.totalMonthly);
                    
                    // Breakdown
                    if (this.principalInterest) this.principalInterest.textContent = formatCurrency(values.monthlyPI);
                    if (this.monthlyTax) this.monthlyTax.textContent = formatCurrency(values.monthlyTax);
                    if (this.monthlyInsurance) this.monthlyInsurance.textContent = formatCurrency(values.monthlyInsurance);
                    if (this.monthlyHOA) this.monthlyHOA.textContent = formatCurrency(values.monthlyHOA);
                    if (this.monthlyPMI) this.monthlyPMI.textContent = formatCurrency(values.monthlyPMI);
                    
                    // Loan summary
                    if (this.loanAmount) this.loanAmount.textContent = formatCurrency(values.loanAmount);
                    
                    if (this.displayDownPayment) {
                        this.displayDownPayment.textContent = formatCurrency(values.downPayment) + ` (${values.downPercent}%)`;
                    }
                    
                    if (this.totalInterest) this.totalInterest.textContent = formatCurrency(values.totalInterest);
                    
                    if (this.totalPayments) this.totalPayments.textContent = formatCurrency(values.totalPayments);
                    
                    if (this.closingCostsDisplay && this.showClosingCosts) {
                        this.closingCostsDisplay.textContent = formatCurrency(this.currentClosingCosts);
                    }
                    
                    // Animate result
                    const resultEl = this.monthlyPayment?.closest('.hvnly-property-single__mortgage-result');
                    if (resultEl) {
                        resultEl.style.transform = 'scale(1.02)';
                        setTimeout(() => {
                            resultEl.style.transform = 'scale(1)';
                        }, 200);
                    }
                }
                
                updateAmortizationSchedule() {
                    if (!this.amortizationTable || !this.showAmortization) return;
                    
                    const loanAmount = this.propertyPrice - this.currentDownPayment;
                    const monthlyRate = this.currentInterestRate / 100 / 12;
                    const payments = this.currentTerm * 12;
                    
                    if (loanAmount <= 0 || monthlyRate <= 0) return;
                    
                    const monthlyPI = (loanAmount * monthlyRate * Math.pow(1 + monthlyRate, payments)) / 
                                      (Math.pow(1 + monthlyRate, payments) - 1);
                    
                    let balance = loanAmount;
                    let tableHtml = '';
                    
                    // Generate yearly summary
                    for (let year = 1; year <= this.currentTerm; year++) {
                        let yearlyPrincipal = 0;
                        let yearlyInterest = 0;
                        
                        for (let month = 1; month <= 12; month++) {
                            if (balance <= 0) break;
                            
                            const interestPayment = balance * monthlyRate;
                            const principalPayment = monthlyPI - interestPayment;
                            
                            yearlyPrincipal += principalPayment;
                            yearlyInterest += interestPayment;
                            balance -= principalPayment;
                            
                            if (balance < 0) balance = 0;
                        }
                        
                        tableHtml += `
                            <tr>
                                <td>${year}</td>
                                <td>${this.formatCurrency(yearlyPrincipal)}</td>
                                <td>${this.formatCurrency(yearlyInterest)}</td>
                                <td>${this.formatCurrency(balance)}</td>
                            </tr>
                        `;
                        
                        if (balance <= 0) break;
                    }
                    
                    this.amortizationTable.innerHTML = tableHtml;
                }
                
                formatCurrency(val) {
                    const rounded = Math.round(val);
                    if (this.currencyPosition === 'left') {
                        return this.currencySymbol + rounded.toLocaleString();
                    } else {
                        return rounded.toLocaleString() + this.currencySymbol;
                    }
                }
                
                updateCurrencyDisplay() {
                    // Update all displayed values with new currency
                    this.calculate();
                    
                    // Update currency symbols in input fields
                    document.querySelectorAll('.currency-symbol').forEach(el => {
                        el.textContent = this.currencySymbol;
                    });
                }
            }
            
        })(jQuery);
        </script>

        <style>
        /* Additional styles for enhanced calculator */
        .hvnly-mortgage-field-label {
            display: block;
            margin-bottom: var(--hvnly-space-xs);
            font-size: var(--hvnly-font-size-sm);
            color: var(--hvnly-text-primary);
            font-weight: var(--hvnly-font-weight-medium);
        }
        
        .hvnly-mortgage-field-note {
            font-size: var(--hvnly-font-size-xs);
            color: var(--hvnly-text-secondary);
            font-weight: var(--hvnly-font-weight-regular);
            margin-left: var(--hvnly-space-xs);
        }
        
        .hvnly-mortgage-input-with-symbol {
            position: relative;
        }
        
        .hvnly-mortgage-input-with-symbol .currency-symbol {
            position: absolute;
            left: 6px;
            top: 45%;
            transform: translateY(-50%);
            color: var(--hvnly-text-secondary);
            z-index: 1;
        }
        
        .hvnly-mortgage-input-with-padding {
            padding-left: calc(var(--hvnly-space-md) * 2 + 10px) !important;
        }
        
        .hvnly-mortgage-result-header {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-bottom: var(--hvnly-space-md);
        }
        
        .hvnly-mortgage-result-label {
            font-size: var(--hvnly-font-size-sm);
            opacity: 0.9;
        }
        
        .hvnly-mortgage-amortization-toggle {
            width: 100%;
            background: none;
            border: 1px solid var(--hvnly-border-color);
            border-radius: var(--hvnly-border-radius-sm);
            padding: var(--hvnly-space-md);
            display: flex;
            align-items: center;
            gap: var(--hvnly-space-sm);
            cursor: pointer;
            transition: all var(--hvnly-transition-time);
            color: var(--hvnly-text-primary);
        }
        
        .hvnly-mortgage-amortization-toggle:hover {
            background: rgba(108, 96, 254, 0.05);
            border-color: var(--hvnly-brand-primary);
        }
        
        .hvnly-mortgage-amortization-table-container {
            max-height: 300px;
            overflow-y: auto;
            margin-top: var(--hvnly-space-md);
            border: 1px solid var(--hvnly-border-color);
            border-radius: var(--hvnly-border-radius-sm);
        }
        
        .hvnly-mortgage-amortization-table {
            width: 100%;
            border-collapse: collapse;
            font-size: var(--hvnly-font-size-xs);
        }
        
        .hvnly-mortgage-amortization-table th {
            background: rgba(108, 96, 254, 0.05);
            padding: var(--hvnly-space-sm);
            text-align: left;
            font-weight: var(--hvnly-font-weight-semibold);
            position: sticky;
            top: 0;
            background: var(--hvnly-color-bg-white);
            border-bottom: 2px solid var(--hvnly-border-color);
        }
        
        .hvnly-mortgage-amortization-table td {
            padding: var(--hvnly-space-sm);
            border-bottom: 1px solid var(--hvnly-border-color);
        }
        
        .hvnly-mortgage-amortization-table tr:last-child td {
            border-bottom: none;
        }
        
        .hvnly-mortgage-amortization-table tr:hover td {
            background: rgba(108, 96, 254, 0.02);
        }
        
        .hvnly-input-suffix {
            position: absolute;
            right: var(--hvnly-space-md);
            top: 50%;
            transform: translateY(-50%);
            color: var(--hvnly-text-secondary);
        }
        </style>

        <?php
        echo wp_kses_post($args['after_widget']);
    }

    /**
     * Widget form (admin)
     *
     * @param array $instance Widget instance
     * @return void
     */
    public function form($instance) {
        // Sanitize and validate instance
        $instance = $this->sanitize_instance($instance);
        
        // Get values with defaults
        $title = isset($instance['title']) ? $instance['title'] : __('Mortgage Calculator', 'havenlytics');
        $default_interest_rate = isset($instance['default_interest_rate']) ? $instance['default_interest_rate'] : 4.5;
        $default_term = isset($instance['default_term']) ? $instance['default_term'] : 30;
        $default_down_payment_percent = isset($instance['default_down_payment_percent']) ? $instance['default_down_payment_percent'] : 10;
        
        // Checkbox values
        $show_advanced = !empty($instance['show_advanced']);
        $show_property_tax = !empty($instance['show_property_tax']);
        $show_home_insurance = !empty($instance['show_home_insurance']);
        $show_hoa_fees = !empty($instance['show_hoa_fees']);
        $show_pmi = !empty($instance['show_pmi']);
        $show_closing_costs = !empty($instance['show_closing_costs']);
        $show_amortization = !empty($instance['show_amortization']);
        $show_currency_selector = !empty($instance['show_currency_selector']);
        
        // Get current currency settings
        $currency_settings = $this->get_currency_settings();
        $current_currency = $currency_settings['currency_code'] . ' (' . $currency_settings['currency_symbol'] . ')';
        ?>

        <div class="hvnly-widget-fields">
            <p>
                <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
                    <?php esc_html_e('Title:', 'havenlytics'); ?>
                </label>
                <input type="text" 
                       class="widefat" 
                       id="<?php echo esc_attr($this->get_field_id('title')); ?>" 
                       name="<?php echo esc_attr($this->get_field_name('title')); ?>" 
                       value="<?php echo esc_attr($title); ?>">
            </p>

            <p>
                <label for="<?php echo esc_attr($this->get_field_id('default_interest_rate')); ?>">
                    <?php esc_html_e('Default Interest Rate (%):', 'havenlytics'); ?>
                </label>
                <input type="number" 
                       class="widefat" 
                       id="<?php echo esc_attr($this->get_field_id('default_interest_rate')); ?>" 
                       name="<?php echo esc_attr($this->get_field_name('default_interest_rate')); ?>" 
                       value="<?php echo esc_attr($default_interest_rate); ?>" 
                       step="0.125" 
                       min="0.1" 
                       max="15">
            </p>

            <p>
                <label for="<?php echo esc_attr($this->get_field_id('default_term')); ?>">
                    <?php esc_html_e('Default Loan Term (years):', 'havenlytics'); ?>
                </label>
                <select class="widefat" 
                        id="<?php echo esc_attr($this->get_field_id('default_term')); ?>" 
                        name="<?php echo esc_attr($this->get_field_name('default_term')); ?>">
                    <option value="30" <?php selected($default_term, 30); ?>><?php esc_html_e('30 years', 'havenlytics'); ?></option>
                    <option value="20" <?php selected($default_term, 20); ?>><?php esc_html_e('20 years', 'havenlytics'); ?></option>
                    <option value="15" <?php selected($default_term, 15); ?>><?php esc_html_e('15 years', 'havenlytics'); ?></option>
                    <option value="10" <?php selected($default_term, 10); ?>><?php esc_html_e('10 years', 'havenlytics'); ?></option>
                </select>
            </p>

            <p>
                <label for="<?php echo esc_attr($this->get_field_id('default_down_payment_percent')); ?>">
                    <?php esc_html_e('Default Down Payment (%):', 'havenlytics'); ?>
                </label>
                <input type="number" 
                       class="widefat" 
                       id="<?php echo esc_attr($this->get_field_id('default_down_payment_percent')); ?>" 
                       name="<?php echo esc_attr($this->get_field_name('default_down_payment_percent')); ?>" 
                       value="<?php echo esc_attr($default_down_payment_percent); ?>" 
                       min="0" 
                       max="50" 
                       step="1">
            </p>

            <p class="hvnly-widget-section-title" style="font-weight: 600; margin: 15px 0 5px; border-bottom: 1px solid #ddd; padding-bottom: 5px;">
                <?php esc_html_e('Currency Settings', 'havenlytics'); ?>
            </p>

            <p>
                <strong><?php esc_html_e('Current Currency:', 'havenlytics'); ?></strong> 
                <?php echo esc_html($current_currency); ?>
                <br>
                <small><?php esc_html_e('Currency settings are managed globally in Havenlytics Settings.', 'havenlytics'); ?></small>
            </p>

            <p>
                <input type="checkbox" 
                       class="checkbox" 
                       id="<?php echo esc_attr($this->get_field_id('show_currency_selector')); ?>" 
                       name="<?php echo esc_attr($this->get_field_name('show_currency_selector')); ?>" 
                       value="1" 
                       <?php checked($show_currency_selector); ?>>
                <label for="<?php echo esc_attr($this->get_field_id('show_currency_selector')); ?>">
                    <?php esc_html_e('Show currency info', 'havenlytics'); ?>
                </label>
                <br>
                <small><?php esc_html_e('Displays the current currency from global settings.', 'havenlytics'); ?></small>
            </p>

            <p class="hvnly-widget-section-title" style="font-weight: 600; margin: 15px 0 5px; border-bottom: 1px solid #ddd; padding-bottom: 5px;">
                <?php esc_html_e('Advanced Options', 'havenlytics'); ?>
            </p>

            <p>
                <input type="checkbox" 
                       class="checkbox" 
                       id="<?php echo esc_attr($this->get_field_id('show_advanced')); ?>" 
                       name="<?php echo esc_attr($this->get_field_name('show_advanced')); ?>" 
                       value="1" 
                       <?php checked($show_advanced); ?>>
                <label for="<?php echo esc_attr($this->get_field_id('show_advanced')); ?>">
                    <?php esc_html_e('Enable advanced options panel', 'havenlytics'); ?>
                </label>
            </p>

            <div class="hvnly-widget-subsection" style="margin-left: 20px;">
                <p>
                    <input type="checkbox" 
                           class="checkbox" 
                           id="<?php echo esc_attr($this->get_field_id('show_property_tax')); ?>" 
                           name="<?php echo esc_attr($this->get_field_name('show_property_tax')); ?>" 
                           value="1" 
                           <?php checked($show_property_tax); ?>>
                    <label for="<?php echo esc_attr($this->get_field_id('show_property_tax')); ?>">
                        <?php esc_html_e('Show property tax field', 'havenlytics'); ?>
                    </label>
                </p>

                <p>
                    <input type="checkbox" 
                           class="checkbox" 
                           id="<?php echo esc_attr($this->get_field_id('show_home_insurance')); ?>" 
                           name="<?php echo esc_attr($this->get_field_name('show_home_insurance')); ?>" 
                           value="1" 
                           <?php checked($show_home_insurance); ?>>
                    <label for="<?php echo esc_attr($this->get_field_id('show_home_insurance')); ?>">
                        <?php esc_html_e('Show home insurance field', 'havenlytics'); ?>
                    </label>
                </p>

                <p>
                    <input type="checkbox" 
                           class="checkbox" 
                           id="<?php echo esc_attr($this->get_field_id('show_hoa_fees')); ?>" 
                           name="<?php echo esc_attr($this->get_field_name('show_hoa_fees')); ?>" 
                           value="1" 
                           <?php checked($show_hoa_fees); ?>>
                    <label for="<?php echo esc_attr($this->get_field_id('show_hoa_fees')); ?>">
                        <?php esc_html_e('Show HOA fees field', 'havenlytics'); ?>
                    </label>
                </p>

                <p>
                    <input type="checkbox" 
                           class="checkbox" 
                           id="<?php echo esc_attr($this->get_field_id('show_pmi')); ?>" 
                           name="<?php echo esc_attr($this->get_field_name('show_pmi')); ?>" 
                           value="1" 
                           <?php checked($show_pmi); ?>>
                    <label for="<?php echo esc_attr($this->get_field_id('show_pmi')); ?>">
                        <?php esc_html_e('Show PMI (Private Mortgage Insurance)', 'havenlytics'); ?>
                    </label>
                </p>

                <p>
                    <input type="checkbox" 
                           class="checkbox" 
                           id="<?php echo esc_attr($this->get_field_id('show_closing_costs')); ?>" 
                           name="<?php echo esc_attr($this->get_field_name('show_closing_costs')); ?>" 
                           value="1" 
                           <?php checked($show_closing_costs); ?>>
                    <label for="<?php echo esc_attr($this->get_field_id('show_closing_costs')); ?>">
                        <?php esc_html_e('Show closing costs field', 'havenlytics'); ?>
                    </label>
                </p>
            </div>

            <p class="hvnly-widget-section-title" style="font-weight: 600; margin: 15px 0 5px; border-bottom: 1px solid #ddd; padding-bottom: 5px;">
                <?php esc_html_e('Additional Features', 'havenlytics'); ?>
            </p>

            <p>
                <input type="checkbox" 
                       class="checkbox" 
                       id="<?php echo esc_attr($this->get_field_id('show_amortization')); ?>" 
                       name="<?php echo esc_attr($this->get_field_name('show_amortization')); ?>" 
                       value="1" 
                       <?php checked($show_amortization); ?>>
                <label for="<?php echo esc_attr($this->get_field_id('show_amortization')); ?>">
                    <?php esc_html_e('Show amortization schedule', 'havenlytics'); ?>
                </label>
                <br>
                <small><?php esc_html_e('Displays yearly breakdown of principal and interest payments.', 'havenlytics'); ?></small>
            </p>
        </div>

        <style>
        .hvnly-widget-fields p {
            margin: 1em 0;
        }
        .hvnly-widget-subsection {
            border-left: 2px solid #6c60fe;
            padding-left: 15px;
            margin-left: 10px;
            margin-bottom: 15px;
        }
        </style>
        <?php
    }

    /**
     * Update widget settings
     *
     * @param array $new_instance New settings
     * @param array $old_instance Old settings
     * @return array
     */
    public function update($new_instance, $old_instance) {
        $instance = array();
        
        // Sanitize text fields
        $instance['title'] = sanitize_text_field($new_instance['title']);
        $instance['default_interest_rate'] = floatval($new_instance['default_interest_rate']);
        $instance['default_term'] = absint($new_instance['default_term']);
        $instance['default_down_payment_percent'] = absint($new_instance['default_down_payment_percent']);
        
        // Handle checkboxes
        $instance['show_advanced'] = !empty($new_instance['show_advanced']);
        $instance['show_property_tax'] = !empty($new_instance['show_property_tax']);
        $instance['show_home_insurance'] = !empty($new_instance['show_home_insurance']);
        $instance['show_hoa_fees'] = !empty($new_instance['show_hoa_fees']);
        $instance['show_pmi'] = !empty($new_instance['show_pmi']);
        $instance['show_closing_costs'] = !empty($new_instance['show_closing_costs']);
        $instance['show_amortization'] = !empty($new_instance['show_amortization']);
        $instance['show_currency_selector'] = !empty($new_instance['show_currency_selector']);
        
        return $instance;
    }

    /**
     * Sanitize instance values
     *
     * @param array $instance
     * @return array
     */
    private function sanitize_instance($instance) {
        if (!is_array($instance)) {
            return array();
        }
        
        $defaults = array(
            'title' => __('Mortgage Calculator', 'havenlytics'),
            'default_interest_rate' => 4.5,
            'default_term' => 30,
            'default_down_payment_percent' => 10,
            'show_advanced' => false,
            'show_property_tax' => false,
            'show_home_insurance' => false,
            'show_hoa_fees' => false,
            'show_pmi' => false,
            'show_closing_costs' => false,
            'show_amortization' => false,
            'show_currency_selector' => false,
        );
        
        $instance = wp_parse_args($instance, $defaults);
        
        // Sanitize each value
        $instance['title'] = sanitize_text_field($instance['title']);
        $instance['default_interest_rate'] = floatval($instance['default_interest_rate']);
        $instance['default_term'] = absint($instance['default_term']);
        $instance['default_down_payment_percent'] = absint($instance['default_down_payment_percent']);
        
        // Boolean values
        $instance['show_advanced'] = (bool) $instance['show_advanced'];
        $instance['show_property_tax'] = (bool) $instance['show_property_tax'];
        $instance['show_home_insurance'] = (bool) $instance['show_home_insurance'];
        $instance['show_hoa_fees'] = (bool) $instance['show_hoa_fees'];
        $instance['show_pmi'] = (bool) $instance['show_pmi'];
        $instance['show_closing_costs'] = (bool) $instance['show_closing_costs'];
        $instance['show_amortization'] = (bool) $instance['show_amortization'];
        $instance['show_currency_selector'] = (bool) $instance['show_currency_selector'];
        
        return $instance;
    }
}