<?php
/**
 * Machine Repair functions and definitions
 *
 * @package Machine Repair
 */

if ( ! defined( 'MACHINE_REPAIR_VERSION' ) ) {
	// Replace the version number of the theme on each release.
	define( 'MACHINE_REPAIR_VERSION', '1.0.0' );
}

function machine_repair_setup() {

	load_theme_textdomain( 'machine-repair', get_template_directory() . '/languages' );
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'woocommerce' );
	add_theme_support( "align-wide" );
	add_theme_support( "responsive-embeds" );

	register_nav_menus(
		array(
			'menu-1' => esc_html__( 'Primary', 'machine-repair' ),
			'social-menu' => esc_html__('Social Menu', 'machine-repair'),
		)
	);

	add_theme_support(
		'html5',
		array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
			'style',
			'script',
		)
	);

	add_theme_support(
		'custom-background',
		apply_filters(
			'machine_repair_custom_background_args',
			array(
				'default-color' => '#ffffff',
				'default-image' => '',
			)
		)
	);

	add_theme_support( 'customize-selective-refresh-widgets' );

	add_theme_support(
		'custom-logo',
		array(
			'height'      => 250,
			'width'       => 250,
			'flex-width'  => true,
			'flex-height' => true,
		)
	);

    add_theme_support( 'post-formats', array(
        'image',
        'video',
        'gallery',
        'audio', 
    ));
	
}
add_action( 'after_setup_theme', 'machine_repair_setup' );

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function machine_repair_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'machine_repair_content_width', 640 );
}
add_action( 'after_setup_theme', 'machine_repair_content_width', 0 );

add_filter( 'woocommerce_enable_setup_wizard', '__return_false' );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function machine_repair_widgets_init() {
	register_sidebar(
		array(
			'name'          => esc_html__( 'Sidebar', 'machine-repair' ),
			'id'            => 'sidebar-1',
			'description'   => esc_html__( 'Add widgets here.', 'machine-repair' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => esc_html__( 'Footer 1', 'machine-repair' ),
			'id'            => 'footer-1',
			'description'   => esc_html__( 'Add widgets here.', 'machine-repair' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => esc_html__( 'Footer 2', 'machine-repair' ),
			'id'            => 'footer-2',
			'description'   => esc_html__( 'Add widgets here.', 'machine-repair' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => esc_html__( 'Footer 3', 'machine-repair' ),
			'id'            => 'footer-3',
			'description'   => esc_html__( 'Add widgets here.', 'machine-repair' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);
}
add_action( 'widgets_init', 'machine_repair_widgets_init' );


function machine_repair_social_menu()
    {
        if (has_nav_menu('social-menu')) :
            wp_nav_menu(array(
                'theme_location' => 'social-menu',
                'container' => 'ul',
                'menu_class' => 'social-menu menu',
                'menu_id'  => 'menu-social',
            ));
        endif;
    }


/**
 * Enqueue scripts and styles.
 */

function machine_repair_scripts() {
    // Google Fonts
    $query_args = array(
        'family' => 'Fira+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900',
        'display' => 'swap',
    );
    wp_enqueue_style('machine-repair-google-fonts', add_query_arg($query_args, 'https://fonts.googleapis.com/css'), array(), null);

    // Font Awesome CSS
    wp_enqueue_style('font-awesome-6', get_template_directory_uri() . '/revolution/assets/vendors/font-awesome-6/css/all.min.css', array(), '6.7.2');

    // Owl Carousel CSS
    wp_enqueue_style('owl-carousel-style', get_template_directory_uri() . '/revolution/assets/css/owl.carousel.css', array(), '2.3.4');

    // Wow script.
	wp_enqueue_script( 'wow-jquery', get_template_directory_uri() . '/revolution/assets/js/wow.js', array('jquery'),'' ,true );
	// Animate CSS
	wp_enqueue_style( 'animate-style', get_template_directory_uri() . '/revolution/assets/css/animate.css' );
    
    // Main stylesheet
    wp_enqueue_style('machine-repair-style', get_stylesheet_uri(), array(), wp_get_theme()->get('Version'));

    // Add custom inline styles
	require get_parent_theme_file_path('/custom-style.php');
	wp_add_inline_style('machine-repair-style', $machine_repair_custom_css);

    // RTL styles if needed
    wp_style_add_data('machine-repair-style', 'rtl', 'replace');

    // Navigation script
    wp_enqueue_script('machine-repair-navigation', get_template_directory_uri() . '/js/navigation.js', array(), wp_get_theme()->get('Version'), true);

    // Owl Carousel script
    wp_enqueue_script('owl-carousel-jquery', get_template_directory_uri() . '/revolution/assets/js/owl.carousel.js', array('jquery'), '2.3.4', true);

    // Custom script
    wp_enqueue_script('machine-repair-custom-js', get_template_directory_uri() . '/revolution/assets/js/custom.js', array('jquery'), wp_get_theme()->get('Version'), true);

    // Comments reply script
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}
add_action('wp_enqueue_scripts', 'machine_repair_scripts');

if (!function_exists('machine_repair_related_post')) :
    /**
     * Display related posts from same category
     *
     */

    function machine_repair_related_post($post_id){        
        $machine_repair_categories = get_the_category($post_id);
        if ($machine_repair_categories) {
            $machine_repair_category_ids = array();
            $machine_repair_category = get_category($machine_repair_category_ids);
            $machine_repair_categories = get_the_category($post_id);
            foreach ($machine_repair_categories as $machine_repair_category) {
                $machine_repair_category_ids[] = $machine_repair_category->term_id;
            }
            $count = $machine_repair_category->category_count;
            if ($count > 1) { ?>

         	<?php
		$machine_repair_related_post_wrap = absint(get_theme_mod('machine_repair_enable_related_post', 1));
		if($machine_repair_related_post_wrap == 1){ ?>
                <div class="related-post">
                    
                    <h2 class="post-title"><?php esc_html_e(get_theme_mod('machine_repair_related_post_text', __('Related Post', 'machine-repair'))); ?></h2>
                    <?php
                    $machine_repair_cat_post_args = array(
                        'category__in' => $machine_repair_category_ids,
                        'post__not_in' => array($post_id),
                        'post_type' => 'post',
                        'posts_per_page' =>  get_theme_mod( 'machine_repair_related_post_count', '3' ),
                        'post_status' => 'publish',
						'orderby'           => 'rand',
                        'ignore_sticky_posts' => true
                    );
                    $machine_repair_featured_query = new WP_Query($machine_repair_cat_post_args);
                    ?>
                    <div class="rel-post-wrap">
                        <?php
                        if ($machine_repair_featured_query->have_posts()) :

                        while ($machine_repair_featured_query->have_posts()) : $machine_repair_featured_query->the_post();
                            ?>

                            <div class="card-item rel-card-item">
								<div class="card-content">
                                    <?php if ( has_post_thumbnail() ) { ?>
                                        <div class="card-media">
                                            <?php machine_repair_post_thumbnail(); ?>
                                        </div>
                                    <?php } else {
                                        // Fallback default image
                                        $machine_repair_default_post_thumbnail = get_template_directory_uri() . '/revolution/assets/images/plans1.png';
                                        echo '<img class="default-post-img" src="' . esc_url( $machine_repair_default_post_thumbnail ) . '" alt="' . esc_attr( get_the_title() ) . '">';
                                    } ?>
									<div class="entry-title">
										<h3>
											<a href="<?php the_permalink() ?>">
												<?php the_title(); ?>
											</a>
										</h3>
									</div>
									<div class="entry-meta">
                                        <?php
                                        machine_repair_posted_on();
                                        machine_repair_posted_by();
                                        ?>
                                    </div>
								</div>
							</div>
                        <?php
                        endwhile;
                        ?>
                <?php
                endif;
                wp_reset_postdata();
                ?>
                </div>
                <?php } ?>
                <?php
            }
        }
    }
endif;
add_action('machine_repair_related_posts', 'machine_repair_related_post', 10, 1);

/**
 * Checkbox sanitization callback example.
 *
 * Sanitization callback for 'checkbox' type controls. This callback sanitizes `$checked`
 * as a boolean value, either TRUE or FALSE.
 */
function machine_repair_sanitize_checkbox($checked)
{
    // Boolean check.
    return ((isset($checked) && true == $checked) ? true : false);
}

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/revolution/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/revolution/inc/template-tags.php';

/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/revolution/inc/template-functions.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/revolution/inc/customizer.php';

/**
 * Breadcrumb File.
 */
require get_template_directory() . '/revolution/inc/breadcrumbs.php';


/**
 * Custom typography options for this theme.
 */
require get_template_directory() . '/revolution/inc/typography-options.php';

//////////////////////////////////////////////   Function for Translation Error   //////////////////////////////////////////////////////
function machine_repair_enqueue_function() {

    /**
    * GET START.
    */
    require get_template_directory() . '/getstarted/machine_repair_about_page.php';

    /**
    * DEMO IMPORT.
    */
    require get_template_directory() . '/demo-import/machine_repair_config_file.php';

    
    define('MACHINE_REPAIR_FREE_SUPPORT',__('https://www.revolutionwp.com/products/free-machine-wordpress-theme','machine-repair'));
    define('MACHINE_REPAIR_PRO_SUPPORT',__('https://www.revolutionwp.com/pages/community/','machine-repair'));
    define('MACHINE_REPAIR_REVIEW',__('https://wordpress.org/support/theme/machine-repair/reviews/#new-post','machine-repair'));
    define('MACHINE_REPAIR_BUY_NOW',__('https://www.revolutionwp.com/products/machine-repair-wordpress-theme','machine-repair'));
    define('MACHINE_REPAIR_LIVE_DEMO',__('https://demo.revolutionwp.com/machine-repair-pro/','machine-repair'));
    define('MACHINE_REPAIR_PRO_DOC',__('https://demo.revolutionwp.com/wpdocs/machine-repair-pro/','machine-repair'));
    define('MACHINE_REPAIR_LITE_DOC',__('https://demo.revolutionwp.com/wpdocs/machine-repair-free/','machine-repair'));
    define('MACHINE_REPAIR_BUNDLE',__('https://www.revolutionwp.com/products/wordpress-theme-bundle','machine-repair'));
    
}
add_action( 'after_setup_theme', 'machine_repair_enqueue_function' );

/**
 * Load Jetpack compatibility file.
 */
if ( defined( 'JETPACK__VERSION' ) ) {
	require get_template_directory() . '/revolution/inc/jetpack.php';

}

function machine_repair_remove_customize_register() {
    global $wp_customize;

    $wp_customize->remove_setting( 'display_header_text' );
    $wp_customize->remove_control( 'display_header_text' );

}

add_action( 'customize_register', 'machine_repair_remove_customize_register', 11 );


/************************************************************************************/
// //////////////////////////////////////////////

/**
 * WooCommerce custom filters
 */
add_filter('loop_shop_columns', 'machine_repair_loop_columns');

if (!function_exists('machine_repair_loop_columns')) {

	function machine_repair_loop_columns() {

		$machine_repair_columns = get_theme_mod( 'machine_repair_per_columns', 3 );

		return $machine_repair_columns;
	}
}

/************************************************************************************/

add_filter( 'loop_shop_per_page', 'machine_repair_per_page', 20 );

function machine_repair_per_page( $machine_repair_cols ) {

  	$machine_repair_cols = get_theme_mod( 'machine_repair_product_per_page', 9 );

	return $machine_repair_cols;
}

/************************************************************************************/

add_filter( 'woocommerce_output_related_products_args', 'machine_repair_products_args' );

function machine_repair_products_args( $machine_repair_args ) {

    $machine_repair_args['posts_per_page'] = get_theme_mod( 'custom_related_products_number', 6 );

    $machine_repair_args['columns'] = get_theme_mod( 'custom_related_products_number_per_row', 3 );

    return $machine_repair_args;
}

/************************************************************************************/

/**
 * Custom logo
 */

function machine_repair_custom_css() {
?>
	<style type="text/css" id="custom-theme-colors" >
        :root {
           
            --machine_repair_logo_width: <?php echo absint(get_theme_mod('machine_repair_logo_width')); ?> ;   
        }
        .site-branding img {
            max-width:<?php echo esc_html(get_theme_mod('machine_repair_logo_width')); ?>px ;    
        }         
	</style>
<?php
}
add_action( 'wp_head', 'machine_repair_custom_css' );

function machine_repair_sanitize_choices( $input, $setting ) {
    global $wp_customize; 
    $control = $wp_customize->get_control( $setting->id ); 
    if ( array_key_exists( $input, $control->choices ) ) {
        return $input;
    } else {
        return $setting->default;
    }
}

//Excerpt 
function machine_repair_excerpt_function($machine_repair_excerpt_count = 35) {
    $machine_repair_excerpt = get_the_excerpt();
    $machine_repair_text_excerpt = wp_strip_all_tags($machine_repair_excerpt);
    $machine_repair_excerpt_limit = (int) get_theme_mod('machine_repair_excerpt_limit', $machine_repair_excerpt_count);
    $machine_repair_words = preg_split('/\s+/', $machine_repair_text_excerpt); 
    $machine_repair_trimmed_words = array_slice($machine_repair_words, 0, $machine_repair_excerpt_limit);
    $machine_repair_theme_excerpt = implode(' ', $machine_repair_trimmed_words);

    return $machine_repair_theme_excerpt;
}

// Add admin notice
function machine_repair_admin_notice() { 
    global $pagenow;
    $machine_repair_theme_args      = wp_get_theme();
    $machine_repair_meta            = get_option( 'machine_repair_admin_notice' );
    $name            = $machine_repair_theme_args->__get( 'Name' );
    $machine_repair_current_screen  = get_current_screen();

    if( !$machine_repair_meta ){
	    if( is_network_admin() ){
	        return;
	    }

	    if( ! current_user_can( 'manage_options' ) ){
	        return;
	    } 
		
		if( $machine_repair_current_screen->base !== 'appearance_page_machine_repair_guide' && 
            $machine_repair_current_screen->base !== 'toplevel_page_machinerepair-demoimport' ) { ?>

            <div class="notice notice-success machine-repair-welcome-notice">
                <p class="machine-repair-dismiss-link">
                    <strong>
                        <a href="<?php echo esc_url( add_query_arg( 'machine_repair_admin_notice', '1' ) ); ?>">
                            <?php esc_html_e( 'Dismiss', 'machine-repair' ); ?>
                        </a>
                    </strong>
                </p>

                <div class="machine-repair-welcome-notice-wrap">
                    <h2 class="machine-repair-notice-title">
                        <span class="dashicons dashicons-admin-home"></span> 
                        <?php 
                            $machine_repair_theme_name = wp_get_theme()->get( 'Name' );
                            /* translators: %s!: Theme Name. */
                            echo esc_html( sprintf( __( 'Welcome to the free theme: %s!', 'machine-repair' ), $machine_repair_theme_name ) );
                        ?>
                    </h2>
                    <p class="machine-repair-notice-desc">
                        <?php esc_html_e( 'Get started by exploring the features of your new theme. Customize your design, add your content, and create a site that fits your vision.', 'machine-repair' ); ?>
                    </p>

                    <div class="machine-repair-welcome-info">
                        <div class="machine-repair-welcome-thumb">
                            <img src="<?php echo esc_url( get_stylesheet_directory_uri() . '/screenshot.png' ); ?>" alt="<?php esc_attr_e( 'Theme Screenshot', 'machine-repair' ); ?>">
                        </div>

                        <div class="machine-repair-welcome-import">
                            <h3><span class="dashicons dashicons-download"></span> <?php esc_html_e( 'Quick Start: Import Demo', 'machine-repair' ); ?></h3>
                            <p><?php esc_html_e( 'Use the Demo Importer to quickly set up your site with a pre-made layout. Get a complete site in minutes.', 'machine-repair' ); ?></p>
                            <p><a class="button info-link button-primary" href="<?php echo esc_url( admin_url( 'themes.php?page=machinerepair-demoimport' ) ); ?>"><?php esc_html_e( 'Go to Demo Importer', 'machine-repair' ); ?></a></p>
                        </div>

                        <div class="machine-repair-welcome-getting-started">
                            <h3><span class="dashicons dashicons-art"></span> <?php esc_html_e( 'Customize Your Theme', 'machine-repair' ); ?></h3>
                            <p><?php esc_html_e( 'Want to make it truly yours? Explore the Getting Started Guide to personalize your site to suit your needs.', 'machine-repair' ); ?></p>
                            <p><a class="info-link button" href="<?php echo esc_url( admin_url( 'themes.php?page=machine-repair-getstart-page' ) ); ?>"><?php esc_html_e( 'View Getting Started Guide', 'machine-repair' ); ?></a></p>
                        </div>
                    </div>
                </div>
            </div>

            <?php
        }

	}
}

add_action( 'admin_notices', 'machine_repair_admin_notice' );

if( ! function_exists( 'machine_repair_update_admin_notice' ) ) :
/**
 * Updating admin notice on dismiss
*/
function machine_repair_update_admin_notice(){
    if ( isset( $_GET['machine_repair_admin_notice'] ) && $_GET['machine_repair_admin_notice'] = '1' ) {
        update_option( 'machine_repair_admin_notice', true );
    }
}
endif;
add_action( 'admin_init', 'machine_repair_update_admin_notice' );


add_action('after_switch_theme', 'machine_repair_setup_options');
function machine_repair_setup_options () {
    update_option('machine_repair_admin_notice', FALSE );
    update_option('machine_repair_demo_imported', false);
}


function get_changelog_from_readme() {
    $file_path = get_template_directory() . '/readme.txt'; // Adjust path if necessary

    if (file_exists($file_path)) {
        $content = file_get_contents($file_path);

        // Extract changelog section
        $changelog_start = strpos($content, "== Changelog ==");
        $changelog = substr($content, $changelog_start);

        // Split changelog into versions (supports "* X.Y.Z - Date", bare "* X.Y.Z",
        // and "= X.Y.Z =" style entries, with tab, space, or "*" indented details).
        preg_match_all('/^(?:\*[ \t]*([\d.]+)(?:[ \t]*-[ \t]*(.+?))?|=[ \t]*([\d.]+)[ \t]*=)[ \t]*\r?\n((?:(?:\t|[ ]{2,}|\*(?!\s*[\d.]+(?:\s|\r?$)))[ \t]*-?[ \t]*.+?\r?\n)*)/m', $changelog, $raw_matches, PREG_SET_ORDER);

        $matches = [];

        foreach ($raw_matches as $raw_match) {
            $version = '' !== $raw_match[1] ? $raw_match[1] : $raw_match[3];
            $details = preg_replace('/^([ \t]*)\*[ \t]*/m', '$1', $raw_match[4]);

            if ('' !== $version && '' !== trim($details)) {
                $matches[] = array( $raw_match[0], $version, trim($raw_match[2]), $details );
            }
        }

        return $matches;
    }
    return [];
}