<?php
/**
 * Share Field Template
 * 
 * This template displays the share options for a property.
 * 
 * HOW TO OVERRIDE THIS TEMPLATE:
 * 1. Copy this file from: wp-content/plugins/havenlytics/templates/archive/fields/share.php
 * 2. Paste it to your theme at: wp-content/themes/your-theme/havenlytics/archive/fields/share.php
 * 3. Modify the copied file to customize the share options display
 * 
 * @package     Havenlytics
 * @subpackage  Templates/archive/Fields
 * @since       2.0.0
 */

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

// Extract template args.
$hvnly_field         = $args['field'] ?? array();
$hvnly_value         = $args['value'] ?? array();
$hvnly_property_id   = $args['property_id'] ?? 0;
$hvnly_property_data = $args['property_data'] ?? array();

// Get field configuration.
$hvnly_field_id    = $hvnly_field['id'] ?? 'share';
$hvnly_field_type  = $hvnly_field['type'] ?? 'share';
$hvnly_field_label = $hvnly_field['label'] ?? __( 'Share', 'havenlytics' );

// Get share data.
$hvnly_share_url   = $hvnly_value['url'] ?? $hvnly_property_data['permalink'] ?? get_permalink( $hvnly_property_id );
$hvnly_share_title = $hvnly_value['title'] ?? $hvnly_property_data['title'] ?? get_the_title( $hvnly_property_id );
$hvnly_share_image = $hvnly_value['image'] ?? $hvnly_property_data['thumbnail']['large'] ?? '';

// Check if social sharing is enabled globally
if ( ! function_exists( 'hvnly_is_social_sharing_enabled' ) || ! hvnly_is_social_sharing_enabled() ) {
    return;
}

// Get enabled platforms from settings
$hvnly_enabled_platforms = function_exists( 'hvnly_get_enabled_share_platforms' ) 
    ? hvnly_get_enabled_share_platforms() 
    : array();

// If field has custom platforms, use those, otherwise use settings
if ( ! empty( $hvnly_field['settings']['platforms'] ) ) {
    $hvnly_share_platforms = $hvnly_field['settings']['platforms'];
} else {
    $hvnly_share_platforms = $hvnly_enabled_platforms;
}

// If no platforms are enabled, don't show anything
if ( empty( $hvnly_share_platforms ) ) {
    return;
}

$hvnly_share_style = $hvnly_field['settings']['style'] ?? 'popup';

// Build email mailto link
/* translators: %s: property title */
$hvnly_email_subject = sprintf( __( 'Check out this property: %s', 'havenlytics' ), $hvnly_share_title );

/* translators: 1: property title, 2: property URL, 3: sender name */
$hvnly_email_body = sprintf(
    __( "Hi,\n\nI found this property and thought you might be interested:\n\n%1\$s\n\n%2\$s\n\nRegards,\n%3\$s", 'havenlytics' ),
    $hvnly_share_title,
    $hvnly_share_url,
    wp_get_current_user()->display_name ?: 'Visitor'
);

$hvnly_mailto_link = 'mailto:?subject=' . rawurlencode( $hvnly_email_subject ) . '&body=' . rawurlencode( $hvnly_email_body );

// Encode data for JavaScript
$hvnly_share_data = array(
    'url'           => $hvnly_share_url,
    'title'         => $hvnly_share_title,
    'image'         => $hvnly_share_image,
    'property_id'   => $hvnly_property_id,
    'platforms'     => $hvnly_share_platforms,
    'mailto_link'   => $hvnly_mailto_link,
);
?>
<div class="hvnly-property-share-field hvnly-property-share-style-<?php echo esc_attr( $hvnly_share_style ); ?>"
    data-share-config='<?php echo wp_json_encode( $hvnly_share_data ); ?>'>

    <!-- Main Share Button -->
    <button class="hvnly-property-grid-list-share hvnly-property-share-trigger" type="button" aria-label="<?php echo esc_attr( sprintf( 
            /* translators: %s: Share this property */
            __( 'Share this property: %s', 'havenlytics' ), 
            $hvnly_share_title ) ); ?>" data-property-id="<?php echo esc_attr( $hvnly_property_id ); ?>">
        <i class="fas fa-share-alt" aria-hidden="true"></i>
    </button>
</div>

<?php
// Only output the global popup once
if ( ! has_action( 'wp_footer', 'hvnly_property_output_global_share_popup' ) ) {
    add_action( 'wp_footer', 'hvnly_property_output_global_share_popup' );
    
    function hvnly_property_output_global_share_popup() {
        ?>
<!-- Global Share Popup Overlay -->
<div id="hvnly-property-global-share-popup" class="hvnly-property-share-popup-overlay" role="dialog" aria-modal="true"
    aria-labelledby="hvnly-share-popup-title" aria-hidden="true">
    <div class="hvnly-property-share-popup-content" role="document">
        <div class="hvnly-property-popup-header">
            <h4 id="hvnly-share-popup-title" class="hvnly-property-popup-title">
                <?php echo esc_html__( 'Share This Property', 'havenlytics' ); ?></h4>
            <button class="hvnly-property-popup-close"
                aria-label="<?php esc_attr_e( 'Close share popup', 'havenlytics' ); ?>">
                <i class="fas fa-times" aria-hidden="true"></i>
            </button>
        </div>

        <div class="hvnly-property-share-stats">
            <div class="hvnly-property-auto-close-timer" aria-live="polite">
                <i class="fas fa-clock" aria-hidden="true"></i>
                <span
                    class="hvnly-property-timer-text"><?php echo esc_html__( 'Auto-close in 15s', 'havenlytics' ); ?></span>
            </div>
        </div>

        <!-- Social Platforms Grid - Populated by JavaScript -->
        <div class="hvnly-property-share-platforms-grid" id="hvnly-property-share-platforms-container" role="group"
            aria-label="<?php esc_attr_e( 'Social sharing platforms', 'havenlytics' ); ?>"></div>

        <!-- Copy Link Section -->
        <div class="hvnly-property-copy-link-section hvnly-property-active-section">
            <div class="hvnly-property-copy-link-header">
                <h5 class="hvnly-property-copy-title"><?php echo esc_html__( 'Copy Property Link', 'havenlytics' ); ?>
                </h5>
                <span class="hvnly-property-copy-success" aria-live="polite">
                    <i class="fas fa-check" aria-hidden="true"></i>
                    <span class="screen-reader-text"><?php esc_html_e( 'Copied successfully', 'havenlytics' ); ?></span>
                </span>
            </div>
            <div class="hvnly-property-copy-link-input">
                <input type="text" class="hvnly-property-link-input" value="" readonly
                    aria-label="<?php esc_attr_e( 'Property link to copy', 'havenlytics' ); ?>">
                <button class="hvnly-property-copy-btn"
                    aria-label="<?php esc_attr_e( 'Copy link to clipboard', 'havenlytics' ); ?>">
                    <i class="fas fa-copy" aria-hidden="true"></i>
                    <span class="hvnly-property-copy-btn-text"><?php echo esc_html__( 'Copy', 'havenlytics' ); ?></span>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
(function($) {
    'use strict';

    class HvnlyPropertyGlobalShareManager {
        constructor() {
            this.isOpen = false;
            this.currentPropertyId = null;
            this.currentShareData = null;
            this.autoCloseTimeout = null;
            this.countdownInterval = null;
            this.secondsLeft = 15;
            this.init();
        }

        init() {
            this.bindEvents();
        }

        bindEvents() {
            const self = this;

            $(document).on('click', '.hvnly-property-share-trigger', function(e) {
                e.stopPropagation();
                const propertyId = $(this).data('property-id');
                const shareField = $(this).closest('.hvnly-property-share-field');
                const shareData = JSON.parse(shareField.attr('data-share-config') || '{}');
                self.openPopup(propertyId, shareData);
            });

            $(document).on('click', '.hvnly-property-popup-close', function() {
                self.closePopup();
            });

            $(document).on('click', '.hvnly-property-share-popup-overlay', function(e) {
                if (e.target === this) {
                    self.closePopup();
                }
            });

            $(document).on('click', '.hvnly-property-copy-btn', function() {
                self.copyToClipboard(this);
            });

            $(document).on('click', '.hvnly-property-share-platform', function(e) {
                const platform = $(this).data('platform');
                self.handlePlatformClick(e, platform, this);
            });

            $(document).on('keyup', function(e) {
                if (e.key === 'Escape' && self.isOpen) {
                    self.closePopup();
                }
            });
        }

        openPopup(propertyId, shareData) {
            if (this.isOpen) return;

            this.isOpen = true;
            this.currentPropertyId = propertyId;
            this.currentShareData = shareData;

            $('.hvnly-property-share-trigger').addClass('disabled');
            $('body').addClass('hvnly-property-share-popup-open');
            const $popup = $('#hvnly-property-global-share-popup');
            $popup.addClass('active').attr('aria-hidden', 'false');

            this.populatePopupContent(shareData);
            this.startAutoCloseTimer();
            this.showCopySection();

            // Focus trap and manage focus
            $popup.find('.hvnly-property-popup-close').focus();
        }

        closePopup() {
            if (!this.isOpen) return;

            this.isOpen = false;
            this.currentPropertyId = null;
            this.currentShareData = null;

            $('.hvnly-property-share-trigger').removeClass('disabled');
            $('body').removeClass('hvnly-property-share-popup-open');
            const $popup = $('#hvnly-property-global-share-popup');
            $popup.removeClass('active').attr('aria-hidden', 'true');

            this.clearAutoCloseTimer();
            this.resetCopyButton();
        }

        populatePopupContent(shareData) {
            $('.hvnly-property-link-input').val(shareData.url);
            this.populatePlatforms(shareData);
        }

        populatePlatforms(shareData) {
            const platformsContainer = $('#hvnly-property-share-platforms-container');
            platformsContainer.empty();

            const platformConfigs = {
                'facebook': {
                    name: 'Facebook',
                    icon: 'fab fa-facebook-f',
                    color: '#1877f2',
                    url: 'https://www.facebook.com/sharer/sharer.php?u={url}'
                },
                'twitter': {
                    name: 'Twitter',
                    icon: 'fab fa-twitter',
                    color: '#1da1f2',
                    url: 'https://twitter.com/intent/tweet?url={url}&text={title}'
                },
                'linkedin': {
                    name: 'LinkedIn',
                    icon: 'fab fa-linkedin-in',
                    color: '#0a66c2',
                    url: 'https://www.linkedin.com/sharing/share-offsite/?url={url}'
                },
                'pinterest': {
                    name: 'Pinterest',
                    icon: 'fab fa-pinterest-p',
                    color: '#bd081c',
                    url: 'https://pinterest.com/pin/create/button/?url={url}&media={image}&description={title}'
                },
                'reddit': {
                    name: 'Reddit',
                    icon: 'fab fa-reddit-alien',
                    color: '#ff4500',
                    url: 'https://reddit.com/submit?url={url}&title={title}'
                },
                'tumblr': {
                    name: 'Tumblr',
                    icon: 'fab fa-tumblr',
                    color: '#35465c',
                    url: 'https://www.tumblr.com/widgets/share/tool?canonicalUrl={url}&title={title}'
                },
                'viber': {
                    name: 'Viber',
                    icon: 'fab fa-viber',
                    color: '#7360f2',
                    url: 'viber://forward?text={title} {url}'
                },
                'telegram': {
                    name: 'Telegram',
                    icon: 'fab fa-telegram-plane',
                    color: '#26a5e4',
                    url: 'https://t.me/share/url?url={url}&text={title}'
                },
                'line': {
                    name: 'Line',
                    icon: 'fab fa-line',
                    color: '#00b900',
                    url: 'https://line.me/R/msg/text/?{title}%20{url}'
                },
                'whatsapp': {
                    name: 'WhatsApp',
                    icon: 'fab fa-whatsapp',
                    color: '#25d366',
                    url: 'https://api.whatsapp.com/send?text={title} {url}'
                },
                'instagram': {
                    name: 'Instagram',
                    icon: 'fab fa-instagram',
                    color: '#e4405f',
                    url: '#'
                },
                'email': {
                    name: 'Email',
                    icon: 'fas fa-envelope',
                    color: '#666666',
                    url: shareData.mailto_link || '#'
                },
                'copy_link': {
                    name: 'Copy Link',
                    icon: 'fas fa-link',
                    color: '#6C60FE',
                    url: '#'
                }
            };

            const platforms = shareData.platforms || [];

            for (let i = 0; i < platforms.length; i++) {
                const platform = platforms[i];
                let config = platformConfigs[platform];

                if (!config) continue;

                // For email, use the mailto link from shareData
                if (platform === 'email') {
                    config = {
                        ...config,
                        url: shareData.mailto_link || '#'
                    };
                }

                let shareUrl = config.url;
                if (platform !== 'email' && platform !== 'instagram' && platform !== 'copy_link') {
                    shareUrl = shareUrl
                        .replace('{url}', encodeURIComponent(shareData.url))
                        .replace('{title}', encodeURIComponent(shareData.title))
                        .replace('{image}', encodeURIComponent(shareData.image || ''));
                }

                const target = (platform === 'copy_link' || platform === 'instagram') ? '' :
                    'target="_blank" rel="noopener noreferrer"';
                const href = (platform === 'copy_link' || platform === 'instagram') ? '#' : shareUrl;

                const platformHtml = `
                            <a href="${href}" 
                               class="hvnly-property-share-platform hvnly-property-share-${platform}" 
                               data-platform="${platform}"
                               ${target}
                               aria-label="<?php esc_attr_e( 'Share on', 'havenlytics' ); ?> ${config.name}">
                                <div class="hvnly-property-platform-icon" style="background-color: ${config.color}">
                                    <i class="${config.icon}" aria-hidden="true"></i>
                                </div>
                                <span class="hvnly-property-platform-name">${config.name}</span>
                            </a>
                        `;

                platformsContainer.append(platformHtml);
            }
        }

        startAutoCloseTimer() {
            this.secondsLeft = 15;
            this.updateTimerText();

            this.countdownInterval = setInterval(() => {
                this.secondsLeft--;
                this.updateTimerText();

                if (this.secondsLeft <= 5) {
                    $('.hvnly-property-auto-close-timer').addClass('timer-warning');
                }

                if (this.secondsLeft <= 0) {
                    this.closePopup();
                }
            }, 1000);

            this.autoCloseTimeout = setTimeout(() => this.closePopup(), 15000);
        }

        clearAutoCloseTimer() {
            if (this.autoCloseTimeout) {
                clearTimeout(this.autoCloseTimeout);
            }
            if (this.countdownInterval) {
                clearInterval(this.countdownInterval);
            }
            $('.hvnly-property-auto-close-timer').removeClass('timer-warning');
        }

        updateTimerText() {
            $('.hvnly-property-timer-text').text(
                '<?php echo esc_js( __( 'Auto-close in', 'havenlytics' ) ); ?> ' + this.secondsLeft + 's');
        }

        copyToClipboard(copyBtn) {
            const input = $('.hvnly-property-link-input')[0];
            const textToCopy = input.value;
            const originalReadonly = input.readOnly;

            input.readOnly = false;
            input.focus();
            input.select();
            input.setSelectionRange(0, 99999);

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(textToCopy).then(() => {
                    this.showCopySuccess(copyBtn);
                }).catch(() => {
                    this.fallbackCopyTextToClipboard(textToCopy, copyBtn);
                }).finally(() => {
                    input.readOnly = originalReadonly;
                });
            } else {
                this.fallbackCopyTextToClipboard(textToCopy, copyBtn);
                input.readOnly = originalReadonly;
            }
        }

        fallbackCopyTextToClipboard(text, copyBtn) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.top = "0";
            textArea.style.left = "0";
            textArea.style.position = "fixed";

            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    this.showCopySuccess(copyBtn);
                }
            } catch (err) {
                // Silent fail
            }

            document.body.removeChild(textArea);
        }

        showCopySuccess(copyBtn) {
            $('.hvnly-property-copy-success').addClass('show');
            $(copyBtn).addClass('copied');

            setTimeout(() => {
                $('.hvnly-property-copy-success').removeClass('show');
                this.resetCopyButton();
            }, 2000);

            this.trackShare('copy');
        }

        resetCopyButton() {
            $('.hvnly-property-copy-btn').removeClass('copied');
        }

        handlePlatformClick(e, platform, element) {
            if (platform === 'instagram') {
                e.preventDefault();
                alert(
                    '<?php echo esc_js( __( 'Please open Instagram app to share this property.', 'havenlytics' ) ); ?>'
                );
            } else if (platform === 'copy_link') {
                e.preventDefault();
                this.copyToClipboard($('.hvnly-property-copy-btn')[0]);
            } else {
                this.trackShare(platform);
                this.clearAutoCloseTimer();
                this.startAutoCloseTimer();
            }
        }

        showCopySection() {
            $('.hvnly-property-copy-link-section').addClass('hvnly-property-active-section');
        }

        trackShare(platform) {
            if (typeof gtag !== 'undefined') {
                gtag('event', 'share', {
                    'method': platform,
                    'content_type': 'property',
                    'content_id': this.currentPropertyId
                });
            }

            $(document).trigger('hvnly_property_shared', {
                property_id: this.currentPropertyId,
                platform: platform,
                url: this.currentShareData?.url
            });
        }
    }

    $(document).ready(function() {
        window.hvnlyPropertyShareManager = new HvnlyPropertyGlobalShareManager();
    });

})(jQuery);
</script>
<?php
    }
}