<?php

require_once('templates/single/job.php');
require_once('templates/single/candidate.php');
require_once('templates/title.php');

remove_filter( 'the_content', 'convert_smilies', 20 );

/* Load the parent style.css file */
function total_child_enqueue_parent_theme_style() {
	// Dynamically get version number of the parent stylesheet (lets browsers re-cache stylesheet when you update your theme)
	$version = '1.0';
	// Load the stylesheet
	wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css', array(), $version );

	// Load Total theme icon font (ticons). Total 6.x no longer enqueues it globally,
	// which broke the legacy social-icon widgets (e.g. footer "Get Connected"). Re-add it.
	$ticons = get_template_directory().'/assets/icons/font/ticons.min.css';
	if ( file_exists( $ticons ) ) {
		wp_enqueue_style( 'total-ticons', get_template_directory_uri().'/assets/icons/font/ticons.min.css', array(), $version );
	}

	wp_register_style( 'site-style', get_stylesheet_directory_uri().'/assets/css/main.css', array(), array() );
	wp_register_script( 'site-script', get_stylesheet_directory_uri().'/assets/js/app.js', array(), array(), true );

	wp_enqueue_style( 'site-style' );
	
}
add_action( 'wp_enqueue_scripts', 'total_child_enqueue_parent_theme_style' );

/* Child Theme Sidebars */
function utility_widgets() {
	register_sidebar(array(
            'name' => __('Top Bar', ''),
            'id' => 'top-bar-widgets',
            'description' => __('Very top of site', 'total'),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget' => '</div>',
            'before_title' => '<h4 class="widget-title">',
            'after_title' => '</h4>',
	));
	register_sidebar(array(
            'name' => __('Footer Bottom', ''),
            'id' => 'footer-bottom-widgets',
            'description' => __('Very bottom of site', 'total'),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget' => '</div>',
            'before_title' => '<h4 class="widget-title">',
            'after_title' => '</h4>',
	));
	register_sidebar(array(
		'name' => __('Single Job Sidebar', ''),
		'id' => 'single-job-sidebar',
		'description' => __('Single Job page sidebar', 'total'),
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget' => '</div>',
		'before_title' => '<h4 class="widget-title">',
		'after_title' => '</h4>',
	));
	register_sidebar(array(
		'name' => __('Employer Sidebar', ''),
		'id' => 'employer-sidebar',
		'description' => __('Employer page sidebar', 'total'),
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget' => '</div>',
		'before_title' => '<h4 class="widget-title">',
		'after_title' => '</h4>',
	));
}
function other_sidebars() {
}
add_action( 'widgets_init', 'utility_widgets', 100, 200 );
add_action( 'widgets_init', 'other_sidebars', 30, 200 );

add_filter( 'wpex_register_sidebars_array', function( $sidebars ) {
	$sidebars['page_sidebar'] = __( 'Page Sidebar', 'total' );
	return $sidebars;
} );
add_filter( 'wpex_register_sidebars_array', function( $sidebars ) {
	$sidebars['page_sidebar'] = __( 'Blog Sidebar', 'total' );
	return $sidebars;
} );
add_filter( 'wpex_register_sidebars_array', function( $sidebars ) {
	$sidebars['job_sidebar'] = __( 'Job Sidebar', 'total' );
	return $sidebars;
} );
add_filter( 'wpex_register_sidebars_array', function( $sidebars ) {
	$sidebars['job_sidebar'] = __( 'Main Sidebar - Short', 'total' );
	return $sidebars;
} );

function mdocs_matador_bullhorn_import_fields($fields)
{
	$fields = array(
		'customText4' => array(
			'type' => 'string',
			'saveas' => 'meta',
			'name' => 'red_seal_webcat',
		)
	);
	return $fields;
}
add_filter('matador_bullhorn_import_fields', 'mdocs_matador_bullhorn_import_fields');

add_filter( 'matador_the_jobs_description_allowed_tags', 'redseal_matador_the_jobs_description_allowed_tags', 1, 10 );
function redseal_matador_the_jobs_description_allowed_tags( $tags ) {
	$tags[img] = array(
		'src'    => array(),
		'title'  => array(),
		'alt'    => array(),
		'srcset' => array(),
		'height' => array(),
		'width'  => array(),
	);
	return $tags;
}

add_action('init', function(){
	if(isset($_GET['matador-apply']) && $_GET['matador-apply'] == 'complete'){
		// redirect
		header("Location: /apply/thankyou");
		die();
	}
});


function myprefix_custom_mobile_logo() {
	// Get header logo data
	$logo_url   = wpex_header_logo_url();
	$logo_title = wpex_header_logo_title(); ?>
	<a href="<?php echo esc_url( $logo_url ); ?>" title="<?php echo esc_attr( $logo_title ); ?>" rel="home" class="myprefix-mobile-site-logo">
		<img src="/wp-content/uploads/2019/08/logo-mobile3.png" alt="Mobile Logo" data-no-retina />
	</a>
<?php }
add_action( 'wpex_hook_site_logo_inner', 'myprefix_custom_mobile_logo', 99 );

//Landing page settings
add_filter( 'wpex_main_metaboxes_post_types', function( $types ) {
 
  // Add to my custom-type post type
  $types[] = 'l';
  $types[] = 'custom-type-2';
 
  // Return post types array
  return $types;
  
}, 20 );

/* Auto Process All Orders */
/**
 * Auto Complete all WooCommerce orders.
 */
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}

add_filter( 'job_manager_enable_job_archive_page', '__return_false' );
add_filter( 'get_job_listings_cache_results', '__return_false' );

// Intercept the shortcode’s WP_Query args and replace the normal "s" search
add_filter( 'get_job_listings_query_args', function( $query_args, $args ) {
    if ( ! empty( $args['search_keywords'] ) ) {
        $raw = trim( $args['search_keywords'] );

        // split on commas if present, otherwise on whitespace
        if ( strpos( $raw, ',' ) !== false ) {
            $pieces = preg_split( '/\s*,\s*/', $raw, -1, PREG_SPLIT_NO_EMPTY );
        } else {
            $pieces = preg_split( '/\s+/',      $raw, -1, PREG_SPLIT_NO_EMPTY );
        }

        // sanitize + dedupe
        $terms = array_unique( array_map( 'sanitize_text_field', $pieces ) );

        if ( $terms ) {
            // stash for our later WHERE-clause and turn off the normal "s" keyword search
            $query_args['wpjm_title_search'] = $terms;
            unset( $query_args['s'] );
        }
    }
    return $query_args;
}, 20, 2 );

// 2) When WP_Query runs, inject a WHERE clause so post_title LIKE term1 OR term2 …
add_filter( 'posts_where', function( $where, $wp_query ) {
    if ( is_admin() ) {
        return $where;
    }

    // only target the [jobs] queries
    if ( $wp_query->get( 'post_type' ) !== 'job_listing' ) {
        return $where;
    }
    $terms = $wp_query->get( 'wpjm_title_search' );
    if ( empty( $terms ) ) {
        return $where;
    }

    global $wpdb;
    $likes = [];
    foreach ( (array) $terms as $term ) {
        $likes[] = $wpdb->prepare( "{$wpdb->posts}.post_title LIKE %s", '%' . $wpdb->esc_like( $term ) . '%' );
    }

    if ( $likes ) {
        // require at least one of them
        $where .= ' AND ( ' . implode( ' OR ', $likes ) . ' ) ';
    }

    return $where;
}, 10, 2 );

// 1. Trigger the import
function wpai_cron_trigger_import() {
    wp_remote_get(
        'https://redsealrecruiting.com/wp-load.php?import_key=bm4-iJbCAs&import_id=1&action=trigger'
    );
}
add_action( 'wpai_cron_trigger_import', 'wpai_cron_trigger_import' );

// 2. Process the import in batches
function wpai_cron_process_import() {
    wp_remote_get(
        'https://redsealrecruiting.com/wp-load.php?import_key=bm4-iJbCAs&import_id=1&action=processing'
    );
}
add_action( 'wpai_cron_process_import', 'wpai_cron_process_import' );

add_filter('the_content', function ($content) {
    if (get_post_type() !== 'job_listing') return $content;

    // Remove style="" from any HTML tag
    return preg_replace('/(<[a-z0-9:-]+\b[^>]*?)\sstyle\s*=\s*(?:"[^"]*"|\'[^\']*\')/i', '$1', $content);
}, 20);

/**
 * WooCommerce Email: Show Job Posting/Closing dates before Order Summary
 */
add_action('woocommerce_email_before_order_table', function ( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for the "Completed order" email sent to the customer
    if ( ! $email || ! isset( $email->id ) || $email->id !== 'customer_completed_order' ) {
        return;
    }

    if ( ! $order instanceof WC_Order ) {
        return;
    }

    $date_format = get_option('date_format');
    $tz          = wp_timezone();
    $jobs_found  = [];

    // Helper: normalize date strings (e.g., '2025-07-24', timestamps) to localized display
    $fmt = function( $raw ) use ( $date_format, $tz ) {
        if ( empty( $raw ) ) return '';
        // If looks like a timestamp
        if ( is_numeric( $raw ) ) {
            $dt = (new DateTime())->setTimestamp( (int) $raw )->setTimezone( $tz );
            return wp_date( $date_format, $dt->getTimestamp(), $tz );
        }
        // If looks like YYYY-MM-DD (WPJM commonly stores like this)
        if ( preg_match('/^\d{4}-\d{2}-\d{2}$/', $raw) ) {
            try {
                $dt = new DateTime( $raw, $tz );
                return wp_date( $date_format, $dt->getTimestamp(), $tz );
            } catch ( Exception $e ) { /* fall through */ }
        }
        // Fallback: let WordPress try
        $ts = strtotime( $raw );
        return $ts ? wp_date( $date_format, $ts, $tz ) : esc_html( $raw );
    };

    // Collect job listings referenced by order items
    foreach ( $order->get_items() as $item ) {
        if ( ! $item instanceof WC_Order_Item_Product ) continue;

        $meta = $item->get_meta_data();
        $meta_map = [];
        foreach ( $meta as $m ) {
            $meta_map[ $m->key ] = $m->value;
        }

        // Common meta keys used by WC Paid Listings / WP Job Manager checkout
        $possible_keys = ['_job_id','_job_listing_id','job_id','job_listing_id'];
        $job_id = null;
        foreach ( $possible_keys as $key ) {
            if ( ! empty( $meta_map[ $key ] ) && absint( $meta_map[ $key ] ) ) {
                $job_id = absint( $meta_map[ $key ] );
                break;
            }
        }
        if ( ! $job_id ) continue;
        if ( get_post_type( $job_id ) !== 'job_listing' ) continue;

        $post              = get_post( $job_id );
        $posting_date_disp = $fmt( $post->post_date );

        // Closing date priority: job expiry, then application deadline (if you use it)
        $expiry_raw        = get_post_meta( $job_id, '_job_expires', true );
        $deadline_raw      = get_post_meta( $job_id, '_application_deadline', true );

        $closing_label = '';
        $closing_disp  = '';
        if ( ! empty( $expiry_raw ) ) {
            $closing_label = __( 'Job Closing Date', 'your-textdomain' );
            $closing_disp  = $fmt( $expiry_raw );
        } elseif ( ! empty( $deadline_raw ) ) {
            $closing_label = __( 'Application Deadline', 'your-textdomain' );
            $closing_disp  = $fmt( $deadline_raw );
        }

        $jobs_found[] = [
            'id'            => $job_id,
            'title'         => get_the_title( $job_id ),
            'posting_date'  => $posting_date_disp,
            'closing_label' => $closing_label,
            'closing_date'  => $closing_disp,
            'permalink'     => get_permalink( $job_id ),
        ];
    }

    if ( empty( $jobs_found ) ) return;

    // ===== Output =====
    if ( $plain_text ) {
        echo "\n";
        echo "—— Job Details ——\n";
        foreach ( $jobs_found as $j ) {
            echo sprintf( "%s (ID #%d)\n", $j['title'], $j['id'] );
            echo sprintf( "Posting Date: %s\n", $j['posting_date'] ?: '-' );
            if ( $j['closing_label'] ) {
                echo sprintf( "%s: %s\n", $j['closing_label'], $j['closing_date'] ?: '-' );
            }
            echo "\n";
        }
        echo "——————————————\n\n";
        return;
    }

    // HTML block styled to match Woo emails
    ?>
    <div style="margin:0 0 24px 0; padding:16px 20px; border:1px solid #e5e5e5; border-radius:4px;">
        <h2 style="margin:0 0 12px 0; font-size:18px; line-height:1.4;">
            <?php esc_html_e( 'Job details', 'your-textdomain' ); ?>
        </h2>
        <?php foreach ( $jobs_found as $j ) : ?>
            <div style="margin-bottom:12px;">
                <strong>
                    <a href="<?php echo esc_url( $j['permalink'] ); ?>" style="text-decoration:none;">
                        <?php echo esc_html( $j['title'] ); ?>
                    </a>
                </strong>
                <div><?php echo esc_html__( 'Posting Date', 'your-textdomain' ); ?>: <?php echo esc_html( $j['posting_date'] ?: '-' ); ?></div>
                <?php if ( $j['closing_label'] ) : ?>
                    <div><?php echo esc_html( $j['closing_label'] ); ?>: <?php echo esc_html( $j['closing_date'] ?: '-' ); ?></div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
}, 9, 4);

/**
 * Register Chart.js (loaded only when shortcode is used).
 */
function rsr_register_salary_chart_assets() {

    wp_register_script(
        'chartjs',
        'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.js',
        array(),
        '4.4.1',
        true
    );

    $rsr_chart_js_path = get_stylesheet_directory() . '/rsr-salary-chart.js';
    $rsr_chart_js_ver  = file_exists($rsr_chart_js_path) ? filemtime($rsr_chart_js_path) : false;

    wp_register_script(
        'rsr-salary-chart',
        get_stylesheet_directory_uri() . '/rsr-salary-chart.js',
        array('chartjs'),
        $rsr_chart_js_ver,
        true
    );

}
add_action('wp_enqueue_scripts','rsr_register_salary_chart_assets');


/**
 * Shortcode: [rsr_salary_table sheet="URL" mode="both"]
 */
function rsr_salary_table_shortcode($atts){

    $atts = shortcode_atts(
        array(
            'sheet' => '',
            'mode'  => 'both',
        ),
        $atts
    );

    if(empty($atts['sheet'])){
        return '<p>Salary data not available.</p>';
    }

    wp_enqueue_script('chartjs');
    wp_enqueue_script('rsr-salary-chart');


    /*
    -----------------------------
    CACHE CSV
    -----------------------------
    */

    $cache_key = 'rsr_salary_csv_' . md5($atts['sheet']);
    $csv       = get_transient($cache_key);

    if(false === $csv){

        $response = wp_remote_get(
            esc_url_raw($atts['sheet']),
            array('timeout'=>15)
        );

        if(is_wp_error($response)){
            return '<p>Unable to load salary data.</p>';
        }

        $csv = wp_remote_retrieve_body($response);

        if(!$csv){
            return '<p>No salary data found.</p>';
        }

        set_transient($cache_key,$csv,HOUR_IN_SECONDS);

    }

    $rows = array_map('str_getcsv', explode("\n", trim($csv)));

    if(empty($rows)){
        return '<p>No salary data found.</p>';
    }


    /*
    -----------------------------
    TITLE ROW
    -----------------------------
    */

    $title='';
    $first_row = reset($rows);

    if($first_row && count(array_filter($first_row)) === 1){
        $title = trim($first_row[0]);
        array_shift($rows);
    }

    $header = array_shift($rows);


    /*
    -----------------------------
    DETECT COLUMNS
    -----------------------------
    */

    $province_idx = null;
    $city_idx     = null;
    $wage_idx     = null;
    $comp_idx     = null;
    $date_idx     = null;

    $skip_cols = array();

    foreach($header as $i=>$name_raw){

        $name = trim($name_raw);

        if(null === $province_idx && strcasecmp($name,'Province')===0){
            $province_idx = $i;
        } elseif(strcasecmp($name,'Province')===0){
            $skip_cols[] = $i;
        }

        if(null === $city_idx && stripos($name,'City') !== false){
            $city_idx = $i;
        }

        if(null === $wage_idx && stripos($name,'Wage (number only') !== false){
            $wage_idx = $i;
            $skip_cols[] = $i;
        }

        if(null === $comp_idx && stripos($name,'Compensation') !== false){
            $comp_idx = $i;
        }

        if(null === $date_idx && stripos($name,'Date Collected') !== false){
            $date_idx = $i;
        }

        if(strcasecmp($name,'Next Raise')===0) $skip_cols[]=$i;
        if(strcasecmp($name,'Contact Person/Number')===0) $skip_cols[]=$i;
        if(strcasecmp($name,'Date Collected')===0) $skip_cols[]=$i;

        if(stripos($name,'City Wage')!==false){
            $skip_cols[]=$i;
        }
    }


    /*
    -----------------------------
    LARGE CITY LIST
    -----------------------------
    */

    $allowed_cities = array(
    'Toronto','Montreal','Calgary','Ottawa','Edmonton','Winnipeg','Mississauga','Vancouver','Brampton','Hamilton',
    'Surrey','Quebec City','Halifax','Laval','London','Markham','Vaughan','Gatineau','Saskatoon','Kitchener',
    'Longueuil','Burnaby','Windsor','Regina','Oakville','Richmond','Richmond Hill','Burlington','Oshawa','Sherbrooke',
    'Greater Sudbury','Abbotsford','Lévis','Coquitlam','Barrie','Saguenay','Kelowna','Guelph','Trois-Rivières','Whitby',
    'Cambridge','St. Catharines','Milton','Langley','Kingston','Ajax','Waterloo','Terrebonne','Saanich','St. John\'s',
    'Thunder Bay','Delta','Brantford','Chatham-Kent','Clarington','Red Deer','Nanaimo','Strathcona County','Pickering',
    'Lethbridge','Kamloops','Saint-Jean-sur-Richelieu','Niagara Falls','Cape Breton','Chilliwack','Victoria','Brossard',
    'Maple Ridge','North Vancouver','Newmarket','Repentigny','Peterborough','Saint-Jérôme','Moncton','Drummondville',
    'Kawartha Lakes','New Westminster','Prince George','Caledon','Airdrie','Wood Buffalo','Sault Ste. Marie','Sarnia',
    'Saint John','Granby','St. Albert','Norfolk County','Grande Prairie','Medicine Hat','Fredericton','Halton Hills',
    'Aurora','Port Coquitlam','Mirabel','Blainville','Saint-Hyacinthe','Welland','Belleville','North Bay'
    );


    /*
    -----------------------------
    BUILD DATA
    -----------------------------
    */

    $city_values=array();
    $prov_values=array();

    foreach($rows as $cols){

        if(empty(array_filter($cols))){
            continue;
        }

        $city = (null!==$city_idx && isset($cols[$city_idx])) ? trim($cols[$city_idx]) : '';
        $province = (null!==$province_idx && isset($cols[$province_idx])) ? trim($cols[$province_idx]) : '';

        /*
        -----------------------------
        DATE FILTER (last 2 years)
        -----------------------------
        */

        if(null!==$date_idx && isset($cols[$date_idx])){

            $date_raw = trim($cols[$date_idx]);

            if($date_raw){
                $timestamp = strtotime($date_raw);

                if($timestamp && $timestamp < strtotime('-2 years')){
                    continue;
                }
            }
        }

        /*
        -----------------------------
        CITY FILTER (chart only)
        -----------------------------
        */

        $city_for_chart = $city;

        if($city_for_chart && !in_array($city_for_chart,$allowed_cities,true)){
            $city_for_chart='';
        }

        $wage=null;

        if(null!==$wage_idx && isset($cols[$wage_idx])){

            $wage_str = trim($cols[$wage_idx]);

            if(''!==$wage_str){

                $wage_str = str_replace(array(',',' '),'',$wage_str);

                if(is_numeric($wage_str)){
                    $wage = (float)$wage_str;
                }
            }
        }

        if(null===$wage && null!==$comp_idx && isset($cols[$comp_idx])){
            $wage = rsr_parse_compensation_to_number($cols[$comp_idx]);
        }

        if(null!==$wage && ($wage<=0 || $wage>200)){
            $wage=null;
        }

        if(null===$wage){
            continue;
        }

        if($city_for_chart){
            $city_values[$city_for_chart][]=$wage;
        }

        if($province){
            $prov_values[$province][]=$wage;
        }
    }


    /*
    -----------------------------
    CITY AVERAGE + MEDIAN
    -----------------------------
    */

    $city_labels=array();
    $city_avg=array();
    $city_median=array();

    foreach($city_values as $city_name=>$values){

        sort($values);
        $count=count($values);

        if(!$count) continue;

        $avg=array_sum($values)/$count;

        $middle=floor(($count-1)/2);

        $median = ($count%2) ? $values[$middle] : ($values[$middle]+$values[$middle+1])/2;

        $city_labels[]=$city_name;
        $city_avg[]=$avg;
        $city_median[]=$median;
    }


    /*
    -----------------------------
    PROVINCE AVERAGE + MEDIAN
    -----------------------------
    */

    $prov_labels=array();
    $prov_avg=array();
    $prov_median=array();

    foreach($prov_values as $prov_name=>$values){

        sort($values);
        $count=count($values);

        if(!$count) continue;

        $avg=array_sum($values)/$count;

        $middle=floor(($count-1)/2);

        $median = ($count%2) ? $values[$middle] : ($values[$middle]+$values[$middle+1])/2;

        $prov_labels[]=$prov_name;
        $prov_avg[]=$avg;
        $prov_median[]=$median;
    }


    /*
    -----------------------------
    LIMIT CITY COUNT
    -----------------------------
    */

    $max_cities=12;

    $city_combined=array();

    foreach($city_labels as $i=>$label){
        $city_combined[]=array(
            'label'=>$label,
            'avg'=>$city_avg[$i],
            'median'=>$city_median[$i],
        );
    }

    usort($city_combined,function($a,$b){
        return $b['avg'] <=> $a['avg'];
    });

    $city_combined=array_slice($city_combined,0,$max_cities);

    $city_labels=array();
    $city_avg=array();
    $city_median=array();

    foreach($city_combined as $row){
        $city_labels[]=$row['label'];
        $city_avg[]=$row['avg'];
        $city_median[]=$row['median'];
    }


    /*
    -----------------------------
    FINAL PAYLOAD
    -----------------------------
    */

    $chart_payload=array(

        'city'=>array(
            'labels'=>$city_labels,
            'avg'=>$city_avg,
            'median'=>$city_median,
        ),

        'province'=>array(
            'labels'=>$prov_labels,
            'avg'=>$prov_avg,
            'median'=>$prov_median,
        ),
    );


    /*
    -----------------------------
    OUTPUT
    -----------------------------
    */

    ob_start();

    echo '<div class="rsr-salary-wrapper">';

    if('table' !== $atts['mode']){

        echo '<div class="rsr-salary-chart-container">';

        echo '<div class="rsr-salary-chart-panel">';
        echo '<h3 class="rsr-salary-chart-heading">City Average & Median Hourly</h3>';
        echo '<canvas id="rsr-salary-chart-city"></canvas>';
        echo '</div>';

        echo '<div class="rsr-salary-chart-panel">';
        echo '<h3 class="rsr-salary-chart-heading">Provincial Average & Median</h3>';
        echo '<canvas id="rsr-salary-chart-province"></canvas>';
        echo '</div>';

        echo '</div>';
    }


    if('chart' !== $atts['mode']){

        echo '<div class="rsr-salary-table-wrapper">';
        echo '<table class="rsr-salary-table">';

        echo '<thead>';

        $visible_cols = count($header) - count($skip_cols);

        if($title && $visible_cols > 0){

            echo '<tr class="rsr-salary-title-row">';
            echo '<th colspan="'.$visible_cols.'" class="rsr-salary-title">';
            echo esc_html($title);
            echo '</th></tr>';
        }

        echo '<tr>';

        foreach($header as $i=>$heading){

            if(in_array($i,$skip_cols,true)) continue;

            echo '<th>'.esc_html($heading).'</th>';
        }

        echo '</tr>';
        echo '</thead><tbody>';

        foreach($rows as $cols){

            if(empty(array_filter($cols))) continue;

            echo '<tr>';

            foreach($cols as $i=>$c){

                if(in_array($i,$skip_cols,true)) continue;

                echo '<td>'.esc_html($c).'</td>';
            }

            echo '</tr>';
        }

        echo '</tbody></table></div>';
    }


    if('table' !== $atts['mode']){

        echo '<script type="application/json" id="rsr-salary-chart-data">';
        echo wp_json_encode($chart_payload);
        echo '</script>';
    }

    echo '</div>';

    return ob_get_clean();

}
add_shortcode('rsr_salary_table','rsr_salary_table_shortcode');


/**
 * Parse compensation string safely.
 */
function rsr_parse_compensation_to_number($str){

    if(!is_string($str) || ''===trim($str)){
        return null;
    }

    $str = str_replace(array('–','—'),'-',$str);

    if(stripos($str,'/hr')===false && stripos($str,'hour')===false){
        return null;
    }

    preg_match_all('/\d+(?:\.\d+)?/',$str,$matches);

    if(empty($matches[0])){
        return null;
    }

    $numbers = array_map('floatval',$matches[0]);

    $numbers = array_filter($numbers,function($n){
        return $n>0 && $n<=200;
    });

    if(empty($numbers)){
        return null;
    }

    return array_sum($numbers)/count($numbers);
}

add_action( 'woocommerce_account_dashboard', 'rs_employer_dashboard_helper_message', 5 );
function rs_employer_dashboard_helper_message() {

    // Change this to your actual job submission page URL
    $job_post_url = site_url('/post-a-job/');

    ?>
    <p class="employer-helper-message">
        If you are here to post a job, you are already logged in.
        <a href="<?php echo esc_url( $job_post_url ); ?>">
            Click here to post a job
        </a>.
    </p>
    <?php
}

add_filter( 'submit_job_form_login_url', 'wpjms_redirect_login_url' );
function wpjms_redirect_login_url() {
  return 'https://redsealrecruiting.com/my-account/';
}

/**
 * WPJM: Pre-render initial jobs into the <ul> for [jobs show_filters="true"]
 * so jobs appear in View Source, while keeping AJAX filters + Load More working normally.
 */

/**
 * Store shortcode atts so we can detect show_filters on this render.
 */
add_filter( 'job_manager_jobs_shortcode_data_attributes', function ( $data_attributes, $atts ) {
	$GLOBALS['zaheer_wpjm_jobs_shortcode_atts'] = $atts;
	return $data_attributes;
}, 10, 2 );

/**
 * Inject initial server-rendered listings into the UL when show_filters=true.
 * AJAX will still run and can replace/append results normally.
 */
add_filter( 'job_manager_job_listings_output', function ( $output ) {

	if ( empty( $GLOBALS['zaheer_wpjm_jobs_shortcode_atts'] ) ) {
		return $output;
	}

	$atts = $GLOBALS['zaheer_wpjm_jobs_shortcode_atts'];

	// Only for show_filters=true mode (the mode that outputs an empty UL).
	if ( empty( $atts['show_filters'] ) ) {
		return $output;
	}

	// Must have the UL in the markup.
	$needle = '<ul class="job_listings">';
	if ( strpos( $output, $needle ) === false ) {
		return $output;
	}

	// If something already injected listings (or another plugin/theme), don't duplicate.
	if ( preg_match( '/<ul class="job_listings">\\s*<li\\b/i', $output ) ) {
		return $output;
	}

	// Build args similarly to WPJM's non-filter mode (first page only).
	$args = apply_filters(
		'job_manager_output_jobs_args',
		[
			'search_location'   => isset( $atts['location'] ) ? $atts['location'] : '',
			'search_keywords'   => isset( $atts['keywords'] ) ? $atts['keywords'] : '',
			'post_status'       => ! empty( $atts['post_status'] ) ? (array) $atts['post_status'] : [ 'publish' ],
			'search_categories' => ! empty( $atts['categories'] ) ? (array) $atts['categories'] : [],
			'job_types'         => ! empty( $atts['job_types'] ) ? (array) $atts['job_types'] : [],
			'orderby'           => ! empty( $atts['orderby'] ) ? $atts['orderby'] : 'featured',
			'order'             => ! empty( $atts['order'] ) ? $atts['order'] : 'DESC',
			'posts_per_page'    => ! empty( $atts['per_page'] ) ? absint( $atts['per_page'] ) : absint( get_option( 'job_manager_per_page', 10 ) ),
			'featured'          => array_key_exists( 'featured', $atts ) ? $atts['featured'] : null,
			'filled'            => array_key_exists( 'filled', $atts ) ? $atts['filled'] : null,
			'remote_position'   => array_key_exists( 'remote_position', $atts ) ? $atts['remote_position'] : null,
			'featured_first'    => ! empty( $atts['featured_first'] ),
		]
	);

	$jobs = get_job_listings( $args );

	ob_start();

	if ( $jobs && $jobs->have_posts() ) {
		while ( $jobs->have_posts() ) {
			$jobs->the_post();
			get_job_manager_template_part( 'content', \WP_Job_Manager_Post_Types::PT_LISTING );
		}
	} else {
		// If you prefer showing "No jobs found" immediately, keep this;
		// otherwise you can remove it and let AJAX show it.
		do_action( 'job_manager_output_jobs_no_results' );
	}

	wp_reset_postdata();

	$listings_html = ob_get_clean();

	// Inject listings directly into the empty UL.
	$output = str_replace(
		$needle,
		$needle . $listings_html,
		$output
	);

	return $output;

}, 20 );

/**
 * Always force "Red Seal Recruiting" as hiringOrganization in WPJM JobPosting schema
 * (works even if job has no company name set).
 */
add_filter( 'wpjm_get_job_listing_structured_data', 'wd_override_job_schema_company_name', 10, 2 );

function wd_override_job_schema_company_name( $data, $post ) {

	if ( empty( $data ) || ! is_array( $data ) ) {
		return $data;
	}

	// Ensure structure exists
	if ( empty( $data['hiringOrganization'] ) || ! is_array( $data['hiringOrganization'] ) ) {
		$data['hiringOrganization'] = [ '@type' => 'Organization' ];
	}

	$data['hiringOrganization']['name'] = 'Red Seal Recruiting';

	// Optional: keep identifier consistent too
	if ( empty( $data['identifier'] ) || ! is_array( $data['identifier'] ) ) {
		$data['identifier'] = [ '@type' => 'PropertyValue' ];
	}
	$data['identifier']['name'] = 'Red Seal Recruiting';

	return $data;
}