<?php
/**
 * Theme functions and definitions.
 *
 * https://developers.elementor.com/docs/hello-elementor-theme/
 *
 * @package HelloElementorChild
 */

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

define( 'HELLO_ELEMENTOR_CHILD_VERSION', '2.0.0' );

/**
 * Load child theme scripts & styles.
 */
function hello_elementor_child_scripts_styles() {
    wp_enqueue_style(
        'hello-elementor-child-style',
        get_stylesheet_directory_uri() . '/style.css',
        [ 'hello-elementor-theme-style' ],
        HELLO_ELEMENTOR_CHILD_VERSION
    );
}
add_action( 'wp_enqueue_scripts', 'hello_elementor_child_scripts_styles', 20 );

/**
 * SVG uploads
 */
add_filter('upload_mimes', function($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
});

add_filter('wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    if (strtolower($ext) === 'svg') {
        $data['ext']  = 'svg';
        $data['type'] = 'image/svg+xml';
    }
    return $data;
}, 10, 4);

/**
 * Adobe Typekit font
 */
function enqueue_quincy_typekit() {
    wp_enqueue_style(
        'adobe-typekit-quincy',
        'https://use.typekit.net/oos5pym.css',
        [],
        null
    );
}
add_action('wp_enqueue_scripts', 'enqueue_quincy_typekit');
add_action('elementor/editor/after_enqueue_styles', 'enqueue_quincy_typekit');

// Register "quincy-cf" so it shows up in Elementor's font dropdown
add_action('elementor/init', function () {
    add_filter('elementor/fonts/additional_fonts', function ($fonts) {
        $fonts['quincy-cf'] = 'Quincy CF';
        return $fonts;
    });
});

/**
 * Shortcodes (ACF repeaters) — safe if ACF not installed
 */
add_shortcode('focus_areas', function() {
    if (!function_exists('get_field') || !function_exists('have_rows') || !have_rows('focus_areas')) return '';
    ob_start();
    echo '<div class="focus-areas">';
    while (have_rows('focus_areas')) {
        the_row();
        $label = function_exists('get_sub_field') ? get_sub_field('focus_area') : '';
        if (!$label) continue;
        echo '<span class="focus-pill">'.esc_html($label).'</span>';
    }
    echo '</div>';
    return ob_get_clean();
});

add_shortcode('services_used', function() {
    if (!function_exists('get_field') || !function_exists('have_rows') || !have_rows('services_used')) return '';
    ob_start();
    echo '<div class="services-list">';
    while (have_rows('services_used')) {
        the_row();
        $service = function_exists('get_sub_field') ? get_sub_field('service') : '';
        if (!$service) continue;
        echo '<div class="service-pill">'.esc_html($service).'</div>';
    }
    echo '</div>';
    return ob_get_clean();
});

add_shortcode('case_results', function() {
    if (!function_exists('get_field') || !function_exists('have_rows') || !have_rows('results')) return '';
    ob_start();
    echo '<ul class="results-list">';
    while (have_rows('results')) {
        the_row();
        $result = function_exists('get_sub_field') ? get_sub_field('result') : '';
        if (!$result) continue;
        echo '<li>'.esc_html($result).'</li>';
    }
    echo '</ul>';
    return ob_get_clean();
});

/**
 * [medium_logo url="" alt=""]
 */
function bb_medium_logo_shortcode( $atts ) {
    $a = shortcode_atts([
        'url' => '',
        'alt' => '',
    ], $atts, 'medium_logo');

    if ( empty( $a['url'] ) ) return '';

    $url = esc_url_raw( $a['url'] );
    $alt = sanitize_text_field( $a['alt'] );

    $id = attachment_url_to_postid( $url );
    if ( $id ) {
        if ( $alt === '' ) {
            $stored_alt = get_post_meta( $id, '_wp_attachment_image_alt', true );
            if ( $stored_alt ) $alt = $stored_alt;
        }
        $attrs = [
            'class'    => 'logo-img',
            'loading'  => 'lazy',
            'decoding' => 'async',
            'alt'      => $alt,
            'sizes'    => '(max-width: 767px) 32px, 42px',
        ];
        $html = wp_get_attachment_image( $id, 'medium', false, $attrs );
        if ( $html ) return $html;
    }

    // Fallback: attempt -300xH URL
    $med_url = $url;
    $parsed  = wp_parse_url( $url );
    if ( ! empty( $parsed['path'] ) ) {
        $path = $parsed['path'];
        $ext  = pathinfo( $path, PATHINFO_EXTENSION );
        $base = substr( $path, 0, -( strlen($ext) + 1 ) );
        $abs  = untrailingslashit( ABSPATH ) . $path;

        $w = $h = 0;
        if ( file_exists( $abs ) ) {
            $sz = @getimagesize( $abs );
            if ( $sz ) { $w = (int)$sz[0]; $h = (int)$sz[1]; }
        }

        if ( $w > 0 && $h > 0 ) {
            $med_h   = max( 1, round( $h * ( 300 / $w ) ) );
            $med_rel = "{$base}-300x{$med_h}.{$ext}";
            $med_url = home_url( $med_rel );
        }
    }

    $alt_attr = $alt !== '' ? ' alt="' . esc_attr($alt) . '"' : '';
    return '<img class="logo-img" src="' . esc_url( $med_url ) . '"' . $alt_attr . ' loading="lazy" decoding="async">';
}
add_shortcode( 'medium_logo', 'bb_medium_logo_shortcode' );

/**
 * Attach Focus Area taxonomy to Case Study CPT + seed terms once.
 */
add_action('init', function () {
    $taxonomy  = 'focus-area';
    $post_type = 'case-study';

    if (taxonomy_exists($taxonomy)) {
        register_taxonomy_for_object_type($taxonomy, $post_type);
    } else {
        return;
    }

    if (get_option('bb_seeded_focus_areas')) return;

    $terms = [
        'Arts & Culture',
        'Biotechnology & Life Sciences',
        'Climate, Environment, & Sustainability',
        'Community & Network Building',
        'Community Development',
        'Early Childhood Development',
        'Education',
        'Food Security & Nutrition',
        'Gender Equality',
        'Healthcare',
        'International Development',
        'Mental Health & Wellbeing',
        'Poverty Alleviation',
        'Power Generation & Energy',
        'Public Health',
        'Socioeconomic Equity',
        'Technology & Digital Innovation',
        'Transportation',
    ];

    foreach ($terms as $name) {
        if (!term_exists($name, $taxonomy)) {
            wp_insert_term($name, $taxonomy);
        }
    }

    update_option('bb_seeded_focus_areas', 1);
}, 20);

/**
 * Elementor Post Info: use <br> between Focus Area terms
 */
add_filter('elementor_pro/posts/info/terms_separator', function($separator, $taxonomy){
    return ($taxonomy === 'focus-area') ? '<br>' : $separator;
}, 10, 2);

/**
 * Query var for pretty Focus Area route
 */
add_filter('query_vars', function($vars){
    $vars[] = 'fa';
    return $vars;
});

/**
 * Rewrite rules:
 *  - /case-studies/page/2/
 *  - /case-studies/{slug}/
 *  - /case-studies/{slug}/page/2/
 */
add_action('init', function(){
    // normal archive pagination FIRST
    add_rewrite_rule(
        '^case-studies/page/([0-9]+)/?$',
        'index.php?post_type=case-study&paged=$matches[1]',
        'top'
    );

    add_rewrite_rule(
        '^case-studies/([^/]+)/page/([0-9]+)/?$',
        'index.php?post_type=case-study&fa=$matches[1]&paged=$matches[2]',
        'top'
    );

    add_rewrite_rule(
        '^case-studies/([^/]+)/?$',
        'index.php?post_type=case-study&fa=$matches[1]',
        'top'
    );
}, 10);

/**
 * Force ALL Focus Area term links to /case-studies/{slug}/
 */
add_filter('term_link', function($url, $term, $taxonomy){
    if ($taxonomy === 'focus-area') {
        return trailingslashit( home_url( 'case-studies/' . $term->slug ) );
    }
    return $url;
}, 10, 3);

/**
 * Redirect legacy /focus-area/{slug}/ → /case-studies/{slug}/
 */
add_action('template_redirect', function(){
    if (is_tax('focus-area')) {
        $term = get_queried_object();
        if ($term && !is_wp_error($term)) {
            wp_redirect(trailingslashit( home_url( 'case-studies/' . $term->slug ) ), 301);
            exit;
        }
    }
});

/**
 * Main query filter for CPT archive when filtered by fa
 */
add_action('pre_get_posts', function($q){
    if (is_admin() || !$q->is_main_query()) return;

    // NOTE: these pretty URLs are still the case-study archive query, just with fa attached
    if ($q->is_post_type_archive('case-study')) {
        $slug = get_query_var('fa');
        if ($slug) {
            $q->set('tax_query', [[
                'taxonomy' => 'focus-area',
                'field'    => 'slug',
                'terms'    => sanitize_title($slug),
            ]]);
        }
    }
});

/**
 * Robustly detect focus-area slug from /case-studies/{slug}/
 * (works even when Elementor loses query_var context)
 */
function bb_cs_focus_slug_from_request() {
    global $wp_query;

    // 1) preferred: rewrite query var
    $slug = get_query_var('fa');

    // 2) Elementor sometimes loses context, but WP still has it in query_vars
    if (empty($slug) && isset($wp_query) && is_object($wp_query) && !empty($wp_query->query_vars['fa'])) {
        $slug = $wp_query->query_vars['fa'];
    }

    // 3) last resort: parse URL path /case-studies/{slug}/
    if (empty($slug) && !empty($_SERVER['REQUEST_URI'])) {
        $path  = wp_parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $path  = trim($path, '/');
        $parts = explode('/', $path);

        // parts[0] = case-studies, parts[1] = slug OR "page"
        if (!empty($parts[0]) && $parts[0] === 'case-studies' && !empty($parts[1]) && $parts[1] !== 'page') {
            $slug = sanitize_title($parts[1]);
        }
    }

    return $slug ? sanitize_title($slug) : '';
}

/**
 * Archive title output for Elementor "Archive Title" widget:
 * - filtered: term name
 * - unfiltered: "Making the complex clear."
 */
function bb_cs_resolved_archive_heading() {
    $slug = bb_cs_focus_slug_from_request();
    if ($slug) {
        $term = get_term_by('slug', $slug, 'focus-area');
        if ($term && !is_wp_error($term)) {
            return $term->name;
        }
    }
    return 'Making the complex clear.';
}

// Cover the common WordPress title sources Elementor may use
add_filter('get_the_archive_title', function($title){
    if (is_post_type_archive('case-study')) {
        return bb_cs_resolved_archive_heading();
    }
    return $title;
}, 9999);

add_filter('post_type_archive_title', function($title, $post_type){
    if ($post_type === 'case-study') {
        return bb_cs_resolved_archive_heading();
    }
    return $title;
}, 9999, 2);

/**
 * [focus_area_filter] list
 */
add_shortcode('focus_area_filter', function () {
    $tax = 'focus-area';

    $terms = get_terms([
        'taxonomy'   => $tax,
        'hide_empty' => false,
        'orderby'    => 'name',
    ]);

    if ( is_wp_error($terms) || empty($terms) ) return '';

    $current_slug = bb_cs_focus_slug_from_request();

    ob_start(); ?>
    <div class="fa-filter-wrap">
        <ul class="fa-list" aria-label="Focus areas">
            <?php foreach ($terms as $t): ?>
                <?php $url = trailingslashit( home_url( 'case-studies/' . $t->slug ) ); ?>
                <li>
                    <h3>
                        <a class="fa-link<?php echo ($current_slug === $t->slug) ? ' is-active' : ''; ?>"
                           href="<?php echo esc_url($url); ?>">
                            <?php echo esc_html($t->name); ?>
                        </a>
                    </h3>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php
    return ob_get_clean();
});

/**
 * Dropdown change helper (if you use .fa-select somewhere)
 */
add_action('wp_footer', function(){ ?>
<script>
document.addEventListener('change', function(e){
    if (!e.target.matches('.fa-select')) return;
    const url = e.target.value;
    if (url) window.location.href = url;
});
</script>
<?php });

/**
 * Elementor Query (if you use a single loop with Query ID = cs_filter)
 */
add_action('elementor/query/cs_filter', function( $query ){
    $query->set('post_type', 'case-study');

    $slug = bb_cs_focus_slug_from_request();
    if ($slug) {
        $query->set('tax_query', [[
            'taxonomy' => 'focus-area',
            'field'    => 'slug',
            'terms'    => $slug,
        ]]);
    }

    // for normal paged loops (not offset blocks)
    $paged = max(1, (int) get_query_var('paged'), (int) get_query_var('page'));
    if ($paged > 1) $query->set('paged', $paged);
});

/**
 * ACF image fallback chain for Case Studies loop cards.
 * Bind your Elementor Image widget to `hero_banner`.
 */
add_filter('acf/format_value/name=hero_banner', function ($value, $post_id, $field) {

    $to_id = function ($val) {
        if (empty($val)) return 0;
        if (is_numeric($val)) return (int) $val;
        if (is_array($val) && !empty($val['ID'])) return (int) $val['ID'];
        if (is_string($val)) {
            $id = attachment_url_to_postid($val);
            return $id ? (int) $id : 0;
        }
        return 0;
    };

    $id = $to_id($value);
    if ($id) return $id;

    $id = $to_id(function_exists('get_field') ? get_field('secondary_banner', $post_id) : 0);
    if ($id) return $id;

    $id = $to_id(function_exists('get_field') ? get_field('feature_image_3', $post_id) : 0);
    if ($id) return $id;

    $thumb = get_post_thumbnail_id($post_id);
    if ($thumb) return (int) $thumb;

    return $value;
}, 10, 3);

/**
 * [acf_image_meta]
 */
function get_acf_image_meta_shortcode($atts) {
    $atts = shortcode_atts([
        'field' => '',
        'meta'  => 'caption', // caption or description
    ], $atts);

    if (!$atts['field'] || !function_exists('get_field')) return '';

    $image = get_field($atts['field']);
    if (!$image || !isset($image['ID'])) return '';

    $attachment_id = $image['ID'];

    if ($atts['meta'] === 'description') {
        $attachment = get_post($attachment_id);
        return $attachment ? $attachment->post_content : '';
    }

    return wp_get_attachment_caption($attachment_id);
}
add_shortcode('acf_image_meta', 'get_acf_image_meta_shortcode');

/**
 * ------------------------------------------------------------
 * BLOCK QUERIES (1 / 3 / 2 / 3) with page-aware offsets
 * ------------------------------------------------------------
 */
function bb_cs_apply_block_query( $query, $ppp, $offset ) {
    $query->set('post_type', 'case-study');
    $query->set('posts_per_page', (int) $ppp);
    $query->set('orderby', 'date');
    $query->set('order', 'DESC');

    $paged = max( 1, (int) get_query_var('paged'), (int) get_query_var('page') );

    $page_size   = 9; // total across all blocks per page (1+3+2+3)
    $page_offset = ( ($paged - 1) * $page_size ) + (int) $offset;

    $query->set('offset', $page_offset);

    $slug = bb_cs_focus_slug_from_request();
    if ( $slug ) {
        $query->set('tax_query', [[
            'taxonomy' => 'focus-area',
            'field'    => 'slug',
            'terms'    => $slug,
        ]]);
    }

    // IMPORTANT: do NOT set 'paged' when using offset
}

add_action('elementor/query/cs_block_1', function($query){ bb_cs_apply_block_query($query, 1, 0); });
add_action('elementor/query/cs_block_2', function($query){ bb_cs_apply_block_query($query, 3, 1); });
add_action('elementor/query/cs_block_3', function($query){ bb_cs_apply_block_query($query, 2, 4); });
add_action('elementor/query/cs_block_4', function($query){ bb_cs_apply_block_query($query, 3, 6); });

/**
 * Pagination shortcode for the case-study archive
 * Works for:
 *  - /case-studies/page/2/
 *  - /case-studies/{slug}/page/2/
 */
add_shortcode('cs_archive_pagination', function () {
    if (!is_post_type_archive('case-study')) return '';

    global $wp_query;

    $current = max(1, (int) get_query_var('paged'), (int) get_query_var('page'));
    $total   = max(1, (int) $wp_query->max_num_pages);

    if ($total <= 1) return '';

    $slug = bb_cs_focus_slug_from_request();

    // Build base correctly for filtered/unfiltered
    if ($slug) {
        $base = trailingslashit( home_url("case-studies/{$slug}/") ) . 'page/%#%/';
    } else {
        $base = trailingslashit( home_url("case-studies/") ) . 'page/%#%/';
    }

    $links = paginate_links([
        'base'      => $base,
        'format'    => '',
        'current'   => $current,
        'total'     => $total,
        'type'      => 'array',
        'prev_text' => '‹ Prev',
        'next_text' => 'Next ›',
    ]);

    if (empty($links) || !is_array($links)) return '';

    $out = '<nav class="cs-pagination" aria-label="Case studies pagination"><ul class="page-numbers">';
    foreach ($links as $link) {
        $out .= '<li>' . $link . '</li>';
    }
    $out .= '</ul></nav>';

    return $out;
});

/**
 * Team ordering bits
 */
add_action('init', function () {
    foreach (['our-team','team'] as $pt) {
        if ( post_type_exists($pt) ) {
            add_post_type_support($pt, 'page-attributes');
        }
    }
}, 20);

add_action('elementor/query/team_order', function( $query ) {
    $query->set('orderby', ['menu_order' => 'ASC', 'date' => 'DESC']);
    $query->set('order', 'ASC');
});

add_action('pre_get_posts', function( $q ){
    if ( is_admin() || !$q->is_main_query() ) return;

    if ( $q->is_post_type_archive('our-team') || $q->is_post_type_archive('team') ) {
        $q->set('orderby', ['menu_order' => 'ASC', 'date' => 'DESC']);
        $q->set('order', 'ASC');
    }
});

/**
 * [team_prev_next]
 */
add_shortcode('team_prev_next', function () {
    if (!is_singular('our-team')) return '';

    $posts = get_posts([
        'post_type'      => 'our-team',
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'orderby'        => ['menu_order' => 'ASC', 'title' => 'ASC'],
        'order'          => 'ASC',
        'fields'         => 'ids',
        'suppress_filters' => false,
    ]);
    if (empty($posts) || count($posts) < 2) return '';

    $current_id = get_the_ID();
    $idx = array_search($current_id, $posts, true);
    if ($idx === false) return '';

    $prev_id = $posts[ ($idx - 1 + count($posts)) % count($posts) ];
    $next_id = $posts[ ($idx + 1) % count($posts) ];

    ob_start(); ?>
    <nav class="team-prev-next" aria-label="Team navigation">
        <a class="team-prev" href="<?php echo esc_url(get_permalink($prev_id)); ?>">
            <span class="chev" aria-hidden="true">‹</span>
            <span class="label">Meet <?php echo esc_html(get_the_title($prev_id)); ?></span>
        </a>
        <span class="team-div">//</span>
        <a class="team-next" href="<?php echo esc_url(get_permalink($next_id)); ?>">
            <span class="label">Meet <?php echo esc_html(get_the_title($next_id)); ?></span>
            <span class="chev" aria-hidden="true">›</span>
        </a>
    </nav>
    <?php
    return ob_get_clean();
});
