<?php
/**
 * Enqueue child styles.
 */
function child_enqueue_styles() {
    wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/style.css', array(), 100 );
}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles' );


function my_dynamic_filter_text() {
    if ( isset($_GET['kb_filter']) ) {
        $term_slug = sanitize_text_field($_GET['kb_filter']);
        $term = get_term_by('slug', $term_slug, 'resource-type'); 
        if ( $term ) {
            return 'Displaying articles for category: ' . esc_html($term->name);
        }
    }
    return 'Please select a category in the filter.';
}
add_shortcode('filter_dynamic_text', 'my_dynamic_filter_text');

function bw_custom_big_image_size_threshold() {
    return 4000; // example 4000px
}
add_filter('big_image_size_threshold', 'bw_custom_big_image_size_threshold');


// Youtube Shortcode — now handled by the bw-youtube-embed plugin.
// See: wp-content/plugins/bw-youtube-embed/bw-youtube-embed.php
// Usage: [bw_youtube] for thumbnail (default), [bw_youtube mode="video"] for iframe embed.


/**
 * Custom JS in footer: Scroll to top on Kadence Ajax pagination
 * Exclude on /resources/ page
 */
add_action('wp_footer', function () {
//     if (is_page('resources')) {
//         return; // Skip script on this page
//     }
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        // Find the query loop container
        const loopContainer = document.querySelector('.wp-block-kadence-query');
        if (!loopContainer) return;

        // Use MutationObserver to detect content changes
        const observer = new MutationObserver(function (mutationsList) {
            for (let mutation of mutationsList) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    // Smoothly scroll to the top of the page
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                }
            }
        });

        // Start observing loopContainer changes
        observer.observe(loopContainer, { childList: true, subtree: true });
    });
    </script>
    <?php
});





/// [bw_typeintro param="2847258112" taxonomy="service" select="(auto)"]
add_shortcode('bw_typeintro', function($atts){
    $a = shortcode_atts([
        'param'    => '2847258112', // URL query key that holds the term_id
        'taxonomy' => 'service',    // taxonomy to read from
        // If you omit 'select', we'll target the Kadence filter whose wrapper has data-hash="<param>"
        // e.g. .wp-block-kadence-query-filter[data-hash='2847258112'] .kb-filter
        'select'   => '',
    ], $atts, 'bw_typeintro');

    $param    = sanitize_key($a['param']);
    $taxonomy = sanitize_key($a['taxonomy']);

    // Default selector if not provided
    $selector = $a['select'];
    if ($selector === '' || $selector === null) {
        $selector = ".wp-block-kadence-query-filter[data-hash='{$param}'] .kb-filter";
    }

    $nonce = wp_create_nonce('bw_typeintro_nonce');
    $ajax  = admin_url('admin-ajax.php');

    ob_start(); ?>
    <script>
    (function(){
        var SELECTOR  = <?php echo json_encode($selector); ?>;
        var PARAM_KEY = <?php echo json_encode($param); ?>;
        var TAXONOMY  = <?php echo json_encode($taxonomy); ?>;
        var AJAX_URL  = <?php echo json_encode($ajax); ?>;
        var NONCE     = <?php echo json_encode($nonce); ?>;

        var titleEl = document.getElementById('page-title');
        var descEl  = document.getElementById('page-description');
        if (!titleEl || !descEl) return;

        // Keep originals so we can restore when cleared
        var originalTitleHTML = titleEl.innerHTML;
        var originalDescHTML  = descEl.innerHTML;

        function setOutput(name, descriptionHTML){
            if (name && (''+name).trim() !== '') {
                titleEl.textContent = ('Resources: '+name).trim(); // safe: text only
            } else {
                titleEl.innerHTML = originalTitleHTML;  // restore
            }

            if (descriptionHTML && (''+descriptionHTML).trim() !== '') {
                descEl.innerHTML = descriptionHTML;     // server sanitized
            } else {
                descEl.innerHTML = originalDescHTML;    // restore
            }
        }

        function fetchTerm(termId){
            if (!termId) { setOutput('', ''); return; }
            var fd = new FormData();
            fd.append('action', 'bw_typeintro_term');
            fd.append('term_id', String(termId));
            fd.append('taxonomy', TAXONOMY);
            fd.append('_ajax_nonce', NONCE);

            fetch(AJAX_URL, { method: 'POST', body: fd, credentials: 'same-origin' })
              .then(function(r){ return r.json(); })
              .then(function(data){
                  if (data && data.success && data.term) {
                      setOutput(data.term.name || '', data.term.description || '');
                  } else {
                      setOutput('', '');
                  }
              })
              .catch(function(){ setOutput('', ''); });
        }

        function updateUrlParam(val){
            try{
                var url = new URL(window.location.href);
                if (!val) url.searchParams.delete(PARAM_KEY);
                else url.searchParams.set(PARAM_KEY, String(val));
                history.replaceState(null, '', url.toString());
            }catch(e){}
        }

        function onChange(e){
            var t = e.target;
            if (!t || !t.matches || !t.matches(SELECTOR)) return; // only our service select
            var val = (t.value || '').trim();
            updateUrlParam(val);
            if (!val) setOutput('', '');
            else fetchTerm(val);
        }
        document.addEventListener('change', onChange, true);

        // On load, if URL already has the param, populate title/desc
        try{
            var url = new URL(window.location.href);
            var idFromUrl = (url.searchParams.get(PARAM_KEY) || '').trim();
            if (idFromUrl) fetchTerm(idFromUrl);
        } catch(e){}
    })();
    </script>
    <?php
    return ob_get_clean();
});

/**
 * AJAX: return term name + sanitized description by ID for a taxonomy.
 * - Name is entity-decoded to avoid "M&amp;A" showing literally.
 * - Description is kses-sanitized (basic HTML allowed).
 */
add_action('wp_ajax_bw_typeintro_term', 'bw_typeintro_term_ajax');
add_action('wp_ajax_nopriv_bw_typeintro_term', 'bw_typeintro_term_ajax');
function bw_typeintro_term_ajax(){
    check_ajax_referer('bw_typeintro_nonce');

    $term_id  = isset($_POST['term_id']) ? absint($_POST['term_id']) : 0;
    $taxonomy = isset($_POST['taxonomy']) ? sanitize_key($_POST['taxonomy']) : '';

    if (!$term_id || !$taxonomy) {
        wp_send_json(['success' => false, 'error' => 'missing_params']);
    }

    $term = get_term($term_id, $taxonomy);
    if (!$term || is_wp_error($term)) {
        wp_send_json(['success' => false, 'error' => 'term_not_found']);
    }

    // Decode entities in name (fix "M&amp;A" -> "M&A")
    $name = wp_specialchars_decode($term->name, ENT_QUOTES);

    // Sanitize description but allow basic formatting
    $desc_raw = term_description($term->term_id, $taxonomy);
    $desc     = $desc_raw ? wp_kses_post($desc_raw) : '';

    wp_send_json([
        'success' => true,
        'term' => [
            'id'          => $term->term_id,
            'name'        => $name,
            'description' => $desc,
        ],
    ]);
}



/* Enable auto-updates of plugins/themes on Flywheel */
add_action(
    'wp_update_plugins',
    function() {
        if (wp_doing_cron() && ! doing_action('wp_maybe_auto_update')) {
            do_action('wp_maybe_auto_update');
        }
    },
    20
);


add_shortcode('auto_download_mca_guide', 'swc_bulletproof_download');

function swc_bulletproof_download() {
    $pdf_url = 'https://secondwindconsultants.com/wp-content/uploads/2025/10/Debt_Settlement_v16_web.pdf';

    ob_start();
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(function() {
            var url = '<?php echo esc_url($pdf_url); ?>';
            var fileName = 'MCA_Debt_Settlement_Guide.pdf';

            fetch(url)
                .then(function(response) { return response.blob(); })
                .then(function(blob) {
                    var blobUrl = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = blobUrl;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    setTimeout(function() {
                        document.body.removeChild(a);
                        URL.revokeObjectURL(blobUrl);
                    }, 200);
                });
        }, 1500);
    });
    </script>
    <?php
    return ob_get_clean();
}

  /**
   * SWC — auto-fill "Lead Source (Salesforce)" on every Gravity Form.
   *
   * If the form was submitted from a URL containing "/l/", set the value to
   * "SWC Landing Page"; otherwise "Website". Finds the field by label, so the
   * snippet keeps working across form edits and multiple forms.
   */
  add_action( 'gform_pre_submission', function ( $form ) {
        $referer = isset( $_SERVER['HTTP_REFERER'] ) ? wp_unslash( $_SERVER['HTTP_REFERER'] ) : '';
        $value   = ( false !== strpos( $referer, '/l/' ) ) ? 'SWC Landing Page' : 'Website';

        foreach ( $form['fields'] as $field ) {
                if ( strcasecmp( trim( (string) $field->label ), 'Lead Source (Salesforce)' ) === 0 ) {
                        $_POST[ 'input_' . $field->id ] = $value;
                        break;
                }
        }
  } );



/**
 * Suppress the default Kadence theme output of post_content for 'our-team' posts.
 * Content is only rendered via the [team_bio] shortcode inside the Kadence Element template.
 */
function swc_suppress_our_team_content( $content ) {
    global $swc_doing_team_bio;
    if ( ! empty( $swc_doing_team_bio ) ) return $content;
    if ( ! is_singular( 'our-team' ) ) return $content;
    if ( ! in_the_loop() || ! is_main_query() ) return $content;
    return '';
}
add_filter( 'the_content', 'swc_suppress_our_team_content', 5 );

/**
 * [team_bio] shortcode — outputs the current Our Team post editor content.
 * Guards against recursion if [team_bio] accidentally appears inside bio content.
 */
function swc_team_bio_shortcode() {
    global $post, $swc_doing_team_bio;
    if ( ! $post || ! empty( $swc_doing_team_bio ) ) return '';
    $swc_doing_team_bio = true;
    $content = apply_filters( 'the_content', get_the_content( null, false, $post ) );
    $swc_doing_team_bio = false;
    return $content;
}
add_shortcode( 'team_bio', 'swc_team_bio_shortcode' );


/**
 * MCA Debt Relief Guide — static page injection.
 *
 * The WP page is kept empty so Gutenberg and Kadence skip parsing ~273 KB of
 * blocks on edit and on every request. The fully rendered HTML and its
 * per-block CSS were captured once and stored under the child theme; this
 * filter injects them in place of the_content() on that page only.
 *
 * To refresh: re-capture the rendered page, replace
 * template-parts/mca-debt-relief-guide.html and assets/mca-debt-relief-guide.css.
 */
define( 'SWC_MCA_GUIDE_SLUG', 'mca-debt-relief-guide' );

function swc_mca_guide_is_target() {
    if ( ! is_singular() || ! is_main_query() || ! in_the_loop() ) {
        return false;
    }
    $post = get_queried_object();
    return $post && isset( $post->post_name ) && $post->post_name === SWC_MCA_GUIDE_SLUG;
}

function swc_mca_guide_inject_content( $content ) {
    if ( ! swc_mca_guide_is_target() ) {
        return $content;
    }
    $path = get_stylesheet_directory() . '/template-parts/mca-debt-relief-guide.html';
    if ( ! is_readable( $path ) ) {
        return $content;
    }
    return file_get_contents( $path );
}
add_filter( 'the_content', 'swc_mca_guide_inject_content', 999 );

function swc_mca_guide_enqueue_assets() {
    if ( ! is_singular() ) {
        return;
    }
    $post = get_queried_object();
    if ( ! $post || $post->post_name !== SWC_MCA_GUIDE_SLUG ) {
        return;
    }
    $css_path = get_stylesheet_directory() . '/assets/mca-debt-relief-guide.css';
    if ( ! file_exists( $css_path ) ) {
        return;
    }
    // Force-enqueue Kadence block stylesheets that Kadence would normally
    // auto-enqueue when it detects these blocks in post_content — but the
    // post is empty, so we re-register them by hand.
    $kb_dist = content_url( 'plugins/kadence-blocks/dist' );
    $kb_ver  = defined( 'KADENCE_BLOCKS_VERSION' ) ? KADENCE_BLOCKS_VERSION : null;
    foreach ( array( 'icon', 'infobox', 'table' ) as $block ) {
        wp_enqueue_style( "kadence-blocks-{$block}", "{$kb_dist}/style-blocks-{$block}.css", array(), $kb_ver );
    }
    wp_enqueue_style(
        'swc-mca-debt-relief-guide',
        get_stylesheet_directory_uri() . '/assets/mca-debt-relief-guide.css',
        array( 'child-theme' ),
        filemtime( $css_path )
    );
}
add_action( 'wp_enqueue_scripts', 'swc_mca_guide_enqueue_assets', 20 );

/**
 * =============================================================================
 * Grant Editor role access to Kadence Elements and Appearance Menu
 * Copy this entire section to other sites
 * =============================================================================
 */

/**
 * Add capabilities to Editor role for Kadence Elements and Appearance menu
 */
add_action('init', 'swc_editor_kadence_capabilities');
function swc_editor_kadence_capabilities() {
    $editor = get_role('editor');
    if (!$editor) {
        return;
    }

    // Kadence Elements capabilities (custom post type: kadence_element)
    $editor->add_cap('edit_kadence_elements');
    $editor->add_cap('edit_others_kadence_elements');
    $editor->add_cap('publish_kadence_elements');
    $editor->add_cap('read_private_kadence_elements');
    $editor->add_cap('delete_kadence_elements');
    $editor->add_cap('delete_others_kadence_elements');
    $editor->add_cap('delete_published_kadence_elements');
    $editor->add_cap('edit_published_kadence_elements');

    // Appearance menu capabilities (for Menus, Widgets, Customizer)
    $editor->add_cap('edit_theme_options');
}

/**
 * Allow Editors to access Kadence Elements admin menu
 */
add_filter('kadence_element_post_type_args', 'swc_kadence_elements_editor_access');
function swc_kadence_elements_editor_access($args) {
    $args['capability_type'] = 'kadence_element';
    $args['map_meta_cap'] = true;
    $args['capabilities'] = array(
        'edit_post'              => 'edit_kadence_element',
        'read_post'              => 'read_kadence_element',
        'delete_post'            => 'delete_kadence_element',
        'edit_posts'             => 'edit_kadence_elements',
        'edit_others_posts'      => 'edit_others_kadence_elements',
        'publish_posts'          => 'publish_kadence_elements',
        'read_private_posts'     => 'read_private_kadence_elements',
        'delete_posts'           => 'delete_kadence_elements',
        'delete_others_posts'    => 'delete_others_kadence_elements',
        'delete_published_posts' => 'delete_published_kadence_elements',
        'edit_published_posts'   => 'edit_published_kadence_elements',
    );
    return $args;
}