<?php
/**
 * jobtex functions and definitions
 *
 * @package WordPress
 * @subpackage Jobtex
 * @since Jobtex 1.2.24
 */

define( 'JOBTEX_THEME_VERSION', '1.2.24' );
define( 'JOBTEX_DEMO_MODE', false );

if ( ! isset( $content_width ) ) {
	$content_width = 660;
}

if ( ! function_exists( 'jobtex_setup' ) ) :
function jobtex_setup() {
	load_theme_textdomain( 'jobtex', get_template_directory() . '/languages' );
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	set_post_thumbnail_size( 1200, 750, true );
	
	register_nav_menus( array(
		'primary' => esc_html__( 'Primary Menu', 'jobtex' ),
		'mobile-primary' => esc_html__( 'Mobile Primary Menu', 'jobtex' ),
		'employer-menu' => esc_html__( 'Employer Menu', 'jobtex' ),
		'candidate-menu' => esc_html__( 'Candidate Menu', 'jobtex' ),
		'employee-menu' => esc_html__( 'Employee Menu', 'jobtex' ),
	) );
	
	add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) );
	add_theme_support( "woocommerce", array('gallery_thumbnail_image_width' => 410) );
	add_theme_support( 'wc-product-gallery-lightbox' );
	add_theme_support( 'wc-product-gallery-slider' );
	add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'gallery', 'status', 'audio', 'chat' ) );
	
	$color_scheme  = jobtex_get_color_scheme();
	$default_color = trim( $color_scheme[0], '#' );
	
	add_theme_support( 'custom-background', apply_filters( 'jobtex_custom_background_args', array(
		'default-color'      => $default_color,
		'default-attachment' => 'fixed',
	) ) );
	
	add_theme_support( 'customize-selective-refresh-widgets' );
	add_theme_support( 'wp-block-styles' );
	add_theme_support( 'align-wide' );
	add_theme_support( 'editor-styles' );
	add_theme_support( 'responsive-embeds' );
	add_editor_style( array( 'css/style-editor.css' ) );
}
endif;
add_action( 'after_setup_theme', 'jobtex_setup' );

function jobtex_get_fonts_url() {
    $fonts_url = '';
    $main_font = jobtex_get_config('main-font');
	$main_font = !empty($main_font) ? json_decode($main_font, true) : array();
	if ( !empty($main_font['fontfamily']) ) {
		$main_font_family = $main_font['fontfamily'];
		$main_font_weight = !empty($main_font['fontweight']) ? $main_font['fontweight'] : '400,500,600,700,800';
		$main_font_subsets = !empty($main_font['subsets']) ? $main_font['subsets'] : 'latin,latin-ext';
	} else {
		$main_font_family = 'Plus+Jakarta+Sans';
		$main_font_weight = '400,500,600,700,800';
		$main_font_subsets = 'latin,latin-ext';
	}
	$heading_font = jobtex_get_config('heading-font');
	$heading_font = !empty($heading_font) ? json_decode($heading_font, true) : array();
	if ( !empty($heading_font['fontfamily']) ) {
		$heading_font_family = $heading_font['fontfamily'];
		$heading_font_weight = !empty($heading_font['fontweight']) ? $heading_font['fontweight'] : '700';
		$heading_font_subsets = !empty($heading_font['subsets']) ? $heading_font['subsets'] : 'latin,latin-ext';
	} else {
		$heading_font_family = 'Plus+Jakarta+Sans';
		$heading_font_weight = '700';
		$heading_font_subsets = 'latin,latin-ext';
	}
	if ( $main_font_family == $heading_font_family ) {
		$font_weight = $main_font_weight.','.$heading_font_weight;
		$font_subsets = $main_font_subsets.','.$heading_font_subsets;
		$fonts = array( $main_font_family => array( 'weight' => $font_weight, 'subsets' => $font_subsets ) );
	} else {
		$fonts = array(
			$main_font_family => array( 'weight' => $main_font_weight, 'subsets' => $main_font_subsets ),
			$heading_font_family => array( 'weight' => $heading_font_weight, 'subsets' => $heading_font_subsets ),
		);
	}
	$font_families = array();
	$subset = array();
	foreach ($fonts as $key => $opt) {
		$font_families[] = $key.':'.$opt['weight'];
		$subset[] = $opt['subsets'];
	}
    $query_args = array( 'family' => implode( '|', $font_families ), 'subset' => urlencode( implode( ',', $subset ) ) );
	$protocol = is_ssl() ? 'https:' : 'http:';
    $fonts_url = add_query_arg( $query_args, $protocol .'//fonts.googleapis.com/css' );
    return esc_url( $fonts_url );
}

function jobtex_admin_enqueue_styles() {
  	wp_enqueue_style( 'jobtex-theme-fonts', jobtex_get_fonts_url(), array(), null );
	wp_enqueue_style( 'all-awesome', get_template_directory_uri() . '/css/all-awesome.css', array(), '5.11.2' );
	wp_enqueue_style( 'icomoon', get_template_directory_uri() . '/css/icon-font.css', array(), '1.0.0' );
	wp_enqueue_style( 'themify-icons', get_template_directory_uri() . '/css/themify-icons.css', array(), '1.0.0' );
}
add_action( 'admin_enqueue_scripts', 'jobtex_admin_enqueue_styles' );

function jobtex_enqueue_styles() {
  	wp_enqueue_style( 'jobtex-theme-fonts', jobtex_get_fonts_url(), array(), null );
	wp_enqueue_style( 'all-awesome', get_template_directory_uri() . '/css/all-awesome.css', array(), '5.11.2' );
	wp_enqueue_style( 'jobtex-icomoon', get_template_directory_uri() . '/css/icon-font.css', array(), '1.0.0' );
	wp_enqueue_style( 'themify-icons', get_template_directory_uri() . '/css/themify-icons.css', array(), '1.0.0' );
	wp_enqueue_style( 'animate', get_template_directory_uri() . '/css/animate.css', array(), '3.6.0' );
	if( is_rtl() ){
		wp_enqueue_style( 'bootstrap-rtl', get_template_directory_uri() . '/css/bootstrap.rtl.css', array(), '5.0.2' );
	} else {
		wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), '5.0.2' );
	}
	wp_enqueue_style( 'slick', get_template_directory_uri() . '/css/slick.css', array(), '1.8.0' );
	wp_enqueue_style( 'magnific-popup', get_template_directory_uri() . '/css/magnific-popup.css', array(), '1.1.0' );
	wp_enqueue_style( 'perfect-scrollbar', get_template_directory_uri() . '/css/perfect-scrollbar.css', array(), '0.6.12' );
	wp_enqueue_style( 'sliding-menu', get_template_directory_uri() . '/css/sliding-menu.min.css', array(), '0.3.0' );
	if( is_rtl() ){
		wp_enqueue_style( 'jobtex-template', get_template_directory_uri() . '/css/template.rtl.css', array(), '1.0' );
	} else {
		wp_enqueue_style( 'jobtex-template', get_template_directory_uri() . '/css/template.css', array(), '1.0' );
	}
	$custom_style = jobtex_custom_styles();
	if ( !empty($custom_style) ) {
		wp_add_inline_style( 'jobtex-template', $custom_style );
	}
	wp_enqueue_style( 'jobtex-style', get_template_directory_uri() . '/style.css', array(), '1.0' );
}
add_action( 'wp_enqueue_scripts', 'jobtex_enqueue_styles', 100 );

function jobtex_login_enqueue_styles() {
	wp_enqueue_style( 'all-awesome', get_template_directory_uri() . '/css/all-awesome.css', array(), '5.11.2' );
	wp_enqueue_style( 'jobtex-login-style', get_template_directory_uri() . '/css/login-style.css', array(), '1.0' );
}
add_action( 'login_enqueue_scripts', 'jobtex_login_enqueue_styles', 10 );

function jobtex_enqueue_scripts() {
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
	wp_enqueue_script( 'bootstrap-bundle', get_template_directory_uri() . '/js/bootstrap.bundle.min.js', array( 'jquery' ), '5.0.2', true );
	wp_enqueue_script( 'slick', get_template_directory_uri() . '/js/slick.min.js', array( 'jquery' ), '1.8.0', true );
	wp_register_script( 'countdown', get_template_directory_uri() . '/js/countdown.js', array( 'jquery' ), '20150315', true );
	wp_localize_script( 'countdown', 'jobtex_countdown_opts', array(
		'days' => esc_html__('Days', 'jobtex'),
		'hours' => esc_html__('Hrs', 'jobtex'),
		'mins' => esc_html__('Mins', 'jobtex'),
		'secs' => esc_html__('Secs', 'jobtex'),
	));
	wp_enqueue_script( 'jquery-magnific-popup', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js', array( 'jquery' ), '1.1.0', true );
	wp_enqueue_script( 'jquery-unveil', get_template_directory_uri() . '/js/jquery.unveil.js', array( 'jquery' ), '1.1.0', true );
	wp_enqueue_script( 'perfect-scrollbar', get_template_directory_uri() . '/js/perfect-scrollbar.jquery.min.js', array( 'jquery' ), '0.6.12', true );
	if ( jobtex_get_config('keep_header') ) {
		wp_enqueue_script( 'jquery-waypoints', get_template_directory_uri() . '/js/jquery.waypoints.min.js', array( 'jquery' ), '4.0.1', true );
		wp_enqueue_script( 'sticky', get_template_directory_uri() . '/js/sticky.min.js', array( 'jquery', 'jquery-waypoints' ), '4.0.1', true );
	}
	wp_enqueue_script( 'sliding-menu', get_template_directory_uri() . '/js/sliding-menu.js', array( 'jquery' ), '0.3.0', true );
	wp_register_script( 'jobtex-functions', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20150330', true );
	wp_localize_script( 'jobtex-functions', 'jobtex_ajax', array(
		'ajaxurl' => admin_url( 'admin-ajax.php' ),
		'previous' => esc_html__('Previous', 'jobtex'),
		'next' => esc_html__('Next', 'jobtex'),
		'menu_back_text' => esc_html__('Back', 'jobtex')
	));
	wp_enqueue_script( 'jobtex-functions' );
	wp_add_inline_script( 'jobtex-functions', "(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);" );
}
add_action( 'wp_enqueue_scripts', 'jobtex_enqueue_scripts', 1 );

function jobtex_search_form_modify( $html ) {
	return str_replace( 'class="search-submit"', 'class="search-submit screen-reader-text"', $html );
}
add_filter( 'get_search_form', 'jobtex_search_form_modify' );

function jobtex_get_config($name, $default = '') {
    global $jobtex_theme_options;
	if ( empty($jobtex_theme_options) ) {
		$jobtex_theme_options = get_option('jobtex_theme_options');
	}
    if ( isset($jobtex_theme_options[$name]) ) {
        return $jobtex_theme_options[$name];
    }
    return $default;
}

function jobtex_set_exporter_settings_option_keys($option_keys) {
	return array(
		'jobtex_theme_options',
		'elementor_disable_color_schemes',
		'elementor_disable_typography_schemes',
		'elementor_allow_tracking',
		'elementor_cpt_support',
		'wp_job_board_pro_settings',
		'wp_job_board_pro__job__fields_data',
		'wp_job_board_pro__employer__fields_data',
		'wp_job_board_pro__candidate__fields_data',
	);
}
add_filter( 'apus_exporter_ocdi_settings_option_keys', 'jobtex_set_exporter_settings_option_keys' );

function jobtex_disable_one_click_import() {
	return false;
}
add_filter('apus_frammework_enable_one_click_import', 'jobtex_disable_one_click_import');

function jobtex_widgets_init() {
	register_sidebar( array( 'name' => esc_html__( 'Sidebar Default', 'jobtex' ), 'id' => 'sidebar-default', 'description' => esc_html__( 'Add widgets here to appear in your Sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Jobs filter sidebar', 'jobtex' ), 'id' => 'jobs-filter-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Jobs filter top', 'jobtex' ), 'id' => 'jobs-filter-top-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Jobs filter topbar sidebar', 'jobtex' ), 'id' => 'jobs-filter-topbar-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Jobs filter sub topbar sidebar', 'jobtex' ), 'id' => 'jobs-filter-sub-topbar-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sub sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Jobs filter topbar sidebar v2', 'jobtex' ), 'id' => 'jobs-filter-topbar-sidebar-v2', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Jobs filter sub topbar sidebar v2', 'jobtex' ), 'id' => 'jobs-filter-sub-topbar-sidebar-v2', 'description' => esc_html__( 'Add widgets here to appear in your sub sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Job single sidebar', 'jobtex' ), 'id' => 'job-single-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Employers filter sidebar', 'jobtex' ), 'id' => 'employers-filter-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Employers filter top sidebar', 'jobtex' ), 'id' => 'employers-filter-top-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Employers filter top maps sidebar', 'jobtex' ), 'id' => 'employers-filter-top-maps-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Employer single sidebar', 'jobtex' ), 'id' => 'employer-single-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Candidates filter sidebar', 'jobtex' ), 'id' => 'candidates-filter-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Candidates filter top sidebar', 'jobtex' ), 'id' => 'candidates-filter-top-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Candidate single sidebar', 'jobtex' ), 'id' => 'candidate-single-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'User Profile sidebar', 'jobtex' ), 'id' => 'user-profile-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Blog sidebar', 'jobtex' ), 'id' => 'blog-sidebar', 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'jobtex' ), 'before_widget' => '<aside class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title"><span>', 'after_title' => '</span></h2>' ) );
	register_sidebar( array( 'name' => esc_html__( 'Header Mobile Bottom', 'jobtex' ), 'id' => 'header-mobile-bottom', 'description' => esc_html__( 'Add widgets here to appear in your header mobile.', 'jobtex' ), 'before_widget' => '<aside class="%2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="title"><span>', 'after_title' => '</span></h2>' ) );
}
add_action( 'widgets_init', 'jobtex_widgets_init' );

function jobtex_get_load_plugins() {
	$plugins[] = array( 'name' => esc_html__( 'Apus Framework For Themes', 'jobtex' ), 'slug' => 'apus-frame', 'required' => true, 'source' => get_template_directory() . '/inc/plugins/apus-frame.zip' );
	$plugins[] = array( 'name' => esc_html__( 'Elementor Page Builder', 'jobtex' ), 'slug' => 'elementor', 'required' => true );
	$plugins[] = array( 'name' => esc_html__( 'Cmb2', 'jobtex' ), 'slug' => 'cmb2', 'required' => true );
	$plugins[] = array( 'name' => esc_html__( 'MailChimp for WordPress', 'jobtex' ), 'slug' => 'mailchimp-for-wp', 'required' => true );
	$plugins[] = array( 'name' => esc_html__( 'Contact Form 7', 'jobtex' ), 'slug' => 'contact-form-7', 'required' => true );
	$plugins[] = array( 'name' => esc_html__( 'Woocommerce', 'jobtex' ), 'slug' => 'woocommerce', 'required' => true );
	$plugins[] = array( 'name' => esc_html__( 'WP Job Board Pro', 'jobtex' ), 'slug' => 'wp-job-board-pro', 'required' => true, 'source' => get_template_directory() . '/inc/plugins/wp-job-board-pro.zip' );
	$plugins[] = array( 'name' => esc_html__( 'WP Job Board Pro - WooCommerce Paid Listings', 'jobtex' ), 'slug' => 'wp-job-board-pro-wc-paid-listings', 'required' => true, 'source' => get_template_directory() . '/inc/plugins/wp-job-board-pro-wc-paid-listings.zip' );
	$plugins[] = array( 'name' => esc_html__( 'WP Private Message', 'jobtex' ), 'slug' => 'wp-private-message', 'required' => true, 'source' => get_template_directory() . '/inc/plugins/wp-private-message.zip' );
	$plugins[] = array( 'name' => esc_html__( 'One Click Demo Import', 'jobtex' ), 'slug' => 'one-click-demo-import', 'required' => false, 'force_activation' => false, 'force_deactivation' => false );
	$plugins[] = array( 'name' => esc_html__( 'Easy SVG Support', 'jobtex' ), 'slug' => 'easy-svg', 'required' => false, 'force_activation' => false, 'force_deactivation' => false );
	$config = array( 'id' => 'jobtex', 'default_path' => '', 'menu' => 'tgmpa-install-plugins', 'has_notices' => true, 'dismissable' => true, 'dismiss_msg' => '', 'is_automatic' => false, 'message' => '', 'strings' => array( 'bulk_install' => esc_html__( 'Install Selected Plugins', 'jobtex' ) ) );
	tgmpa( $plugins, $config );
}
add_action( 'tgmpa_register', 'jobtex_get_load_plugins' );

get_template_part( '/inc/plugins/class-tgm-plugin-activation' );
get_template_part( '/inc/functions-helper' );
get_template_part( '/inc/functions-frontend' );
get_template_part( '/inc/custom-header' );
get_template_part( '/inc/classes/megamenu' );
get_template_part( '/inc/classes/mobilemenu' );
require get_template_directory() . '/inc/template-tags.php';
get_template_part( '/inc/customizer/font/custom-controls' );
get_template_part( '/inc/customizer/customizer-custom-control' );
get_template_part( '/inc/customizer/customizer' );

if( jobtex_is_cmb2_activated() ) { get_template_part( '/inc/vendors/cmb2/page' ); }
if( jobtex_is_woocommerce_activated() ) { get_template_part( '/inc/vendors/woocommerce/functions' ); get_template_part( '/inc/vendors/woocommerce/customizer' ); }
if( jobtex_is_wp_job_board_pro_activated() ) {
	get_template_part( '/inc/vendors/wp-job-board-pro/customizer-job' );
	get_template_part( '/inc/vendors/wp-job-board-pro/customizer-employer' );
	get_template_part( '/inc/vendors/wp-job-board-pro/customizer-candidate' );
	get_template_part( '/inc/vendors/wp-job-board-pro/customizer-register' );
	get_template_part( '/inc/vendors/wp-job-board-pro/functions' );
	get_template_part( '/inc/vendors/wp-job-board-pro/functions-employer' );
	get_template_part( '/inc/vendors/wp-job-board-pro/functions-candidate' );
	get_template_part( '/inc/vendors/wp-job-board-pro/functions-job-display' );
	get_template_part( '/inc/vendors/wp-job-board-pro/functions-employer-display' );
	get_template_part( '/inc/vendors/wp-job-board-pro/functions-candidate-display' );
}
if ( jobtex_is_wp_job_board_pro_wc_paid_listings_activated() ) { get_template_part( '/inc/vendors/wp-job-board-pro-wc-paid-listings/functions' ); }

function jobtex_register_load_widget() {
	get_template_part( '/inc/widgets/custom_menu' );
	get_template_part( '/inc/widgets/recent_post' );
	get_template_part( '/inc/widgets/search' );
	get_template_part( '/inc/widgets/socials' );
	if ( did_action( 'elementor/loaded' ) ) { get_template_part( '/inc/widgets/elementor-template' ); }
	if ( jobtex_is_wp_job_board_pro_activated() ) {
		get_template_part( '/inc/widgets/candidate-contact-form' );
		get_template_part( '/inc/widgets/candidate-info' );
		get_template_part( '/inc/widgets/candidate-cv' );
		get_template_part( '/inc/widgets/candidate-buttons' );
		get_template_part( '/inc/widgets/candidate-socials' );
		get_template_part( '/inc/widgets/candidate-tags' );
		get_template_part( '/inc/widgets/employer-contact-form' );
		get_template_part( '/inc/widgets/employer-info' );
		get_template_part( '/inc/widgets/employer-maps' );
		get_template_part( '/inc/widgets/job-info' );
		get_template_part( '/inc/widgets/job-maps' );
		get_template_part( '/inc/widgets/job-tags' );
		get_template_part( '/inc/widgets/job-statistics' );
		get_template_part( '/inc/widgets/job-also-viewed' );
		get_template_part( '/inc/widgets/job-buttons' );
		get_template_part( '/inc/widgets/job-social-share' );
		get_template_part( '/inc/widgets/job-employer-info' );
		get_template_part( '/inc/widgets/job-contact-form' );
		get_template_part( '/inc/widgets/user-short-profile' );
	}
}
add_action( 'widgets_init', 'jobtex_register_load_widget' );

add_filter( 'gutenberg_use_widgets_block_editor', '__return_false' );
add_filter( 'use_widgets_block_editor', '__return_false' );

if ( jobtex_is_wp_private_message() ) { get_template_part( '/inc/vendors/wp-private-message/functions' ); }
get_template_part( '/inc/vendors/elementor/functions' );
get_template_part( '/inc/vendors/one-click-demo-import/functions' );
get_template_part( '/inc/custom-styles' );

// ============================================
// DIASPORAHUB API ENDPOINTS
// ============================================

// Helper function to get user from JWT token
function diasporahub_get_user_from_token($request) {
    $auth_header = $request->get_header('Authorization');
    if (!$auth_header) return null;
    $token = str_replace('Bearer ', '', $auth_header);
    $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null;
    $payload = json_decode(base64_decode($token_parts[1]), true);
    $username = $payload['name'] ?? '';
    return get_user_by('login', $username);
}

// Job Application Endpoint
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/apply', [
        'methods' => 'POST',
        'callback' => 'handle_job_application',
        'permission_callback' => '__return_true'
    ]);
});

function handle_job_application($request) {
    $params = $request->get_json_params();
    $job_id = sanitize_text_field($params['job_id']);
    $applicant_name = sanitize_text_field($params['applicant_name']);
    $applicant_email = sanitize_email($params['applicant_email']);
    $cover_letter = sanitize_textarea_field($params['cover_letter']);
    $resume_url = esc_url_raw($params['resume_url']);
    
    $job_post = get_post($job_id);
    $employer_id = $job_post->post_author;
    $employer_email = get_the_author_meta('user_email', $employer_id);
    
    $application_id = wp_insert_post([
        'post_title' => "Application for Job #$job_id from $applicant_name",
        'post_type' => 'job_application',
        'post_status' => 'private',
        'meta_input' => [
            '_job_id' => $job_id,
            '_applicant_name' => $applicant_name,
            '_applicant_email' => $applicant_email,
            '_cover_letter' => $cover_letter,
            '_resume_url' => $resume_url,
            '_status' => 'pending'
        ]
    ]);
    
    wp_mail($employer_email, "New Job Application", "You have a new application for your job listing.\n\nApplicant: $applicant_name\nEmail: $applicant_email\nCover Letter: $cover_letter\nResume: $resume_url");
    
    return rest_ensure_response(['success' => true, 'application_id' => $application_id, 'message' => 'Application submitted successfully']);
}

// Public Jobs Endpoint
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/public-jobs', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_public_jobs',
        'permission_callback' => '__return_true'
    ]);
});

function diasporahub_get_public_jobs($request) {
    $args = array( 'post_type' => 'job_listing', 'posts_per_page' => 50, 'post_status' => 'publish' );
    $jobs_query = get_posts($args);
    $jobs = array();
    foreach ($jobs_query as $job) {
        $company = get_post_meta($job->ID, '_job_employer_name', true);
        if (empty($company)) {
            $employer_id = get_post_meta($job->ID, '_job_employer_posted_by', true);
            if (!empty($employer_id)) {
                $employer_user = get_user_by('id', $employer_id);
                if ($employer_user) { $company = $employer_user->display_name; }
            }
        }
        if (empty($company)) { $company = 'DiasporaHub Employer'; }
        $logo = get_post_meta($job->ID, '_job_logo', true);
        $salary = get_post_meta($job->ID, '_job_salary', true);
        $jobs[] = array(
            'id' => $job->ID, 'title' => get_the_title($job), 'company' => $company, 'logo' => $logo,
            'salary' => $salary ?: 'Not specified', 'description' => wp_trim_words($job->post_content, 20),
            'link' => get_permalink($job), 'isUrgent' => get_post_meta($job->ID, '_job_urgent', true) === 'on',
            'isFeatured' => get_post_meta($job->ID, '_job_featured', true) === 'on'
        );
    }
    return rest_ensure_response($jobs);
}

// Public Login Endpoint
function diasporahub_register_public_login() {
    register_rest_route('diasporahub/v1', '/public-login', array( 'methods' => 'POST', 'callback' => 'diasporahub_handle_public_login', 'permission_callback' => '__return_true' ));
}
add_action('rest_api_init', 'diasporahub_register_public_login');

function diasporahub_handle_public_login($request) {
    $params = $request->get_json_params();
    $username = isset($params['username']) ? $params['username'] : '';
    $password = isset($params['password']) ? $params['password'] : '';
    if (empty($username) || empty($password)) { return array( 'success' => false, 'message' => 'Username and password are required' ); }
    $response = wp_remote_post('https://diasporahub.app/wp-json/api/v1/token', array( 'body' => json_encode(array( 'username' => $username, 'password' => $password )), 'headers' => array( 'Content-Type' => 'application/json' ), 'timeout' => 30 ));
    if (is_wp_error($response)) { return array( 'success' => false, 'message' => 'Login service error: ' . $response->get_error_message() ); }
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    $status = wp_remote_retrieve_response_code($response);
    if ($status === 200 && isset($data['jwt_token'])) { return array( 'success' => true, 'token' => $data['jwt_token'], 'username' => $username ); }
    return array( 'success' => false, 'message' => isset($data['error_description']) ? $data['error_description'] : 'Invalid username or password' );
}

// Employer Jobs Endpoint
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/employer/jobs', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_employer_jobs',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
});

function diasporahub_get_employer_jobs($request) {
    $user = diasporahub_get_user_from_token($request);
    if (!$user) { return new WP_REST_Response(['jobs' => []], 200); }
    $jobs = get_posts([ 'post_type' => 'job_listing', 'author' => $user->ID, 'posts_per_page' => -1, 'post_status' => ['publish', 'pending', 'draft'] ]);
    $jobs_data = [];
    foreach ($jobs as $job) {
        $jobs_data[] = [ 'id' => $job->ID, 'title' => $job->post_title, 'status' => $job->post_status, 'applications_count' => (int) get_post_meta($job->ID, '_applications_count', true), 'views_count' => (int) get_post_meta($job->ID, '_job_views_count', true), 'date' => $job->post_date ];
    }
    return new WP_REST_Response(['jobs' => $jobs_data], 200);
}

// Employer Stats Endpoint
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/employer/stats', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_employer_stats',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
});

function diasporahub_get_employer_stats($request) {
    $user = diasporahub_get_user_from_token($request);
    if (!$user) { return new WP_REST_Response([ 'total_jobs' => 0, 'total_applications' => 0, 'total_views' => 0, 'shortlisted' => 0 ], 200); }
    $jobs = get_posts([ 'post_type' => 'job_listing', 'author' => $user->ID, 'posts_per_page' => -1 ]);
    $total_jobs = count($jobs);
    $total_applications = 0;
    $total_views = 0;
    foreach ($jobs as $job) {
        $total_applications += (int) get_post_meta($job->ID, '_applications_count', true);
        $total_views += (int) get_post_meta($job->ID, '_job_views_count', true);
    }
    return new WP_REST_Response([ 'total_jobs' => $total_jobs, 'total_applications' => $total_applications, 'total_views' => $total_views, 'shortlisted' => 0 ], 200);
}

// Employer Dashboard Endpoint
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/employer/dashboard', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_employer_dashboard',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
});

function diasporahub_get_employer_dashboard($request) {
    $user = diasporahub_get_user_from_token($request);
    if (!$user) { return new WP_REST_Response(['error' => 'Unauthorized'], 401); }
    $args = [ 'post_type' => 'job_listing', 'author' => $user->ID, 'posts_per_page' => -1, 'post_status' => ['publish', 'pending', 'draft'] ];
    $jobs = get_posts($args);
    $jobs_data = [];
    $total_applications = 0;
    $total_views = 0;
    foreach ($jobs as $job) {
        $applications = get_post_meta($job->ID, '_job_applications_count', true);
        if (empty($applications)) { $applications = get_post_meta($job->ID, '_wpjb_application_count', true); }
        $views = get_post_meta($job->ID, '_job_views_count', true);
        if (empty($views)) { $views = get_post_meta($job->ID, '_wpjb_view_count', true); }
        $total_applications += (int) $applications;
        $total_views += (int) $views;
        $jobs_data[] = [ 'id' => $job->ID, 'title' => $job->post_title, 'status' => $job->post_status, 'applications_count' => (int) $applications, 'views_count' => (int) $views, 'posted_date' => $job->post_date ];
    }
    $employer_stats = [ 'total_jobs' => count($jobs), 'total_applications' => $total_applications, 'total_views' => $total_views, 'profile_views' => (int) get_user_meta($user->ID, '_profile_views', true) ?: 0 ];
    return new WP_REST_Response([ 'success' => true, 'stats' => $employer_stats, 'jobs' => $jobs_data ], 200);
}

// Notifications Table and Endpoints
function diasporahub_create_notifications_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'diasporahub_notifications';
    $sql = "CREATE TABLE IF NOT EXISTS $table_name ( id int(11) NOT NULL AUTO_INCREMENT, user_id int(11) NOT NULL, type varchar(50) NOT NULL, title varchar(255) NOT NULL, message text NOT NULL, link varchar(255) DEFAULT NULL, is_read tinyint(1) DEFAULT 0, created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) )";
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
add_action('init', 'diasporahub_create_notifications_table');

add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/notifications', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_notifications',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
    register_rest_route('diasporahub/v1', '/notifications/unread-count', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_unread_count',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
    register_rest_route('diasporahub/v1', '/notifications/mark-read/(?P<id>\d+)', [
        'methods' => 'POST',
        'callback' => 'diasporahub_mark_notification_read',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
});

function diasporahub_get_notifications($request) {
    $user = diasporahub_get_user_from_token($request);
    if (!$user) { return new WP_REST_Response(['notifications' => []], 200); }
    global $wpdb;
    $table_name = $wpdb->prefix . 'diasporahub_notifications';
    $notifications = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d ORDER BY created_at DESC LIMIT 50", $user->ID));
    $result = [];
    foreach ($notifications as $notif) {
        $result[] = [ 'id' => $notif->id, 'type' => $notif->type, 'title' => $notif->title, 'message' => $notif->message, 'is_read' => (bool) $notif->is_read, 'created_at' => $notif->created_at ];
    }
    return new WP_REST_Response(['notifications' => $result], 200);
}

function diasporahub_get_unread_count($request) {
    $user = diasporahub_get_user_from_token($request);
    if (!$user) { return new WP_REST_Response(['unread_count' => 0], 200); }
    global $wpdb;
    $table_name = $wpdb->prefix . 'diasporahub_notifications';
    $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_name WHERE user_id = %d AND is_read = 0", $user->ID));
    return new WP_REST_Response(['unread_count' => (int) $count], 200);
}

function diasporahub_mark_notification_read($request) {
    $user = diasporahub_get_user_from_token($request);
    $id = $request['id'];
    global $wpdb;
    $table_name = $wpdb->prefix . 'diasporahub_notifications';
    $wpdb->update($table_name, ['is_read' => 1], ['id' => $id, 'user_id' => $user->ID]);
    return new WP_REST_Response(['success' => true], 200);
}

if (!function_exists('diasporahub_create_notification')) {
    function diasporahub_create_notification($user_id, $type, $title, $message, $link = null) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'diasporahub_notifications';
        $wpdb->insert($table_name, [ 'user_id' => $user_id, 'type' => $type, 'title' => $title, 'message' => $message, 'link' => $link, 'created_at' => current_time('mysql') ]);
    }
}

// Messages Endpoints (WP Private Message - Custom Post Type)
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/messages/conversations', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_conversations_cpt',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
    register_rest_route('diasporahub/v1', '/messages/conversation/(?P<user_id>\d+)', [
        'methods' => 'GET',
        'callback' => 'diasporahub_get_conversation_cpt',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
    register_rest_route('diasporahub/v1', '/messages/send', [
        'methods' => 'POST',
        'callback' => 'diasporahub_send_message_cpt',
        'permission_callback' => function() { return get_current_user_id() > 0; }
    ]);
});

function diasporahub_get_conversations_cpt($request) {
    $user = diasporahub_get_user_from_token($request);
    if (!$user) { return new WP_REST_Response(['error' => 'Unauthorized'], 401); }
    $args = [ 'post_type' => 'private_message', 'posts_per_page' => -1, 'meta_query' => [ 'relation' => 'OR', [ 'key' => '_sender_id', 'value' => $user->ID, 'compare' => '=' ], [ 'key' => '_receiver_id', 'value' => $user->ID, 'compare' => '=' ] ] ];
    $messages = get_posts($args);
    $conversations = [];
    foreach ($messages as $msg) {
        $sender_id = (int) get_post_meta($msg->ID, '_sender_id', true);
        $receiver_id = (int) get_post_meta($msg->ID, '_receiver_id', true);
        $other_user_id = ($sender_id == $user->ID) ? $receiver_id : $sender_id;
        if (!isset($conversations[$other_user_id])) {
            $other_user = get_userdata($other_user_id);
            if ($other_user) {
                $conversations[$other_user_id] = [ 'user_id' => $other_user_id, 'user_name' => $other_user->display_name, 'user_avatar' => get_avatar_url($other_user_id), 'last_message' => $msg->post_content, 'last_message_time' => $msg->post_date, 'unread_count' => 0 ];
            }
        }
        if ($receiver_id == $user->ID) {
            $is_read = get_post_meta($msg->ID, '_is_read', true);
            if ($is_read !== 'yes') { $conversations[$other_user_id]['unread_count']++; }
        }
    }
    return new WP_REST_Response([ 'success' => true, 'conversations' => array_values($conversations) ], 200);
}

function diasporahub_get_conversation_cpt($request) {
    $user = diasporahub_get_user_from_token($request);
    $other_user_id = (int) $request['user_id'];
    if (!$user) { return new WP_REST_Response(['error' => 'Unauthorized'], 401); }
    $args = [ 'post_type' => 'private_message', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'ASC', 'meta_query' => [ 'relation' => 'AND', [ 'relation' => 'OR', [ 'key' => '_sender_id', 'value' => [$user->ID, $other_user_id], 'compare' => 'IN' ], [ 'key' => '_receiver_id', 'value' => [$user->ID, $other_user_id], 'compare' => 'IN' ] ] ] ];
    $messages = get_posts($args);
    $result = [];
    foreach ($messages as $msg) {
        $sender_id = (int) get_post_meta($msg->ID, '_sender_id', true);
        $result[] = [ 'id' => $msg->ID, 'sender_id' => $sender_id, 'receiver_id' => (int) get_post_meta($msg->ID, '_receiver_id', true), 'message' => $msg->post_content, 'is_read' => get_post_meta($msg->ID, '_is_read', true) === 'yes', 'created_at' => $msg->post_date, 'is_mine' => $sender_id == $user->ID ];
        if ($sender_id == $other_user_id && !get_post_meta($msg->ID, '_is_read', true)) { update_post_meta($msg->ID, '_is_read', 'yes'); }
    }
    return new WP_REST_Response([ 'success' => true, 'messages' => $result ], 200);
}

function diasporahub_send_message_cpt($request) {
    $user = diasporahub_get_user_from_token($request);
    $params = $request->get_json_params();
    if (!$user) { return new WP_REST_Response(['error' => 'Unauthorized'], 401); }
    $receiver_id = (int) $params['receiver_id'];
    $message = sanitize_textarea_field($params['message']);
    if (empty($receiver_id) || empty($message)) { return new WP_REST_Response(['error' => 'Receiver ID and message are required'], 400); }
    $post_id = wp_insert_post([ 'post_title' => 'Private Message from ' . $user->display_name, 'post_content' => $message, 'post_type' => 'private_message', 'post_status' => 'publish', 'post_author' => $user->ID ]);
    if ($post_id) {
        update_post_meta($post_id, '_sender_id', $user->ID);
        update_post_meta($post_id, '_receiver_id', $receiver_id);
        update_post_meta($post_id, '_is_read', 'no');
        diasporahub_create_notification($receiver_id, 'message', 'New Message', $user->display_name . ' sent you a message');
        return new WP_REST_Response([ 'success' => true, 'message_id' => $post_id, 'message' => $message, 'created_at' => current_time('mysql'), 'is_mine' => true ], 200);
    }
    return new WP_REST_Response(['error' => 'Failed to send message'], 500);
}

// DEBUG ENDPOINT - Check messages in database
add_action('rest_api_init', function() {
    register_rest_route('diasporahub/v1', '/debug-all-messages', [
        'methods' => 'GET',
        'callback' => 'diasporahub_debug_all_messages',
        'permission_callback' => '__return_true'
    ]);
});

function diasporahub_debug_all_messages() {
    global $wpdb;
    
    // Check custom post type 'private_message'
    $args = array(
        'post_type' => 'private_message',
        'posts_per_page' => 20,
        'post_status' => 'any'
    );
    
    $posts = get_posts($args);
    $post_messages = array();
    
    foreach ($posts as $post) {
        $post_messages[] = array(
            'id' => $post->ID,
            'title' => $post->post_title,
            'content' => $post->post_content,
            'status' => $post->post_status,
            'author' => $post->post_author,
            'sender_id' => get_post_meta($post->ID, '_sender_id', true),
            'receiver_id' => get_post_meta($post->ID, '_receiver_id', true),
            'is_read' => get_post_meta($post->ID, '_is_read', true)
        );
    }
    
    // Also check wppm_messages table if it exists
    $table_name = $wpdb->prefix . 'wppm_messages';
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
    
    $table_messages = array();
    if ($table_exists) {
        $table_messages = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 20");
    }
    
    return array(
        'custom_post_type_messages' => $post_messages,
        'wppm_table_exists' => $table_exists,
        'wppm_table_messages' => $table_messages,
        'current_user_id' => get_current_user_id(),
        'current_user_login' => wp_get_current_user()->user_login
    );
}

