<?php

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

/**
 * Allow the production Where Next app protocol through esc_url().
 */
add_filter('kses_allowed_protocols', function ($protocols) {
    $protocols[] = 'wherenext';

    return array_unique($protocols);
});

add_shortcode('where_next_button', 'wnc_render_button');

add_shortcode('where_next_badge', 'wnc_render_ready_badge_shortcode');

if (!function_exists('wnc_badge')) {
    function wnc_badge($post_id = 0) {
        echo wnc_render_ready_badge($post_id);
    }
}

add_shortcode('where_next_card_button', function ($atts = []) {

    $atts = shortcode_atts([
        'post_id' => get_the_ID(),
        'mode'    => 'url',
    ], $atts);

    return do_shortcode(
        '[where_next_button mode="' . esc_attr($atts['mode']) . '" post_id="' . absint($atts['post_id']) . '"]'
    );
});

function wnc_site_is_where_next_ready() {
    $options = function_exists('wnc_get_options') ? wnc_get_options() : [];

    if (empty($options['show_badge'])) {
        return false;
    }

    if (empty($options['fallback_url'])) {
        return false;
    }

    if (empty($options['button_label'])) {
        return false;
    }

    if (empty($options['button_style'])) {
        return false;
    }

    return true;
}

function wnc_page_can_show_ready_badge($post_id = 0) {
    $post_id = absint($post_id) ?: get_the_ID();

    if (!$post_id) {
        return false;
    }

    if (!wnc_site_is_where_next_ready()) {
        return false;
    }

    if (is_admin()) {
        return false;
    }

    return true;
}

function wnc_render_ready_badge($post_id = 0) {
    $post_id = absint($post_id) ?: get_the_ID();

    if (!wnc_page_can_show_ready_badge($post_id)) {
        return '';
    }

    $options = function_exists('wnc_get_options') ? wnc_get_options() : [];

    $variant = $options['badge_variant'] ?? 'colour';
    $allowed = ['colour', 'light', 'icon'];

    if (!in_array($variant, $allowed, true)) {
        $variant = 'colour';
    }

    $badge_url = plugin_dir_url(dirname(__FILE__)) . 'assets/badges/badge-' . $variant . '.png';

    return '<a class="wnc-ready-badge wnc-ready-badge-' . esc_attr($variant) . '" href="https://wherenext.dev/works-with/" target="_blank" rel="noopener">' .
        '<img src="' . esc_url($badge_url) . '" alt="Works with Where Next" loading="lazy">' .
    '</a>';
}

function wnc_render_ready_badge_shortcode($atts = []) {
    $atts = shortcode_atts([
        'post_id' => get_the_ID(),
    ], $atts);

    return wnc_render_ready_badge(absint($atts['post_id']));
}

/**
 * Legacy/full deep-link redirect support.
 *
 * This keeps support for:
 * /?wnc_open_post=123
 *
 * It is not the main flow now. The main flow is:
 * wherenext://import-place?sourceUrl=https://example.com/location-page/
 */
add_action('template_redirect', function () {

    if (empty($_GET['wnc_open_post'])) {
        return;
    }

    $post_id = absint($_GET['wnc_open_post']);

    if (!$post_id) {
        wp_safe_redirect(home_url('/'));
        exit;
    }

    $target = wnc_build_deep_link($post_id);

    if (!$target || strpos($target, WNC_APP_SCHEME . '://') !== 0) {
        wp_safe_redirect(get_permalink($post_id));
        exit;
    }

    wp_redirect($target);
    exit;
});

function wnc_render_button($atts = []) {

    if (!is_singular() && empty($atts['post_id'])) {
        return '';
    }

    $options = wnc_get_options();

    $atts = shortcode_atts([
        'label'    => $options['button_label'] ?? 'Send to Where Next',
        'fallback' => $options['fallback_url'] ?? home_url('/getwherenext/'),
        'mode'     => 'url',
        'post_id'  => get_the_ID(),
    ], $atts);

    $post_id = absint($atts['post_id']) ?: get_the_ID();

    if (!$post_id) {
        return '';
    }

    /**
     * Default mode is URL scan.
     *
     * URL mode sends only the page URL:
     * wherenext://import-place?sourceUrl=https://example.com/location-page/
     *
     * The app then fetches sourceUrl and scans the page for:
     * <meta name="wherenext:*" content="...">
     *
     * Full mode remains available manually:
     * [where_next_button mode="full"]
     */
    if ($atts['mode'] === 'full') {
        $deep_link = wnc_build_deep_link($post_id);
    } else {
        $source_url = get_permalink($post_id);

        $deep_link = WNC_APP_SCHEME . '://' . WNC_APP_ROUTE . '?sourceUrl=' . rawurlencode($source_url);
    }

    if (!$deep_link) {
        return '';
    }

    $is_mobile = wnc_is_mobile_device();

    if (!$is_mobile) {

        // Never show QR codes on URL-scan card buttons.
        if ($atts['mode'] === 'url') {
            return '';
        }

        // Full location page can still show QR codes if Pro QR support exists.
        if (
            function_exists('wnc_is_pro_active')
            && wnc_is_pro_active()
            && !empty($options['pro_show_desktop_qr'])
            && function_exists('wnc_render_qr_box')
        ) {
            return wnc_render_qr_box($deep_link);
        }

        return '';
    }

    if (
        function_exists('wnc_should_display_button')
        && !wnc_should_display_button()
    ) {
        return '';
    }

    $icon_url = wnc_get_icon_url(
        $options['button_icon'] ?? 'journey'
    );

    $position_class = '';

    if (function_exists('wnc_get_button_position_class')) {
        $position_class = wnc_get_button_position_class();
    }

    ob_start();
    ?>

    <span class="wnc-button-wrap <?php echo esc_attr($position_class); ?>">
        <a
            class="wnc-button wnc-button-<?php echo esc_attr($options['button_style'] ?? 'filled'); ?> wnc-button-<?php echo esc_attr($options['button_size'] ?? 'medium'); ?>"
            href="<?php echo esc_url($deep_link); ?>"
            data-fallback="<?php echo esc_url($atts['fallback']); ?>"
            data-wnc-post-id="<?php echo esc_attr($post_id); ?>"
            data-wnc-button-mode="<?php echo esc_attr($atts['mode']); ?>"
            rel="nofollow"
        >
            <?php if ($icon_url) : ?>
                <img
                    class="wnc-button-icon wnc-icon-<?php echo esc_attr($options['icon_size'] ?? 'medium'); ?>"
                    src="<?php echo esc_url($icon_url); ?>"
                    alt=""
                    loading="lazy"
                >
            <?php endif; ?>

            <span class="wnc-button-label">
                <?php echo esc_html($atts['label']); ?>
            </span>
        </a>
    </span>

<?php if (!empty($options['show_badge']) && ($options['badge_position'] ?? 'manual') === 'after_button') : ?>
    <?php echo wnc_render_ready_badge($post_id); ?>
<?php endif; ?>

<?php

    return ob_get_clean();
}

add_filter('the_content', function ($content) {
    if (!is_singular()) {
        return $content;
    }

    $options = function_exists('wnc_get_options') ? wnc_get_options() : [];

    if (empty($options['show_badge']) || ($options['badge_position'] ?? 'manual') !== 'after_content') {
        return $content;
    }

    return $content . wnc_render_ready_badge(get_the_ID());
});

add_filter('the_content', function ($content) {
    if (!is_singular()) {
        return $content;
    }

    $options = function_exists('wnc_get_options') ? wnc_get_options() : [];

    if (empty($options['show_badge']) || ($options['badge_position'] ?? 'manual') !== 'after_post_footer') {
        return $content;
    }

    return $content . '<div class="wnc-ready-badge-after-post-footer">' . wnc_render_ready_badge(get_the_ID()) . '</div>';
}, 30);

add_filter('the_excerpt', 'wnc_maybe_add_archive_button_to_excerpt', 20);

function wnc_maybe_add_archive_button_to_excerpt($excerpt) {
    if (is_admin() || is_singular()) {
        return $excerpt;
    }

    $options = wnc_get_options();

    if (empty($options['archive_button_enabled'])) {
        return $excerpt;
    }

    $post_id = get_the_ID();

    if (!$post_id || !wnc_is_enabled_post_type(get_post_type($post_id))) {
        return $excerpt;
    }

    $mode = $options['archive_button_mode'] ?? 'url';

    $button = do_shortcode(
        '[where_next_card_button post_id="' . absint($post_id) . '" mode="' . esc_attr($mode) . '"]'
    );

    if (!$button) {
        return $excerpt;
    }

    return $excerpt . '<div class="wnc-archive-button-wrap">' . $button . '</div>';
}

add_action('wp_footer', function () {
    $options = function_exists('wnc_get_options') ? wnc_get_options() : [];

    if (empty($options['show_badge'])) {
        return;
    }

    $position = $options['badge_position'] ?? 'manual';

    if (!in_array($position, ['footer_inline', 'footer_center', 'floating'], true)) {
        return;
    }

    $post_id = is_singular() ? get_the_ID() : 0;

    if ($position === 'footer_inline') {
        echo '<div class="wnc-ready-badge-footer wnc-ready-badge-footer-inline">';
        echo wnc_render_ready_badge($post_id);
        echo '</div>';
        return;
    }

    if ($position === 'footer_center') {
        echo '<div class="wnc-ready-badge-footer wnc-ready-badge-footer-center">';
        echo wnc_render_ready_badge($post_id);
        echo '</div>';
        return;
    }

    if ($position === 'floating') {
        echo '<div class="wnc-ready-badge-floating">';
        echo wnc_render_ready_badge($post_id);
        echo '</div>';
    }
});

add_action('wp_enqueue_scripts', function () {
    $options = wnc_get_options();

    $button_style = $options['button_style'] ?? 'filled';

    $background = $options['button_bg_colour'] ?? '#0f766e';
    $text = $options['button_text_colour'] ?? '#ffffff';
    $border = $options['button_border_colour'] ?? $background;

    if ($button_style === 'outline') {
        $background = 'transparent';
    }

    if ($button_style === 'soft') {
        $background = $background;
    }

    $sizes = [
        'small' => [
            'height' => '44px',
            'padding' => '10px 18px',
            'font' => '15px',
            'gap' => '8px',
        ],
        'medium' => [
            'height' => '54px',
            'padding' => '14px 26px',
            'font' => '17px',
            'gap' => '10px',
        ],
        'large' => [
            'height' => '64px',
            'padding' => '18px 34px',
            'font' => '18px',
            'gap' => '12px',
        ],
    ];

    $icon_sizes = [
        'small' => '22px',
        'medium' => '28px',
        'large' => '34px',
    ];

    $button_size_key = $options['button_size'] ?? 'medium';
    $icon_size_key = $options['icon_size'] ?? 'medium';

    $size = $sizes[$button_size_key] ?? $sizes['medium'];
    $icon_size = $icon_sizes[$icon_size_key] ?? $icon_sizes['medium'];

    wp_register_style('where-next-connector', false, [], WNC_VERSION);
    wp_enqueue_style('where-next-connector');

    $css = '

.wnc-button-wrap{
    display:inline-block !important;
}

/* ==========================
   Floating positions
========================== */

.wnc-sticky-bottom{
    position:fixed !important;
    bottom:18px !important;
    left:50% !important;
    transform:translateX(-50%) !important;
    z-index:999999 !important;
    max-width:calc(100vw - 24px) !important;
}

.wnc-floating-right{
    position:fixed !important;
    bottom:18px !important;
    right:18px !important;
    z-index:999999 !important;
    max-width:calc(100vw - 24px) !important;
}

.wnc-floating-left{
    position:fixed !important;
    bottom:18px !important;
    left:18px !important;
    z-index:999999 !important;
    max-width:calc(100vw - 24px) !important;
}

/* ==========================
   Main Button
========================== */

a.wnc-button,
.wnc-button{

    display:inline-flex !important;

    align-items:center !important;

    justify-content:center !important;

    gap:' . esc_attr($size['gap']) . ' !important;

    min-height:' . esc_attr($size['height']) . ' !important;

    padding:' . esc_attr($size['padding']) . ' !important;

    border-radius:999px !important;

    background:' . esc_attr($background) . ' !important;

    color:' . esc_attr($text) . ' !important;

    border:2px solid ' . esc_attr($border) . ' !important;

    font-size:' . esc_attr($size['font']) . ' !important;

    font-weight:800 !important;

    text-decoration:none !important;

    line-height:1 !important;

    box-shadow:0 4px 12px rgba(0,0,0,.12) !important;

    width:auto !important;

    max-width:100% !important;

    overflow:hidden !important;

    box-sizing:border-box !important;
}

a.wnc-button:hover,
a.wnc-button:focus,
.wnc-button:hover,
.wnc-button:focus{

    opacity:.92 !important;

    color:' . esc_attr($text) . ' !important;

    text-decoration:none !important;
}

.wnc-button img.wnc-button-icon,
img.wnc-button-icon{

    width:' . esc_attr($icon_size) . ' !important;

    height:' . esc_attr($icon_size) . ' !important;

    max-width:' . esc_attr($icon_size) . ' !important;

    max-height:' . esc_attr($icon_size) . ' !important;

    object-fit:contain !important;

    flex:0 0 auto !important;

    display:block !important;

    margin:0 !important;

    padding:0 !important;
}

.wnc-button .wnc-button-label{

    display:inline-block !important;

    white-space:nowrap !important;

    line-height:1.1 !important;

    margin:0 !important;

    padding:0 !important;
}

/* ==========================
   QR Desktop Card
========================== */

.wnc-qr-box{

    display:flex !important;

    align-items:center !important;

    justify-content:space-between !important;

    gap:22px !important;

    max-width:560px !important;

    padding:22px !important;

    border:1px solid #e5e7eb !important;

    border-radius:24px !important;

    background:#ffffff !important;

    box-shadow:0 10px 30px rgba(15,23,42,.10) !important;

    text-align:left !important;
}

.wnc-qr-box-content{

    flex:1 !important;
}

.wnc-qr-box strong{

    display:block !important;

    margin:0 0 10px !important;

    font-size:24px !important;

    line-height:1.1 !important;

    color:#111827 !important;
}

.wnc-qr-box p{

    margin:0 !important;

    color:#64748b !important;

    font-size:15px !important;

    line-height:1.5 !important;
}

.wnc-qr-box img{

    display:block !important;

    width:170px !important;

    height:170px !important;

    min-width:170px !important;

    max-width:170px !important;

    object-fit:contain !important;

    aspect-ratio:1 / 1 !important;

    background:#fff !important;

    padding:10px !important;

    border:1px solid #eef2f7 !important;

    border-radius:14px !important;

    margin:0 !important;
}

/* ==========================
   Mobile
========================== */

@media (max-width:700px){

    .wnc-qr-box{

        flex-direction:column !important;

        text-align:center !important;

        max-width:320px !important;
    }

    .wnc-qr-box img{

        width:150px !important;

        height:150px !important;

        min-width:150px !important;
    }
}

.wnc-ready-badge {
    display:inline-flex !important;
    align-items:center !important;
    text-decoration:none !important;
    margin-top:12px !important;
}

.wnc-ready-badge img {
    display:block !important;
    width:220px !important;
    max-width:100% !important;
    height:auto !important;
    border:0 !important;
    box-shadow:none !important;
}

.wnc-ready-badge-icon img {
    width:48px !important;
}

.wnc-ready-badge-after-post-footer {
    margin:28px 0 0 !important;
    text-align:center !important;
}

.wnc-ready-badge-footer {
    text-align:center !important;
    padding:24px 12px !important;
}

.wnc-ready-badge-footer-inline {
    display:flex !important;
    justify-content:center !important;
    align-items:center !important;
}

.wnc-ready-badge-footer-center {
    display:block !important;
    text-align:center !important;
}

.wnc-ready-badge-floating {
    position:fixed !important;
    right:18px !important;
    bottom:18px !important;
    z-index:999999 !important;
    max-width:220px !important;
}

.wnc-ready-badge-floating .wnc-ready-badge {
    margin:0 !important;
}

@media (max-width:700px){
    .wnc-ready-badge-floating {
        right:12px !important;
        bottom:12px !important;
        max-width:160px !important;
    }

    .wnc-ready-badge-floating .wnc-ready-badge img {
        width:160px !important;
    }
}
';

    wp_add_inline_style('where-next-connector', $css);

    wp_register_script('where-next-connector', '', [], WNC_VERSION, true);
    wp_enqueue_script('where-next-connector');

    wp_add_inline_script(
        'where-next-connector',
        "
        document.addEventListener('click', function(e) {
            var button = e.target.closest('.wnc-button');

            if (!button) return;

            var fallback = button.getAttribute('data-fallback');

            if (!fallback) return;

            var appOpened = false;

            function markAppOpened() {
                appOpened = true;
            }

            function visibilityHandler() {
                if (document.hidden) {
                    markAppOpened();
                }
            }

            document.addEventListener('visibilitychange', visibilityHandler);
            window.addEventListener('pagehide', markAppOpened);
            window.addEventListener('blur', markAppOpened);

            setTimeout(function() {
                document.removeEventListener('visibilitychange', visibilityHandler);

                if (!appOpened) {
                    window.location.href = fallback;
                }
            }, 1800);
        });
        "
    );
});
