<?php

defined('ABSPATH') || exit;

function aurora_lite_theme_setup() {
    add_theme_support('title-tag');
    add_theme_support('elementor');
    add_theme_support('align-wide');
    add_theme_support('woocommerce');
    add_theme_support('custom-logo');
    add_theme_support('post-thumbnails');
    add_theme_support('wp-block-styles');
    add_theme_support('responsive-embeds');
    add_theme_support('widgets-block-editor');
    add_theme_support('automatic-feed-links');
    add_theme_support('wc-product-gallery-zoom');
    add_theme_support('wc-product-gallery-slider');
    add_theme_support('wc-product-gallery-lightbox');
    add_editor_style( 'assets/css/editor-style.css' );
    add_theme_support('customize-selective-refresh-widgets');
    load_theme_textdomain('aurora-lite', get_template_directory() . '/languages');
    add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption'));
    register_block_pattern(
        'aurora-lite/intro',
        [
            'title'      => __( 'Intro Paragraph', 'aurora-lite' ),
            'categories' => [ 'text' ],
            'content'    => '<!-- wp:paragraph {"className":"aurora-lite-intro"} --><p class="aurora-lite-intro">Write your intro here.</p><!-- /wp:paragraph -->',
        ]
    );
    register_block_style(
        'core/paragraph',
        [
            'name'  => 'aurora-lite-intro',
            'label' => __( 'Aurora Lite Intro', 'aurora-lite' ),
        ]
    );
}
add_action('after_setup_theme', 'aurora_lite_theme_setup');


function aurora_lite_theme_scripts() {
    $style_path = get_template_directory() . '/style.css';
    wp_enqueue_style( 'aurora-lite-style', get_stylesheet_uri(), array(), file_exists( $style_path ) ? filemtime( $style_path ) : false );
    wp_enqueue_style( 'fontawesome', get_template_directory_uri() . '/assets/fonts/font-awesome/css/fontawesome.min.css', array(), '7.2.0' );
    wp_enqueue_style( 'fontawesome-solid', get_template_directory_uri() . '/assets/fonts/font-awesome/css/solid.min.css', array( 'fontawesome' ), '7.2.0' );
    wp_enqueue_style( 'fontawesome-brands', get_template_directory_uri() . '/assets/fonts/font-awesome/css/brands.min.css', array( 'fontawesome' ), '7.2.0' );
    wp_enqueue_style( 'fontawesome-regular', get_template_directory_uri() . '/assets/fonts/font-awesome/css/regular.min.css', array( 'fontawesome' ), '7.2.0' );
    $main_js = get_template_directory() . '/assets/js/main.js';
    wp_enqueue_script( 'aurora-lite-scripts', get_template_directory_uri() . '/assets/js/main.js', array( 'jquery' ), file_exists( $main_js ) ? filemtime( $main_js ) : false, true );
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_theme_scripts' );


function aurora_lite_customizer_controls_styles() {

    $file_path = get_template_directory() . '/assets/css/customizer-controls.css';

    if ( file_exists( $file_path ) ) {
        wp_enqueue_style(
            'aurora-lite-customizer-controls',
            get_template_directory_uri() . '/assets/css/customizer-controls.css',
            [],
            filemtime( $file_path )
        );
    }
}
add_action( 'customize_controls_enqueue_scripts', 'aurora_lite_customizer_controls_styles' );


function aurora_lite_enqueue_rtl() {
    if ( is_rtl() ) {
        $file_path = get_template_directory() . '/assets/css/rtl.css';
        if ( file_exists( $file_path ) ) {
            wp_enqueue_style('aurora-lite-rtl', get_template_directory_uri() . '/assets/css/rtl.css', [], filemtime( $file_path ));
        }
    }
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_rtl' );


require_once get_template_directory() . '/assets/inc/admin.php';

function aurora_lite_preconnect_fonts() {
    echo '<link rel="preconnect" href="' . esc_url( 'https://fonts.googleapis.com' ) . '">' . "\n";
    echo '<link rel="preconnect" href="' . esc_url( 'https://fonts.gstatic.com' ) . '" crossorigin>' . "\n";
}
add_action( 'wp_head', 'aurora_lite_preconnect_fonts', 1 );


function aurora_lite_enqueue_layout_styles() {

    $base_dir = get_template_directory() . '/assets/css/base/';
    if ( is_dir($base_dir) ) {
        foreach ( glob($base_dir . '*.css') as $file_path ) {
            if ( ! file_exists( $file_path ) ) continue;
            $file_name = basename($file_path, '.css');
            wp_enqueue_style(
                'aurora-lite-base-' . $file_name,
                get_template_directory_uri() . '/assets/css/base/' . $file_name . '.css',
                [],
                filemtime($file_path)
            );
        }
    }

    $layout_mods = [
        'header_layout'         => true,
        'footer_layout'         => true,
        '404_page_layout'       => is_404(),
        'author_page_layout'    => is_author(),
        'single_post_layout'    => is_single(),
        'search_results_layout' => is_search(),
        'homepage_layout'       => is_front_page() || is_home(),
        'archive_layout'        => is_category() || is_tag() || is_date() || is_search() || is_author(),
    ];

    foreach ( $layout_mods as $mod => $condition ) {
        if ( ! $condition ) continue;

        $value = strtolower( get_theme_mod( 'aurora_lite_' . $mod, 'Default' ) );

        $file_relative = "/assets/css/$mod/$value.css";
        $file_path     = get_template_directory() . $file_relative;

        if ( file_exists($file_path) ) {
            wp_enqueue_style(
                "aurora-lite-$mod-$value",
                get_template_directory_uri() . $file_relative,
                [],
                filemtime($file_path)
            );
        }
    }

    $page_context_styles = [
        '404'       => is_404(),
        'page'      => is_page(),
        'archive'    => is_category() || is_tag() || is_date() || is_search() || is_author(),
        'search'    => is_search(),
        'author'    => is_author(),
        'single'    => is_single(),
        'home'      => is_front_page() || is_home(),
    ];

    foreach ( $page_context_styles as $context => $condition ) {
        if ( ! $condition ) continue;

        $file_relative = "/assets/css/pages/{$context}.css";
        $file_path     = get_template_directory() . $file_relative;

        if ( file_exists($file_path) ) {
            wp_enqueue_style(
                "aurora-lite-page-{$context}",
                get_template_directory_uri() . $file_relative,
                [],
                filemtime($file_path)
            );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_layout_styles' );


function aurora_lite_enqueue_sidebar_styles() {

    $load = false;

    if ( is_single() && get_theme_mod( 'aurora_lite_show_sidebar', true ) ) {
        $load = true;
    }

    if ( ( is_archive() || is_search() ) && get_theme_mod( 'aurora_lite_show_archive_sidebar', true ) ) {
        $load = true;
    }

    if ( ! $load ) {
        return;
    }

    $file_path = get_template_directory() . '/assets/css/pages/sidebar.css';
    $file_uri  = get_template_directory_uri() . '/assets/css/pages/sidebar.css';

    wp_enqueue_style(
        'aurora-lite-sidebar',
        $file_uri,
        [],
        file_exists( $file_path ) ? filemtime( $file_path ) : null
    );
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_sidebar_styles' );


require_once get_template_directory() . '/assets/inc/customizer.php';

require_once get_template_directory() . '/assets/inc/layouts/gen-styles.php';

require_once get_template_directory() . '/assets/inc/homepage-sections.php';

require_once get_template_directory() . '/assets/inc/layouts/archives.php';

require_once get_template_directory() . '/assets/inc/layouts/single.php';

require_once get_template_directory() . '/assets/inc/layouts/header.php';

require_once get_template_directory() . '/assets/inc/layouts/search.php';

require_once get_template_directory() . '/assets/inc/layouts/author.php';

require_once get_template_directory() . '/assets/inc/layouts/404.php';

require_once get_template_directory() . '/assets/inc/layouts/footer.php';


function aurora_lite_customizer_preview() {
    $file_path = get_template_directory() . '/assets/js/customizer-preview.js';
    wp_enqueue_script( 'aurora-lite-customizer', get_template_directory_uri() . '/assets/js/customizer-preview.js', array( 'customize-preview' ), file_exists( $file_path ) ? filemtime( $file_path ) : false, true );
}
add_action('customize_preview_init', 'aurora_lite_customizer_preview');


function aurora_lite_customizer_controls() {
    $file_path = get_template_directory() . '/assets/js/customizer-controls.js';
    wp_enqueue_script( 'aurora-lite-customizer-controls', get_template_directory_uri() . '/assets/js/customizer-controls.js', array( 'jquery', 'customize-controls' ), file_exists( $file_path ) ? filemtime( $file_path ) : false, true );
}
add_action('customize_controls_enqueue_scripts', 'aurora_lite_customizer_controls');


function aurora_lite_enqueue_navigation_script() {
    $file_path = get_template_directory() . '/assets/js/navigation.js';
    wp_enqueue_script(
        'aurora-lite-navigation',
        get_template_directory_uri() . '/assets/js/navigation.js',
        [],
        file_exists( $file_path ) ? filemtime( $file_path ) : false,
        true
    );
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_navigation_script' );

function aurora_lite_template_loader( $relative_path, $vars = [] ) {

    $base_dir     = get_template_directory() . '/' . trim( $relative_path, '/\\' );
    $default_file = $base_dir . '/Default.php';

    if ( file_exists( $default_file ) ) {
        if ( ! empty( $vars ) && is_array( $vars ) ) {
            extract( $vars );
        }
        include $default_file;
    }
}

function aurora_lite_register_menus() {
    
    register_nav_menus([
        'primary' => __('Primary Menu', 'aurora-lite'),
        'secondary' => __('Secondary Menu', 'aurora-lite'),
        'footer1' => __('Footer Menu 1', 'aurora-lite'),
        'footer2' => __('Footer Menu 2', 'aurora-lite'),
        'footer3' => __('Footer Menu 3', 'aurora-lite'),
        'footerbottom' => __('Footer Bottom Menu', 'aurora-lite'),
        '404_menu' => __('404 Menu', 'aurora-lite'),
        'mobile' => __('Mobile Menu', 'aurora-lite'),
    ]);
}
add_action('init', 'aurora_lite_register_menus');


function aurora_lite_register_sidebar() {
    register_sidebar([
        'name'          => __( 'Sidebar', 'aurora-lite' ),
        'id'            => 'main-sidebar',
        'description'   => __( 'Add widgets here to appear in your sidebar.', 'aurora-lite' ),
        'before_widget' => '<div id="%1$s" class="aurora-lite-widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h4 class="aurora-lite-widget-title">',
        'after_title'   => '</h4>',
    ]);
}
add_action( 'widgets_init', 'aurora_lite_register_sidebar' );


function aurora_lite_get_date_format() {
        
    $format = get_theme_mod('aurora_lite_date_format', 'M j, Y');

    if ($format === 'custom') {
        $custom_format = trim(get_theme_mod('aurora_lite_custom_date_format'));
        
        if (!empty($custom_format)) {
            return $custom_format;
        }
        return 'M j, Y';
    }

    if (empty($format) || $format === 'custom') {
        return 'M j, Y';
    }

    return $format;
}


function aurora_lite_get_categories($args = []) {

    $defaults = [
        'post_id'  => null,
        'multiple' => false,
        'archive'  => false,
        'query'    => null,
        'links'    => false,
        'separator'=> ', ',
        'before'   => '',
        'after'    => '',
        'echo'     => true,
    ];

    $args = wp_parse_args($args, $defaults);

    if ($args['archive']) {

        $term = null;

        if (!wp_doing_ajax()) {
            $term = get_queried_object();

            if (!$term instanceof WP_Term || $term->taxonomy !== 'category') {
                $term = null;
            }

        }

        if (!$term && $args['query'] instanceof WP_Query) {

            $tax_query = $args['query']->get('tax_query');

            if (!empty($tax_query)) {
                foreach ($tax_query as $tax) {
                    if (!empty($tax['taxonomy']) && $tax['taxonomy'] === 'category' && !empty($tax['terms'])) {
                        $term_id = is_array($tax['terms']) ? $tax['terms'][0] : $tax['terms'];
                        $term = get_term($term_id, 'category');
                        break;
                    }
                }
            }

            if (!$term && $args['query']->get('cat')) {
                $term = get_category($args['query']->get('cat'));
            }
        }

        if ($term && !is_wp_error($term)) {
            $output = esc_html($term->name);

            if ($args['links']) {
                $output = sprintf(
                    '<a href="%s" class="post-category-link">%s</a>',
                    esc_url(get_term_link($term)),
                    $output
                );
            }

            $output = $args['before'] . $output . $args['after'];

            if ($args['echo']) {
                echo $output;
                return '';
            }

            return $output;
        }

        $args['archive'] = false;
    }


    $post_id = $args['post_id'] ?: get_the_ID();

    if (!$post_id) return '';

    $categories = get_the_category($post_id);

    if (empty($categories)) return '';

    if ($args['multiple']) {

        $items = [];

        foreach ($categories as $cat) {
            $name = esc_html($cat->name);

            if ($args['links']) {
                $name = sprintf(
                    '<a href="%s" class="post-category-link">%s</a>',
                    esc_url(get_category_link($cat->term_id)),
                    $name
                );
            }

            $items[] = $name;
        }

        $output = implode($args['separator'], $items);

    } else {

        $cat = $categories[0];
        $name = esc_html($cat->name);

        if ($args['links']) {
            $name = sprintf(
                '<a href="%s" class="post-category-link">%s</a>',
                esc_url(get_category_link($cat->term_id)),
                $name
            );
        }

        $output = $name;
    }

    $output = $args['before'] . $output . $args['after'];

    if ($args['echo']) {
        echo $output;
        return;
    }

    return $output;
}


function aurora_lite_show_comment_number() {
    $comment_count = get_comments_number();

    if ( $comment_count == 0 ) {
        echo esc_html__( 'No comments yet', 'aurora-lite' );
        return;
    }

    printf(
        /* translators: %s: number of comments */
        _n( '%s comment', '%s comments', $comment_count, 'aurora-lite' ),
        number_format_i18n( $comment_count )
    );
}


function aurora_lite_enqueue_woo_styles() {
    if ( class_exists( 'WooCommerce' ) ) {

        if ( function_exists('is_woocommerce') && ( is_woocommerce() || is_cart() || is_checkout() || is_account_page() ) ) {

            $css_file = get_template_directory() . '/assets/css/woo.css';

            wp_enqueue_style(
                'aurora-lite-woo-styles',
                get_template_directory_uri() . '/assets/css/woo.css',
                array(),
                file_exists($css_file) ? filemtime($css_file) : false
            );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_woo_styles' );


function aurora_lite_enqueue_comment_reply() {
    if ( is_single() && comments_open() ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_comment_reply' );

function aurora_lite_enqueue_custom_header_styles() {
    $css_file = get_template_directory() . '/assets/css/customizer.css';

    wp_enqueue_style(
        'aurora-lite-custom-header-styles',
        get_template_directory_uri() . '/assets/css/customizer.css',
        array(),
        file_exists($css_file) ? filemtime($css_file) : false
    );
}
add_action( 'customize_preview_init', 'aurora_lite_enqueue_custom_header_styles' );


function aurora_lite_enqueue_comments_style() {
    if ( is_singular() && comments_open() ) {
        $file_path = get_template_directory() . '/assets/css/comments.css';
        if ( file_exists( $file_path ) ) {
            wp_enqueue_style(
                'aurora-lite-comments',
                get_template_directory_uri() . '/assets/css/comments.css',
                [],
                filemtime( $file_path )
            );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_comments_style' );


function aurora_lite_footer_email() {

    $email = get_theme_mod( 'aurora_lite_contact_email', '' );

    if ( empty( $email ) ) {
        return;
    }

    echo '<a href="mailto:' . esc_attr( $email ) . '" class="social-icon">';
    echo '<i class="fa-solid fa-envelope" aria-hidden="true"></i>';
    echo '<span class="screen-reader-text">' . esc_html__( 'Email', 'aurora-lite' ) . '</span>';
    echo '</a>';
}


