<?php
/**
 * Paws & Care Theme Functions
 *
 * @package Paws_And_Care
 * @since 0.1.2
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Define theme constants
define('PAWS_AND_CARE_VERSION', '0.1.6');
define('PAWS_AND_CARE_DIR', get_template_directory());
define('PAWS_AND_CARE_URI', get_template_directory_uri());

/**
 * Theme Setup
 */
function paws_and_care_setup()
{
    // Load theme text domain for translations
    load_theme_textdomain('paws-and-care', get_template_directory() . '/languages');

    // Add theme support
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('automatic-feed-links');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
        'style',
        'script',
    ));
    add_theme_support('custom-logo', array(
        'height' => 60,
        'width' => 200,
        'flex-height' => true,
        'flex-width' => true,
    ));
    add_theme_support('customize-selective-refresh-widgets');

    // Block Editor Support
    add_theme_support('responsive-embeds');
    add_theme_support('align-wide');
    add_theme_support('wp-block-styles');

    // WooCommerce Support
    add_theme_support('woocommerce', array(
        'thumbnail_image_width' => 300,
        'single_image_width'    => 600,
        'product_grid'          => array(
            'default_rows'    => 3,
            'min_rows'        => 2,
            'max_rows'        => 8,
            'default_columns' => 4,
            'min_columns'     => 2,
            'max_columns'     => 5,
        ),
    ));
    add_theme_support('wc-product-gallery-zoom');
    add_theme_support('wc-product-gallery-lightbox');
    add_theme_support('wc-product-gallery-slider');

    // Editor Styles
    add_editor_style('assets/css/editor-style.css');

    // Register navigation menus
    register_nav_menus(array(
        'primary' => esc_html__('Primary Menu', 'paws-and-care'),
        'footer' => esc_html__('Footer Menu', 'paws-and-care'),
    ));

    // Set content width
    if (!isset($content_width)) {
        $content_width = 1140;
    }
}
add_action('after_setup_theme', 'paws_and_care_setup');

/**
 * Add custom body classes
 */
function paws_and_care_body_classes($classes)
{
    // Header overlap/transparent mode
    $header_overlap = get_theme_mod('paws_and_care_header_overlap', false);

    if ($header_overlap) {
        $apply_on = get_theme_mod('paws_and_care_overlap_apply_on', 'front-page');

        // Determine if we should apply overlap on this page
        $should_apply = false;

        if ('all-pages' === $apply_on) {
            $should_apply = true;
        } elseif ('front-page' === $apply_on && is_front_page()) {
            $should_apply = true;
        }

        if ($should_apply) {
            $classes[] = 'header-overlap';
            $classes[] = 'hide-topbar'; // Always hide topbar in transparent mode
        }
    }

    // Sticky header class
    $sticky_header = get_theme_mod('paws_and_care_sticky_header', true);
    if ($sticky_header) {
        $classes[] = 'sticky-header-enabled';
    }

    return $classes;
}
add_filter('body_class', 'paws_and_care_body_classes');

/**
 * Enqueue scripts and styles
 */
function paws_and_care_scripts()
{
    // Styles
    wp_enqueue_style('bootstrap', PAWS_AND_CARE_URI . '/assets/bootstrap-5.3.6-dist/css/bootstrap.min.css', array(), '5.3.6');
    wp_enqueue_style('font-awesome', PAWS_AND_CARE_URI . '/assets/fontawesome-free-6.5.1-web/css/all.min.css', array(), '6.5.1');
    wp_enqueue_style('paws-and-care-fonts', PAWS_AND_CARE_URI . '/assets/fonts/fonts.css', array(), PAWS_AND_CARE_VERSION);
    wp_enqueue_style('paws-and-care-main', PAWS_AND_CARE_URI . '/assets/css/style.css', array('bootstrap'), PAWS_AND_CARE_VERSION);
    wp_enqueue_style('paws-and-care-breadcrumbs', PAWS_AND_CARE_URI . '/assets/css/breadcrumbs.css', array('paws-and-care-main'), PAWS_AND_CARE_VERSION);
    wp_enqueue_style('paws-and-care-style', get_stylesheet_uri(), array('paws-and-care-breadcrumbs'), PAWS_AND_CARE_VERSION);

    // WooCommerce Styles & Scripts
    if (class_exists('WooCommerce')) {
        wp_enqueue_style('paws-and-care-woocommerce', PAWS_AND_CARE_URI . '/assets/css/woocommerce.css', array('paws-and-care-style'), PAWS_AND_CARE_VERSION);
        wp_enqueue_script('paws-and-care-woocommerce', PAWS_AND_CARE_URI . '/assets/js/woocommerce-cart.js', array('jquery'), PAWS_AND_CARE_VERSION, true);
    }

    // Scripts - jQuery is loaded automatically as a dependency
    wp_enqueue_script('bootstrap', PAWS_AND_CARE_URI . '/assets/bootstrap-5.3.6-dist/js/bootstrap.bundle.min.js', array('jquery'), '5.3.6', true);
    wp_enqueue_script('paws-and-care-scripts', PAWS_AND_CARE_URI . '/assets/js/scripts.js', array('jquery', 'bootstrap'), PAWS_AND_CARE_VERSION, true);

    // Comment reply script for threaded comments
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}
add_action('wp_enqueue_scripts', 'paws_and_care_scripts');

/**
 * Register widget areas
 */
function paws_and_care_widgets_init()
{
    register_sidebar(array(
        'name' => esc_html__('Sidebar', 'paws-and-care'),
        'id' => 'sidebar-1',
        'description' => esc_html__('Add widgets here to appear in your sidebar.', 'paws-and-care'),
        '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' => esc_html__('Footer Widget 1', 'paws-and-care'),
        'id' => 'footer-1',
        'description' => esc_html__('First footer widget area.', 'paws-and-care'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h5 class="widget-title">',
        'after_title' => '</h5>',
    ));

    register_sidebar(array(
        'name' => esc_html__('Footer Widget 2', 'paws-and-care'),
        'id' => 'footer-2',
        'description' => esc_html__('Second footer widget area.', 'paws-and-care'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h5 class="widget-title">',
        'after_title' => '</h5>',
    ));

    register_sidebar(array(
        'name' => esc_html__('Footer Widget 3', 'paws-and-care'),
        'id' => 'footer-3',
        'description' => esc_html__('Third footer widget area.', 'paws-and-care'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h5 class="widget-title">',
        'after_title' => '</h5>',
    ));

    register_sidebar(array(
        'name' => esc_html__('Footer Widget 4', 'paws-and-care'),
        'id' => 'footer-4',
        'description' => esc_html__('Fourth footer widget area.', 'paws-and-care'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h5 class="widget-title">',
        'after_title' => '</h5>',
    ));

    register_sidebar(array(
        'name' => esc_html__('WooCommerce Sidebar', 'paws-and-care'),
        'id' => 'sidebar-woocommerce',
        'description' => esc_html__('Add widgets here to appear in your WooCommerce shop pages.', 'paws-and-care'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h4 class="widget-title">',
        'after_title' => '</h4>',
    ));
}
add_action('widgets_init', 'paws_and_care_widgets_init');

/**
 * Include required files
 */
require_once PAWS_AND_CARE_DIR . '/inc/class-bootstrap-nav-walker.php';
require_once PAWS_AND_CARE_DIR . '/inc/customizer/customizer-repeater/functions.php';
require_once PAWS_AND_CARE_DIR . '/inc/customizer/customizer.php';

/**
 * WooCommerce Integration
 */
if (class_exists('WooCommerce')) {
    require_once PAWS_AND_CARE_DIR . '/inc/woocommerce.php';
}

/**
 * Elementor Integration
 * All Elementor-related functions are in inc/elementor/elementor.php
 */
require_once PAWS_AND_CARE_DIR . '/inc/elementor/elementor.php';

require_once PAWS_AND_CARE_DIR . '/inc/dynamic-styles.php';

/**
 * Dynamic RGBA Variables
 */
require_once PAWS_AND_CARE_DIR . '/inc/dynamic-css.php';

/**
 * Admin Pages & Notices
 * Theme info page and dismissible notices
 */
if (is_admin()) {
    require_once PAWS_AND_CARE_DIR . '/inc/admin/theme-info.php';
    require_once PAWS_AND_CARE_DIR . '/inc/admin/admin-notice.php';
    
    /**
     * Enqueue admin styles and scripts
     */
    function paws_and_care_admin_enqueue($hook) {
        // Load on theme info page, customizer, dashboard, and themes page
        $allowed_pages = array('appearance_page_paws-and-care-info', 'index.php', 'themes.php');
        
        if (in_array($hook, $allowed_pages) || strpos($hook, 'customize') !== false) {
            wp_enqueue_style(
                'paws-and-care-admin-upsell',
                get_template_directory_uri() . '/assets/css/admin-upsell.css',
                array(),
                PAWS_AND_CARE_VERSION
            );

            // Inject the theme's primary color as a CSS variable for admin UI
            $theme_color = get_theme_mod('paws_and_care_theme_color', '#ff8c42');
            $admin_color_css = ":root { --paws-admin-color: {$theme_color}; }";
            wp_add_inline_style('paws-and-care-admin-upsell', $admin_color_css);
            
            wp_enqueue_script(
                'paws-and-care-admin-upsell',
                get_template_directory_uri() . '/assets/js/admin-upsell.js',
                array('jquery'),
                PAWS_AND_CARE_VERSION,
                true
            );
            
            wp_localize_script('paws-and-care-admin-upsell', 'pawsAdminData', array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('paws_dismiss_notice')
            ));
        }
    }
    add_action('admin_enqueue_scripts', 'paws_and_care_admin_enqueue');
}

/**
 * Calculate reading time for posts
 */
function paws_and_care_reading_time()
{
    $content = get_post_field('post_content', get_the_ID());
    $word_count = str_word_count(strip_tags($content));
    $reading_time = ceil($word_count / 200);

    if ($reading_time < 1) {
        $reading_time = 1;
    }

    return sprintf(
        /* translators: %d: reading time in minutes */
        _n('%d min read', '%d min read', $reading_time, 'paws-and-care'),
        $reading_time
    );
}

/**
 * Get theme mod with default fallback
 */
function paws_and_care_get_option($option, $default = '')
{
    return get_theme_mod($option, $default);
}

/**
 * Custom comment callback
 */
function paws_and_care_comment_callback($comment, $args, $depth)
{
    $tag = ('div' === $args['style']) ? 'div' : 'li';
    ?>
    <<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class('comment-item mb-4 p-4 rounded'); ?>>
        <div class="comment-body">
            <div class="d-flex">
                <div class="comment-avatar me-3">
                    <?php echo get_avatar($comment, 60, '', '', array('class' => 'rounded-circle')); ?>
                </div>
                <div class="comment-content flex-grow-1">
                    <div class="comment-meta mb-2">
                        <strong class="comment-author"><?php comment_author_link(); ?></strong>
                        <span class="comment-date text-muted ms-2">
                            <i class="fa-regular fa-clock me-1"></i>
                            <?php
                            printf(
                                /* translators: 1: comment date, 2: comment time */
                                esc_html__('%1$s at %2$s', 'paws-and-care'),
                                get_comment_date(),
                                get_comment_time()
                            );
                            ?>
                        </span>
                    </div>

                    <?php if ('0' === $comment->comment_approved): ?>
                        <p class="comment-awaiting-moderation alert alert-warning">
                            <?php esc_html_e('Your comment is awaiting moderation.', 'paws-and-care'); ?>
                        </p>
                    <?php endif; ?>

                    <div class="comment-text">
                        <?php comment_text(); ?>
                    </div>

                    <div class="comment-actions mt-2">
                        <?php
                        comment_reply_link(array_merge($args, array(
                            'depth' => $depth,
                            'max_depth' => $args['max_depth'],
                            'before' => '<span class="reply-link">',
                            'after' => '</span>',
                        )));
                        edit_comment_link(esc_html__('Edit', 'paws-and-care'), ' <span class="edit-link">', '</span>');
                        ?>
                    </div>
                </div>
            </div>
        </div>
        <?php
}

/**
 * Get sidebar layout configuration for current page type
 *
 * @return array Array with 'position', 'content_class', 'sidebar_class', and 'show_sidebar' keys
 */
function paws_and_care_get_sidebar_layout()
{
    // Determine sidebar position based on page type
    if (is_singular('post')) {
        $position = get_theme_mod('paws_and_care_single_sidebar', 'right');
    } elseif (is_page()) {
        $position = get_theme_mod('paws_and_care_page_sidebar', 'none');
    } elseif (is_archive() || is_search()) {
        $position = get_theme_mod('paws_and_care_archive_sidebar', 'right');
    } else {
        // Blog index and other pages
        $position = get_theme_mod('paws_and_care_blog_sidebar', 'right');
    }

    // Build return array
    $layout = array(
        'position' => $position,
        'show_sidebar' => ('none' !== $position),
        'content_class' => 'col-lg-8',
        'sidebar_class' => 'col-lg-4',
        'content_order' => '',
        'sidebar_order' => '',
    );

    // Adjust classes based on position
    if ('none' === $position) {
        $layout['content_class'] = 'col-12';
        $layout['sidebar_class'] = '';
    } elseif ('left' === $position) {
        $layout['content_order'] = 'order-lg-2';
        $layout['sidebar_order'] = 'order-lg-1';
    }

    return apply_filters('paws_and_care_sidebar_layout', $layout);
}
