<?php
/**
 * Property Agent Widget - Enhanced with Property Selection
 *
 * @package HvnlyNab\Database\Custom_Widgets\All_Widgets
 * @since 2.0.0
 */

namespace HvnlyNab\Database\Custom_Widgets\All_Widgets;

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

/**
 * Class Hvnly_Property_Agent_Widget
 */
class Hvnly_Property_Agent_Widget extends \WP_Widget {

    /**
     * Constructor
     */
    public function __construct() {
        $widget_ops = array(
            'classname' => 'hvnly-property-single__widget hvnly-property-single__widget--agent',
            'description' => __('Display property agent information with contact details. Can be assigned to specific properties.', 'havenlytics'),
            'customize_selective_refresh' => true,
        );
        
        parent::__construct(
            'hvnly_property_agent',
            __('Havenlytics: Property Agent (Advanced)', 'havenlytics'),
            $widget_ops
        );

        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_hvnly_search_properties', array($this, 'ajax_search_properties'));
    }

    /**
     * Enqueue admin scripts
     *
     * @param string $hook_suffix
     * @return void
     */
    public function enqueue_admin_scripts($hook_suffix) {
        if (!in_array($hook_suffix, array('widgets.php', 'customize.php'), true)) {
            return;
        }

        wp_enqueue_media();
        // wp_enqueue_script('jquery-ui-autocomplete');
        // wp_enqueue_style('jquery-ui-style', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css', array(), '1.12.1');

        wp_enqueue_script(
            'hvnly-agent-widget',
            HVNLYNAB_ASSETS_URL . '/admin/js/hvnly-agent-widget.js',
            array('jquery', 'jquery-ui-autocomplete', 'media-upload', 'media-views'),
            HVNLYNAB_VERSION,
            true
        );

        wp_localize_script(
            'hvnly-agent-widget',
            'hvnlyAgentWidget',
            array(
                'selectAvatar' => __('Select Agent Avatar', 'havenlytics'),
                'useAsAvatar'  => __('Use as Avatar', 'havenlytics'),
                'removeAvatar' => __('Remove', 'havenlytics'),
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvnly_search_properties'),
                'searchPlaceholder' => __('Search by title or ID...', 'havenlytics'),
                'selectedText' => __('Selected Properties:', 'havenlytics'),
                'removeText' => __('Remove', 'havenlytics'),
            )
        );
    }

    /**
     * AJAX handler for property search
     */
    public function ajax_search_properties() {
        //  Use filter_input for nonce with FILTER_UNSAFE_RAW (PHP 8.1+ compatible)
        $nonce_raw = filter_input(INPUT_POST, 'nonce', FILTER_UNSAFE_RAW);
        $nonce = $nonce_raw ? sanitize_text_field($nonce_raw) : '';
        
        // Verify nonce
        if (!$nonce || !wp_verify_nonce($nonce, 'hvnly_search_properties')) {
            wp_die('Security check failed');
        }

        // Use filter_input for search parameter
        $search_raw = filter_input(INPUT_POST, 'search', FILTER_UNSAFE_RAW);
        $search = $search_raw ? sanitize_text_field($search_raw) : '';
        
        //  Use filter_input for exclude parameter
        $exclude_raw = filter_input(INPUT_POST, 'exclude', FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY);
        $exclude = is_array($exclude_raw) ? array_map('absint', $exclude_raw) : array();

        $args = array(
            'post_type' => 'hvnly_property',
            'post_status' => 'publish',
            'posts_per_page' => 20,
            's' => $search,
            'post__not_in' => $exclude,
        );

        $query = new \WP_Query($args);
        $results = array();

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $results[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                    'label' => get_the_title() . ' (ID: ' . get_the_ID() . ')',
                );
            }
            wp_reset_postdata();
        }

        wp_send_json($results);
    }

    /**
     * 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;
        }

        $current_property_id = get_the_ID();
        
        // Check if this widget is assigned to current property
        $assigned_properties = isset($instance['assigned_properties']) ? $instance['assigned_properties'] : array();
        
        // If properties are assigned, check if current property is in the list
        if (!empty($assigned_properties) && is_array($assigned_properties)) {
            if (!in_array($current_property_id, $assigned_properties)) {
                return; // Don't show widget for this property
            }
        }

        // Default values
        $defaults = array(
            'title' => __('Property Agent', 'havenlytics'),
            'agent_source' => 'author',
            'agent_name' => '',
            'agent_name_override' => '',
            'agent_position' => '',
            'agent_company' => '',
            'agent_email' => '',
            'agent_phone' => '',
            'agent_whatsapp' => '',
            'agent_avatar' => '',
            'agent_avatar_id' => 0,
            'agent_rating_enabled' => 0,
            'agent_rating' => '4.9',
            'agent_reviews' => '128',
            'show_phone' => '1',
            'show_email' => '1',
            'show_whatsapp' => '0',
            'show_website' => '1',
            'show_social' => '1',
            'show_rating' => '1',
            'social_facebook' => '',
            'social_twitter' => '',
            'social_linkedin' => '',
            'social_instagram' => '',
            'social_youtube' => '',
            'social_tiktok' => '',
            'social_pinterest' => '',
            'social_snapchat' => '',
            'social_telegram' => '',
            'assigned_properties' => array(),
        );

        $instance = wp_parse_args((array) $instance, $defaults);
        
        $title = !empty($instance['title']) ? $instance['title'] : __('Property Agent', 'havenlytics');
        
        // Get agent data based on source
        $property_id = get_the_ID();
        
        if ('author' === $instance['agent_source']) {
            $author_id = get_post_field('post_author', $property_id);
            $agent_data = $this->get_agent_data_from_author($author_id, $instance);
        } else {
            $agent_data = $this->get_agent_data_from_custom($instance);
        }

        // Apply manual name override if set
        if (!empty($instance['agent_name_override'])) {
            $agent_data['name'] = $instance['agent_name_override'];
        }

        // Don't show if no agent data
        if (empty($agent_data['name']) && empty($agent_data['avatar'])) {
            return;
        }

        // Widget output - escape widget args
        echo wp_kses_post( $args['before_widget'] );
        
        if (!empty($title)) {
            echo wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] );
        }
        ?>

<!-- Property Agent Widget -->
<div class="hvnly-property-single__agent-header">
    <?php if (!empty($agent_data['avatar'])) : ?>
    <img src="<?php echo esc_url($agent_data['avatar']); ?>" alt="<?php echo esc_attr($agent_data['name']); ?>"
        class="hvnly-property-single__agent-avatar">
    <?php else : ?>
    <div class="hvnly-property-single__agent-avatar-placeholder">
        <i class="fas fa-user-circle fa-3x"></i>
    </div>
    <?php endif; ?>

    <div class="hvnly-property-single__agent-info">
        <h5><?php echo esc_html($agent_data['name']); ?></h5>

        <?php if (!empty($agent_data['position'])) : ?>
        <p><i class="fas fa-briefcase"></i> <?php echo esc_html($agent_data['position']); ?></p>
        <?php endif; ?>

        <?php if (!empty($agent_data['company'])) : ?>
        <p><i class="fas fa-building"></i> <?php echo esc_html($agent_data['company']); ?></p>
        <?php endif; ?>

        <?php if (!empty($instance['show_rating']) && !empty($instance['agent_rating_enabled'])) : 
                    $rating = floatval($instance['agent_rating']);
                    $reviews = intval($instance['agent_reviews']);
                ?>
        <p class="hvnly-property-single__agent-rating">
            <?php for ($i = 1; $i <= 5; $i++) : ?>
            <i class="fas fa-star<?php echo $i <= floor($rating) ? '' : '-o'; ?>"
                style="color: <?php echo $i <= floor($rating) ? '#FFD700' : '#ddd'; ?>;"></i>
            <?php endfor; ?>
            <span> <?php echo esc_html(number_format($rating, 1)); ?> (<?php echo esc_html(number_format($reviews)); ?>
                reviews)</span>
        </p>
        <?php endif; ?>
    </div>
</div>

<?php 
        // Contact Actions Section
        $has_phone = !empty($instance['show_phone']) && !empty($agent_data['phone']);
        $has_email = !empty($instance['show_email']) && !empty($agent_data['email']);
        $has_whatsapp = !empty($instance['show_whatsapp']) && !empty($agent_data['whatsapp']);
        $has_website = !empty($instance['show_website']) && !empty($agent_data['website']);
        
        if ($has_phone || $has_email || $has_whatsapp || $has_website) : 
        ?>
<div class="hvnly-property-single__agent-actions">
    <?php if ($has_phone) : ?>
    <a href="tel:<?php echo esc_attr(preg_replace('/[^0-9+]/', '', $agent_data['phone'])); ?>"
        class="hvnly-property-single__agent-btn">
        <i class="fas fa-phone-alt"></i>
        <?php esc_html_e('Call Agent', 'havenlytics'); ?>
    </a>
    <?php endif; ?>

    <?php if ($has_email) : ?>
    <a href="mailto:<?php echo esc_attr($agent_data['email']); ?>"
        class="hvnly-property-single__agent-btn hvnly-property-single__agent-btn--secondary">
        <i class="fas fa-envelope"></i>
        <?php esc_html_e('Email Agent', 'havenlytics'); ?>
    </a>
    <?php endif; ?>

    <?php if ($has_whatsapp) : ?>
    <a href="https://wa.me/<?php echo esc_attr(preg_replace('/[^0-9]/', '', $agent_data['whatsapp'])); ?>"
        class="hvnly-property-single__agent-btn hvnly-property-single__agent-btn--secondary" target="_blank"
        rel="noopener noreferrer">
        <i class="fab fa-whatsapp"></i>
        <?php esc_html_e('WhatsApp', 'havenlytics'); ?>
    </a>
    <?php endif; ?>

    <?php if ($has_website) : ?>
    <a href="<?php echo esc_url($agent_data['website']); ?>"
        class="hvnly-property-single__agent-btn hvnly-property-single__agent-btn--secondary" target="_blank"
        rel="noopener noreferrer">
        <i class="fas fa-globe"></i>
        <?php esc_html_e('Website', 'havenlytics'); ?>
    </a>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php 
        // Social Media Links Section
        $social_platforms = array(
            'facebook' => $instance['social_facebook'],
            'twitter' => $instance['social_twitter'],
            'linkedin' => $instance['social_linkedin'],
            'instagram' => $instance['social_instagram'],
            'youtube' => $instance['social_youtube'],
            'tiktok' => $instance['social_tiktok'],
            'pinterest' => $instance['social_pinterest'],
            'snapchat' => $instance['social_snapchat'],
            'telegram' => $instance['social_telegram'],
        );
        
        $social_icons = array(
            'facebook' => 'fab fa-facebook-f',
            'twitter' => 'fab fa-twitter',
            'linkedin' => 'fab fa-linkedin-in',
            'instagram' => 'fab fa-instagram',
            'youtube' => 'fab fa-youtube',
            'tiktok' => 'fab fa-tiktok',
            'pinterest' => 'fab fa-pinterest-p',
            'snapchat' => 'fab fa-snapchat-ghost',
            'telegram' => 'fab fa-telegram-plane',
        );
        
        $has_social = !empty(array_filter($social_platforms)) && !empty($instance['show_social']);
        
        if ($has_social) : 
        ?>
<div class="hvnly-property-single__agent-social">
    <h5><?php esc_html_e('Connect with Agent', 'havenlytics'); ?></h5>
    <div class="hvnly-property-single__social-links">
        <?php foreach ($social_platforms as $platform => $url) : ?>
        <?php if (!empty($url)) : ?>
        <a href="<?php echo esc_url($url); ?>"
            class="hvnly-property-single__social-link hvnly-property-single__social-link--<?php echo esc_attr($platform); ?>"
            target="_blank" rel="noopener noreferrer" title="<?php echo esc_attr(ucfirst($platform)); ?>">
            <i class="<?php echo esc_attr($social_icons[$platform]); ?>"></i>
        </a>
        <?php endif; ?>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<style>
/* Agent Widget Social Styles */
.hvnly-property-single__agent-social {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid rgba(108, 96, 254, 0.1);
}

.hvnly-property-single__agent-social h5 {
    font-size: 14px;
    margin-bottom: 12px;
    color: var(--hvnly-text-secondary, #666);
    font-weight: 600;
}

.hvnly-property-single__social-links {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.hvnly-property-single__social-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: rgba(108, 96, 254, 0.1);
    color: var(--hvnly-text-primary, #333);
    transition: all 0.3s ease;
    text-decoration: none;
}

.hvnly-property-single__social-link:hover {
    transform: translateY(-3px);
    color: white;
}

.hvnly-property-single__social-link--facebook:hover {
    background: #1877f2;
}

.hvnly-property-single__social-link--twitter:hover {
    background: #1da1f2;
}

.hvnly-property-single__social-link--linkedin:hover {
    background: #0077b5;
}

.hvnly-property-single__social-link--instagram:hover {
    background: #e4405f;
}

.hvnly-property-single__social-link--youtube:hover {
    background: #ff0000;
}

.hvnly-property-single__social-link--tiktok:hover {
    background: #000000;
}

.hvnly-property-single__social-link--pinterest:hover {
    background: #bd081c;
}

.hvnly-property-single__social-link--snapchat:hover {
    background: #fffc00;
    color: #000;
}

.hvnly-property-single__social-link--telegram:hover {
    background: #0088cc;
}

.hvnly-property-single__agent-rating i {
    margin-right: 2px;
}
</style>

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

    /**
     * Get agent data from author profile
     *
     * @param int $author_id
     * @param array $instance
     * @return array
     */
    private function get_agent_data_from_author($author_id, $instance) {
        $agent_data = array(
            'name' => get_the_author_meta('display_name', $author_id),
            'email' => get_the_author_meta('user_email', $author_id),
            'phone' => get_user_meta($author_id, '_hvnly_agent_phone', true),
            'whatsapp' => get_user_meta($author_id, '_hvnly_agent_whatsapp', true),
            'position' => get_user_meta($author_id, '_hvnly_agent_position', true),
            'company' => get_user_meta($author_id, '_hvnly_agent_company', true),
            'website' => get_user_meta($author_id, 'user_url', true),
            'avatar' => get_avatar_url($author_id, array('size' => 200)),
        );

        // Use widget values as fallback
        $fields = array('name', 'position', 'company', 'email', 'phone', 'whatsapp', 'website');
        foreach ($fields as $field) {
            if (empty($agent_data[$field]) && !empty($instance['agent_' . $field])) {
                $agent_data[$field] = $instance['agent_' . $field];
            }
        }

        // Override avatar with widget if set
        if (!empty($instance['agent_avatar'])) {
            $agent_data['avatar'] = $instance['agent_avatar'];
        }

        return $agent_data;
    }

    /**
     * Get agent data from custom fields
     *
     * @param array $instance
     * @return array
     */
    private function get_agent_data_from_custom($instance) {
        return array(
            'name' => $instance['agent_name'],
            'email' => $instance['agent_email'],
            'phone' => $instance['agent_phone'],
            'whatsapp' => $instance['agent_whatsapp'],
            'position' => $instance['agent_position'],
            'company' => $instance['agent_company'],
            'website' => !empty($instance['agent_website']) ? $instance['agent_website'] : '',
            'avatar' => $instance['agent_avatar'],
        );
    }

    /**
     * Widget form (admin)
     *
     * @param array $instance Widget instance
     * @return void
     */
    public function form($instance) {
        // Default values
        $defaults = array(
            'title' => __('Property Agent', 'havenlytics'),
            'agent_source' => 'author',
            'agent_name' => '',
            'agent_name_override' => '',
            'agent_position' => '',
            'agent_company' => '',
            'agent_email' => '',
            'agent_phone' => '',
            'agent_whatsapp' => '',
            'agent_website' => '',
            'agent_avatar' => '',
            'agent_avatar_id' => 0,
            'agent_rating_enabled' => 0,
            'agent_rating' => '4.9',
            'agent_reviews' => '128',
            'show_phone' => '1',
            'show_email' => '1',
            'show_whatsapp' => '0',
            'show_website' => '1',
            'show_social' => '1',
            'show_rating' => '1',
            'social_facebook' => '',
            'social_twitter' => '',
            'social_linkedin' => '',
            'social_instagram' => '',
            'social_youtube' => '',
            'social_tiktok' => '',
            'social_pinterest' => '',
            'social_snapchat' => '',
            'social_telegram' => '',
            'assigned_properties' => array(),
        );
        
        $instance = wp_parse_args((array) $instance, $defaults);
        $agent_source = $instance['agent_source'];
        $assigned_properties = is_array($instance['assigned_properties']) ? $instance['assigned_properties'] : array();
        ?>

<div class="hvnly-agent-widget-form">
    <!-- Property Assignment Section -->
    <h5><?php esc_html_e('Property Assignment', 'havenlytics'); ?></h5>
    <p class="description">
        <?php esc_html_e('Select which properties should display this agent. Leave empty to show on all properties.', 'havenlytics'); ?>
    </p>

    <div class="hvnly-property-search-container">
        <input type="text" class="widefat hvnly-property-search"
            placeholder="<?php esc_attr_e('Search properties to assign...', 'havenlytics'); ?>"
            data-target="<?php echo esc_attr($this->get_field_id('assigned_properties')); ?>">

        <div class="hvnly-selected-properties" id="<?php echo esc_attr($this->get_field_id('selected-properties')); ?>">
            <?php if (!empty($assigned_properties)) : ?>
            <?php foreach ($assigned_properties as $prop_id) : 
                            $prop_title = get_the_title($prop_id);
                            if ($prop_title) :
                        ?>
            <div class="hvnly-selected-property" data-id="<?php echo esc_attr($prop_id); ?>">
                <span><?php echo esc_html($prop_title); ?> (ID: <?php echo esc_html($prop_id); ?>)</span>
                <button type="button" class="hvnly-remove-property">×</button>
                <input type="hidden" name="<?php echo esc_attr($this->get_field_name('assigned_properties')); ?>[]"
                    value="<?php echo esc_attr($prop_id); ?>">
            </div>
            <?php endif; ?>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <hr>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
            <?php esc_html_e('Widget 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($instance['title']); ?>">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('agent_source')); ?>">
            <?php esc_html_e('Agent Data Source:', 'havenlytics'); ?>
        </label>
        <select class="widefat hvnly-agent-source" id="<?php echo esc_attr($this->get_field_id('agent_source')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_source')); ?>">
            <option value="author" <?php selected($agent_source, 'author'); ?>>
                <?php esc_html_e('Use Property Author', 'havenlytics'); ?>
            </option>
            <option value="custom" <?php selected($agent_source, 'custom'); ?>>
                <?php esc_html_e('Custom Agent Data', 'havenlytics'); ?>
            </option>
        </select>
    </p>

    <!-- Manual Name Override -->
    <p>
        <label for="<?php echo esc_attr($this->get_field_id('agent_name_override')); ?>">
            <?php esc_html_e('Manual Name Override:', 'havenlytics'); ?>
        </label>
        <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_name_override')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_name_override')); ?>"
            value="<?php echo esc_attr($instance['agent_name_override']); ?>"
            placeholder="<?php esc_attr_e('Override agent name (optional)', 'havenlytics'); ?>">
        <small
            class="description"><?php esc_html_e('If set, this will override the agent name from any source.', 'havenlytics'); ?></small>
    </p>

    <div class="hvnly-agent-custom-fields" style="<?php echo 'custom' !== $agent_source ? 'display: none;' : ''; ?>">
        <h5><?php esc_html_e('Custom Agent Details', 'havenlytics'); ?></h5>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('agent_name')); ?>">
                <?php esc_html_e('Agent Name:', 'havenlytics'); ?>
            </label>
            <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_name')); ?>"
                name="<?php echo esc_attr($this->get_field_name('agent_name')); ?>"
                value="<?php echo esc_attr($instance['agent_name']); ?>">
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('agent_position')); ?>">
                <?php esc_html_e('Position/Title:', 'havenlytics'); ?>
            </label>
            <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_position')); ?>"
                name="<?php echo esc_attr($this->get_field_name('agent_position')); ?>"
                value="<?php echo esc_attr($instance['agent_position']); ?>">
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('agent_company')); ?>">
                <?php esc_html_e('Company:', 'havenlytics'); ?>
            </label>
            <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_company')); ?>"
                name="<?php echo esc_attr($this->get_field_name('agent_company')); ?>"
                value="<?php echo esc_attr($instance['agent_company']); ?>">
        </p>
    </div>

    <h5><?php esc_html_e('Contact Information', 'havenlytics'); ?></h5>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('agent_email')); ?>">
            <?php esc_html_e('Email:', 'havenlytics'); ?>
        </label>
        <input type="email" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_email')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_email')); ?>"
            value="<?php echo esc_attr($instance['agent_email']); ?>">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('agent_phone')); ?>">
            <?php esc_html_e('Phone:', 'havenlytics'); ?>
        </label>
        <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_phone')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_phone')); ?>"
            value="<?php echo esc_attr($instance['agent_phone']); ?>" placeholder="+1 (555) 123-4567">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('agent_whatsapp')); ?>">
            <?php esc_html_e('WhatsApp:', 'havenlytics'); ?>
        </label>
        <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_whatsapp')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_whatsapp')); ?>"
            value="<?php echo esc_attr($instance['agent_whatsapp']); ?>" placeholder="+1234567890">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('agent_website')); ?>">
            <?php esc_html_e('Website:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_website')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_website')); ?>"
            value="<?php echo esc_attr($instance['agent_website']); ?>" placeholder="https://example.com">
    </p>

    <h5><?php esc_html_e('Avatar', 'havenlytics'); ?></h5>

    <div class="hvnly-agent-avatar-field">
        <input type="hidden" class="hvnly-agent-avatar-id-field"
            id="<?php echo esc_attr($this->get_field_id('agent_avatar_id')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_avatar_id')); ?>"
            value="<?php echo esc_attr($instance['agent_avatar_id']); ?>">

        <input type="hidden" class="hvnly-agent-avatar-url-field"
            id="<?php echo esc_attr($this->get_field_id('agent_avatar')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_avatar')); ?>"
            value="<?php echo esc_attr($instance['agent_avatar']); ?>">

        <div class="hvnly-agent-avatar-preview">
            <?php if (!empty($instance['agent_avatar'])) : ?>
            <img src="<?php echo esc_url($instance['agent_avatar']); ?>" alt=""
                style="max-width: 100px; max-height: 100px; border-radius: 50%;">
            <?php else : ?>
            <div class="hvnly-agent-avatar-placeholder"
                style="width: 100px; height: 100px; background: #f0f0f0; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-user-circle fa-3x" style="color: #999;"></i>
            </div>
            <?php endif; ?>
        </div>

        <p>
            <button type="button" class="button hvnly-agent-avatar-upload-btn">
                <i class="fas fa-upload"></i> <?php esc_html_e('Choose Image', 'havenlytics'); ?>
            </button>
            <button type="button" class="button hvnly-agent-avatar-remove-btn"
                <?php echo empty($instance['agent_avatar']) ? 'style="display:none;"' : ''; ?>>
                <i class="fas fa-times"></i> <?php esc_html_e('Remove', 'havenlytics'); ?>
            </button>
        </p>
    </div>

    <h5><?php esc_html_e('Rating & Reviews', 'havenlytics'); ?></h5>

    <p>
        <input type="checkbox" class="checkbox hvnly-agent-rating-enabled"
            id="<?php echo esc_attr($this->get_field_id('agent_rating_enabled')); ?>"
            name="<?php echo esc_attr($this->get_field_name('agent_rating_enabled')); ?>" value="1"
            <?php checked($instance['agent_rating_enabled'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('agent_rating_enabled')); ?>">
            <?php esc_html_e('Enable rating display', 'havenlytics'); ?>
        </label>
    </p>

    <div class="hvnly-agent-rating-fields"
        style="<?php echo empty($instance['agent_rating_enabled']) ? 'display: none;' : ''; ?>">
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('agent_rating')); ?>">
                <?php esc_html_e('Rating (1-5):', 'havenlytics'); ?>
            </label>
            <input type="number" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_rating')); ?>"
                name="<?php echo esc_attr($this->get_field_name('agent_rating')); ?>"
                value="<?php echo esc_attr($instance['agent_rating']); ?>" min="1" max="5" step="0.1">
        </p>

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('agent_reviews')); ?>">
                <?php esc_html_e('Number of Reviews:', 'havenlytics'); ?>
            </label>
            <input type="number" class="widefat" id="<?php echo esc_attr($this->get_field_id('agent_reviews')); ?>"
                name="<?php echo esc_attr($this->get_field_name('agent_reviews')); ?>"
                value="<?php echo esc_attr($instance['agent_reviews']); ?>" min="0">
        </p>
    </div>

    <h5><?php esc_html_e('Social Media Links', 'havenlytics'); ?></h5>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_facebook')); ?>">
            <i class="fab fa-facebook-f" style="color: #1877f2;"></i> <?php esc_html_e('Facebook:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_facebook')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_facebook')); ?>"
            value="<?php echo esc_attr($instance['social_facebook']); ?>" placeholder="https://facebook.com/username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_twitter')); ?>">
            <i class="fab fa-twitter" style="color: #1da1f2;"></i> <?php esc_html_e('Twitter:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_twitter')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_twitter')); ?>"
            value="<?php echo esc_attr($instance['social_twitter']); ?>" placeholder="https://twitter.com/username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_linkedin')); ?>">
            <i class="fab fa-linkedin-in" style="color: #0077b5;"></i> <?php esc_html_e('LinkedIn:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_linkedin')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_linkedin')); ?>"
            value="<?php echo esc_attr($instance['social_linkedin']); ?>"
            placeholder="https://linkedin.com/in/username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_instagram')); ?>">
            <i class="fab fa-instagram" style="color: #e4405f;"></i> <?php esc_html_e('Instagram:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_instagram')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_instagram')); ?>"
            value="<?php echo esc_attr($instance['social_instagram']); ?>" placeholder="https://instagram.com/username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_youtube')); ?>">
            <i class="fab fa-youtube" style="color: #ff0000;"></i> <?php esc_html_e('YouTube:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_youtube')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_youtube')); ?>"
            value="<?php echo esc_attr($instance['social_youtube']); ?>" placeholder="https://youtube.com/@username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_tiktok')); ?>">
            <i class="fab fa-tiktok"></i> <?php esc_html_e('TikTok:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_tiktok')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_tiktok')); ?>"
            value="<?php echo esc_attr($instance['social_tiktok']); ?>" placeholder="https://tiktok.com/@username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_pinterest')); ?>">
            <i class="fab fa-pinterest-p" style="color: #bd081c;"></i> <?php esc_html_e('Pinterest:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_pinterest')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_pinterest')); ?>"
            value="<?php echo esc_attr($instance['social_pinterest']); ?>" placeholder="https://pinterest.com/username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_snapchat')); ?>">
            <i class="fab fa-snapchat-ghost" style="color: #fffc00;"></i>
            <?php esc_html_e('Snapchat:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_snapchat')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_snapchat')); ?>"
            value="<?php echo esc_attr($instance['social_snapchat']); ?>"
            placeholder="https://snapchat.com/add/username">
    </p>

    <p>
        <label for="<?php echo esc_attr($this->get_field_id('social_telegram')); ?>">
            <i class="fab fa-telegram-plane" style="color: #0088cc;"></i>
            <?php esc_html_e('Telegram:', 'havenlytics'); ?>
        </label>
        <input type="url" class="widefat" id="<?php echo esc_attr($this->get_field_id('social_telegram')); ?>"
            name="<?php echo esc_attr($this->get_field_name('social_telegram')); ?>"
            value="<?php echo esc_attr($instance['social_telegram']); ?>" placeholder="https://t.me/username">
    </p>

    <h5><?php esc_html_e('Display Options', 'havenlytics'); ?></h5>

    <p>
        <input type="checkbox" class="checkbox" id="<?php echo esc_attr($this->get_field_id('show_phone')); ?>"
            name="<?php echo esc_attr($this->get_field_name('show_phone')); ?>" value="1"
            <?php checked($instance['show_phone'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('show_phone')); ?>">
            <?php esc_html_e('Show phone button', 'havenlytics'); ?>
        </label>
    </p>

    <p>
        <input type="checkbox" class="checkbox" id="<?php echo esc_attr($this->get_field_id('show_email')); ?>"
            name="<?php echo esc_attr($this->get_field_name('show_email')); ?>" value="1"
            <?php checked($instance['show_email'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('show_email')); ?>">
            <?php esc_html_e('Show email button', 'havenlytics'); ?>
        </label>
    </p>

    <p>
        <input type="checkbox" class="checkbox" id="<?php echo esc_attr($this->get_field_id('show_whatsapp')); ?>"
            name="<?php echo esc_attr($this->get_field_name('show_whatsapp')); ?>" value="1"
            <?php checked($instance['show_whatsapp'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('show_whatsapp')); ?>">
            <?php esc_html_e('Show WhatsApp button', 'havenlytics'); ?>
        </label>
    </p>

    <p>
        <input type="checkbox" class="checkbox" id="<?php echo esc_attr($this->get_field_id('show_website')); ?>"
            name="<?php echo esc_attr($this->get_field_name('show_website')); ?>" value="1"
            <?php checked($instance['show_website'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('show_website')); ?>">
            <?php esc_html_e('Show website button', 'havenlytics'); ?>
        </label>
    </p>

    <p>
        <input type="checkbox" class="checkbox" id="<?php echo esc_attr($this->get_field_id('show_social')); ?>"
            name="<?php echo esc_attr($this->get_field_name('show_social')); ?>" value="1"
            <?php checked($instance['show_social'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('show_social')); ?>">
            <?php esc_html_e('Show social media links', 'havenlytics'); ?>
        </label>
    </p>

    <p>
        <input type="checkbox" class="checkbox" id="<?php echo esc_attr($this->get_field_id('show_rating')); ?>"
            name="<?php echo esc_attr($this->get_field_name('show_rating')); ?>" value="1"
            <?php checked($instance['show_rating'], '1'); ?>>
        <label for="<?php echo esc_attr($this->get_field_id('show_rating')); ?>">
            <?php esc_html_e('Show rating (if enabled)', 'havenlytics'); ?>
        </label>
    </p>
</div>

<style>
.hvnly-agent-widget-form h5 {
    margin: 20px 0 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #ddd;
    font-size: 14px;
}

.hvnly-agent-avatar-preview {
    margin: 10px 0;
}

.hvnly-agent-rating-fields {
    padding: 10px;
    background: #f9f9f9;
    border-left: 3px solid #0073aa;
    margin: 10px 0;
}

.hvnly-agent-custom-fields {
    padding: 10px;
    background: #f9f9f9;
    border-left: 3px solid #46b450;
    margin: 10px 0;
}

.hvnly-selected-property {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    margin: 5px 0;
    background: #f0f0f1;
    border: 1px solid #c3c4c7;
    border-radius: 4px;
}

.hvnly-selected-property button {
    background: none;
    border: none;
    color: #dc3232;
    font-size: 18px;
    cursor: pointer;
    padding: 0 5px;
}

.hvnly-selected-property button:hover {
    color: #a00;
}

.ui-autocomplete {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    z-index: 1000000;
}

.ui-menu-item {
    padding: 8px 12px;
    cursor: pointer;
}

.ui-menu-item:hover {
    background: #f0f0f0;
}

.ui-helper-hidden-accessible {
    display: none;
}
</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();
        
        // Text fields
        $instance['title'] = sanitize_text_field($new_instance['title']);
        $instance['agent_source'] = isset($new_instance['agent_source']) ? sanitize_text_field($new_instance['agent_source']) : 'author';
        $instance['agent_name'] = sanitize_text_field($new_instance['agent_name']);
        $instance['agent_name_override'] = sanitize_text_field($new_instance['agent_name_override']);
        $instance['agent_position'] = sanitize_text_field($new_instance['agent_position']);
        $instance['agent_company'] = sanitize_text_field($new_instance['agent_company']);
        $instance['agent_email'] = sanitize_email($new_instance['agent_email']);
        $instance['agent_phone'] = sanitize_text_field($new_instance['agent_phone']);
        $instance['agent_whatsapp'] = sanitize_text_field($new_instance['agent_whatsapp']);
        $instance['agent_website'] = esc_url_raw($new_instance['agent_website']);
        $instance['agent_avatar'] = esc_url_raw($new_instance['agent_avatar']);
        $instance['agent_avatar_id'] = absint($new_instance['agent_avatar_id']);
        
        // Assigned properties
        $instance['assigned_properties'] = array();
        if (isset($new_instance['assigned_properties']) && is_array($new_instance['assigned_properties'])) {
            $instance['assigned_properties'] = array_map('absint', $new_instance['assigned_properties']);
        }
        
        // Rating
        $instance['agent_rating_enabled'] = isset($new_instance['agent_rating_enabled']) && $new_instance['agent_rating_enabled'] === '1' ? '1' : '0';
        $instance['agent_rating'] = floatval($new_instance['agent_rating']);
        $instance['agent_reviews'] = absint($new_instance['agent_reviews']);
        
        // Social media
        $instance['social_facebook'] = esc_url_raw($new_instance['social_facebook']);
        $instance['social_twitter'] = esc_url_raw($new_instance['social_twitter']);
        $instance['social_linkedin'] = esc_url_raw($new_instance['social_linkedin']);
        $instance['social_instagram'] = esc_url_raw($new_instance['social_instagram']);
        $instance['social_youtube'] = esc_url_raw($new_instance['social_youtube']);
        $instance['social_tiktok'] = esc_url_raw($new_instance['social_tiktok']);
        $instance['social_pinterest'] = esc_url_raw($new_instance['social_pinterest']);
        $instance['social_snapchat'] = esc_url_raw($new_instance['social_snapchat']);
        $instance['social_telegram'] = esc_url_raw($new_instance['social_telegram']);
        
        // Display options
        $instance['show_phone'] = isset($new_instance['show_phone']) && $new_instance['show_phone'] === '1' ? '1' : '0';
        $instance['show_email'] = isset($new_instance['show_email']) && $new_instance['show_email'] === '1' ? '1' : '0';
        $instance['show_whatsapp'] = isset($new_instance['show_whatsapp']) && $new_instance['show_whatsapp'] === '1' ? '1' : '0';
        $instance['show_website'] = isset($new_instance['show_website']) && $new_instance['show_website'] === '1' ? '1' : '0';
        $instance['show_social'] = isset($new_instance['show_social']) && $new_instance['show_social'] === '1' ? '1' : '0';
        $instance['show_rating'] = isset($new_instance['show_rating']) && $new_instance['show_rating'] === '1' ? '1' : '0';
        
        return $instance;
    }
}