<?php
/**
 * Nihongo Theme Functions
 * 
 * @package Nihongo
 * @version 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Theme setup
 */
function nihongo_theme_setup() {
    // Add theme support for various features
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    add_theme_support('custom-logo');
    add_theme_support('customize-selective-refresh-widgets');
    
    // Add support for wide and full alignment
    add_theme_support('align-wide');
    
    // Add support for editor styles
    add_theme_support('editor-styles');
    add_editor_style('assets/css/editor-style.css');
    
    // Register navigation menus
    register_nav_menus(array(
        'primary' => __('Primary Menu', 'nihongo'),
        'footer' => __('Footer Menu', 'nihongo'),
    ));
    
    // Add image sizes
    add_image_size('course-thumbnail', 400, 300, true);
    add_image_size('testimonial-thumbnail', 300, 300, true);
    add_image_size('news-thumbnail', 600, 400, true);
    add_image_size('hero-image', 1920, 1080, true);
}
add_action('after_setup_theme', 'nihongo_theme_setup');

/**
 * Enqueue scripts and styles
 */
function nihongo_scripts() {
    $theme_version = '1.0.0';
    $template_dir = get_template_directory_uri();
    
    // ===== STYLES =====
    
    // Main theme stylesheet (required by WordPress)
    wp_enqueue_style('nihongo-style', get_stylesheet_uri(), array(), $theme_version);
    
    // Main CSS file
    wp_enqueue_style('nihongo-main-style', $template_dir . '/assets/css/style.css', array('nihongo-style'), $theme_version);
    
    // Google Fonts
    wp_enqueue_style('nihongo-fonts', 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Noto+Sans+JP:wght@300;400;500;700;900&family=M+PLUS+Rounded+1c:wght@400;500;700;800&family=BIZ+UDGothic:wght@400;700&family=Noto+Serif+JP:wght@400;600;700;900&family=Hachi+Maru+Pop&display=swap', array(), null);
    
    // ===== SCRIPTS =====
    
    // Main JavaScript file
    wp_enqueue_script('nihongo-main-js', $template_dir . '/assets/js/main.js', array('jquery'), $theme_version, true);
    
    // Navigation JavaScript
    wp_enqueue_script('nihongo-navigation', $template_dir . '/assets/js/navigation.js', array('jquery'), $theme_version, true);
    
    // Localize script for AJAX and theme data
    wp_localize_script('nihongo-main-js', 'nihongo_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('nihongo_nonce'),
        'theme_url' => $template_dir,
        'current_lang' => nihongo_get_current_language(),
        'is_home' => is_front_page(),
        'is_courses' => is_page('courses') || is_post_type_archive('course'),
        'is_contact' => is_page('contact'),
        'is_j_bridge' => is_page('j-bridge'),
        'is_news' => is_page('news') || is_post_type_archive('news'),
        'is_voices' => is_page('voices') || is_post_type_archive('testimonial'),
    ));
    
    // ===== CONDITIONAL SCRIPTS =====
    
    // Hero slider script for home page
    if (is_front_page()) {
        wp_enqueue_script('nihongo-hero-slider', $template_dir . '/assets/js/hero-slider.js', array('jquery'), $theme_version, true);
    }
    
    // Contact form validation for contact page
    if (is_page('contact')) {
        wp_enqueue_script('nihongo-contact-form', $template_dir . '/assets/js/contact-form.js', array('jquery'), $theme_version, true);
    }
    
    // Course filtering for courses page
    if (is_page('courses') || is_post_type_archive('course')) {
        wp_enqueue_script('nihongo-course-filter', $template_dir . '/assets/js/course-filter.js', array('jquery'), $theme_version, true);
    }
    
    // Testimonial carousel for voices page
    if (is_page('voices') || is_post_type_archive('testimonial')) {
        wp_enqueue_script('nihongo-testimonial-carousel', $template_dir . '/assets/js/testimonial-carousel.js', array('jquery'), $theme_version, true);
    }
    
    // News carousel for news page
    if (is_page('news') || is_post_type_archive('news')) {
        wp_enqueue_script('nihongo-news-carousel', $template_dir . '/assets/js/news-carousel.js', array('jquery'), $theme_version, true);
    }
    
    // J-Bridge specific scripts
    if (is_page('j-bridge')) {
        wp_enqueue_script('nihongo-j-bridge', $template_dir . '/assets/js/j-bridge.js', array('jquery'), $theme_version, true);
    }
    
    // ===== WORDPRESS CORE SCRIPTS =====
    
    // Comment reply script
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
    
    // ===== ADMIN SCRIPTS =====
    
    // Admin scripts for custom post types
    if (is_admin()) {
        wp_enqueue_script('nihongo-admin', $template_dir . '/assets/js/admin.js', array('jquery'), $theme_version, true);
        wp_enqueue_style('nihongo-admin-style', $template_dir . '/assets/css/admin.css', array(), $theme_version);
    }
}
add_action('wp_enqueue_scripts', 'nihongo_scripts');

/**
 * Enqueue admin scripts and styles
 */
function nihongo_admin_scripts($hook) {
    $theme_version = '1.0.0';
    $template_dir = get_template_directory_uri();
    
    // Admin styles
    wp_enqueue_style('nihongo-admin-style', $template_dir . '/assets/css/admin.css', array(), $theme_version);
    
    // Admin scripts
    wp_enqueue_script('nihongo-admin', $template_dir . '/assets/js/admin.js', array('jquery'), $theme_version, true);
    
    // Localize admin script
    wp_localize_script('nihongo-admin', 'nihongo_admin', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('nihongo_admin_nonce'),
        'theme_url' => $template_dir,
    ));
}
add_action('admin_enqueue_scripts', 'nihongo_admin_scripts');

/**
 * Add preload hints for critical resources
 */
function nihongo_preload_resources() {
    $template_dir = get_template_directory_uri();
    
    // Preload critical fonts
    echo '<link rel="preload" href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;500;700;900&display=swap" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">';
    
    // Preload critical images for home page
    if (is_front_page()) {
        echo '<link rel="preload" href="' . $template_dir . '/assets/img/bg11.jpg" as="image">';
        echo '<link rel="preload" href="' . $template_dir . '/assets/img/logo.png" as="image">';
    }
}
add_action('wp_head', 'nihongo_preload_resources', 1);

/**
 * Add critical CSS inline for better performance
 */
function nihongo_critical_css() {
    if (is_front_page()) {
        ?>
        <style id="nihongo-critical-css">
        /* Critical CSS for above-the-fold content */
        .hero { min-height: 100vh; position: relative; }
        .hero-background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
        .hero-content { position: relative; z-index: 2; }
        .header { position: fixed; top: 0; left: 0; width: 100%; z-index: 1000; }
        </style>
        <?php
    }
}
add_action('wp_head', 'nihongo_critical_css', 2);

/**
 * Optimize asset loading
 */
function nihongo_optimize_assets() {
    // Remove unnecessary WordPress assets
    if (!is_admin()) {
        wp_dequeue_style('wp-block-library');
        wp_dequeue_style('wp-block-library-theme');
        wp_dequeue_style('wc-block-style');
        wp_dequeue_style('global-styles');
    }
}
add_action('wp_enqueue_scripts', 'nihongo_optimize_assets', 100);

/**
 * Get asset version for cache busting
 */
function nihongo_get_asset_version($file_path) {
    $file_full_path = get_template_directory() . $file_path;
    
    if (file_exists($file_full_path)) {
        return filemtime($file_full_path);
    }
    
    return '1.0.0';
}

/**
 * Enqueue assets with automatic versioning
 */
function nihongo_enqueue_asset($type, $handle, $src, $deps = array(), $ver = null, $media = 'all') {
    $template_dir = get_template_directory_uri();
    $file_path = str_replace($template_dir, '', $src);
    
    if ($ver === null) {
        $ver = nihongo_get_asset_version($file_path);
    }
    
    if ($type === 'style') {
        wp_enqueue_style($handle, $src, $deps, $ver, $media);
    } elseif ($type === 'script') {
        wp_enqueue_script($handle, $src, $deps, $ver, true);
    }
}

/**
 * Add async/defer attributes to scripts
 */
function nihongo_add_script_attributes($tag, $handle, $src) {
    // Scripts to load with defer
    $defer_scripts = array(
        'nihongo-main-js',
        'nihongo-hero-slider',
        'nihongo-contact-form',
        'nihongo-course-filter',
        'nihongo-testimonial-carousel',
        'nihongo-news-carousel',
        'nihongo-j-bridge'
    );
    
    if (in_array($handle, $defer_scripts)) {
        return str_replace(' src', ' defer src', $tag);
    }
    
    return $tag;
}
add_filter('script_loader_tag', 'nihongo_add_script_attributes', 10, 3);

/**
 * Add loading="lazy" to images
 */
function nihongo_add_lazy_loading($content) {
    if (is_admin() || is_feed() || is_preview()) {
        return $content;
    }
    
    // Add lazy loading to images
    $content = preg_replace('/<img(.*?)src=/', '<img$1loading="lazy" src=', $content);
    
    return $content;
}
add_filter('the_content', 'nihongo_add_lazy_loading');
add_filter('post_thumbnail_html', 'nihongo_add_lazy_loading');

/**
 * Register widget areas
 */
function nihongo_widgets_init() {
    register_sidebar(array(
        'name'          => __('Sidebar', 'nihongo'),
        'id'            => 'sidebar-1',
        'description'   => __('Add widgets here.', 'nihongo'),
        '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'          => __('Footer Widgets', 'nihongo'),
        'id'            => 'footer-widgets',
        'description'   => __('Add widgets here to appear in footer.', 'nihongo'),
        'before_widget' => '<div id="%1$s" class="footer-widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3 class="footer-widget-title">',
        'after_title'   => '</h3>',
    ));
}
add_action('widgets_init', 'nihongo_widgets_init');

/**
 * Custom Post Types
 */
function nihongo_register_post_types() {
    // Courses Post Type
    register_post_type('course', array(
        'labels' => array(
            'name' => __('Courses', 'nihongo'),
            'singular_name' => __('Course', 'nihongo'),
            'add_new' => __('Add New Course', 'nihongo'),
            'add_new_item' => __('Add New Course', 'nihongo'),
            'edit_item' => __('Edit Course', 'nihongo'),
            'new_item' => __('New Course', 'nihongo'),
            'view_item' => __('View Course', 'nihongo'),
            'search_items' => __('Search Courses', 'nihongo'),
            'not_found' => __('No courses found', 'nihongo'),
            'not_found_in_trash' => __('No courses found in trash', 'nihongo'),
        ),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'courses'),
        'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'),
        'menu_icon' => 'dashicons-book-alt',
        'show_in_rest' => true,
    ));
    
    // Testimonials Post Type
    register_post_type('testimonial', array(
        'labels' => array(
            'name' => __('Testimonials', 'nihongo'),
            'singular_name' => __('Testimonial', 'nihongo'),
            'add_new' => __('Add New Testimonial', 'nihongo'),
            'add_new_item' => __('Add New Testimonial', 'nihongo'),
            'edit_item' => __('Edit Testimonial', 'nihongo'),
            'new_item' => __('New Testimonial', 'nihongo'),
            'view_item' => __('View Testimonial', 'nihongo'),
            'search_items' => __('Search Testimonials', 'nihongo'),
            'not_found' => __('No testimonials found', 'nihongo'),
            'not_found_in_trash' => __('No testimonials found in trash', 'nihongo'),
        ),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'testimonials'),
        'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
        'menu_icon' => 'dashicons-format-quote',
        'show_in_rest' => true,
    ));
    
    // News Post Type
    register_post_type('news', array(
        'labels' => array(
            'name' => __('News', 'nihongo'),
            'singular_name' => __('News Item', 'nihongo'),
            'add_new' => __('Add New News', 'nihongo'),
            'add_new_item' => __('Add New News', 'nihongo'),
            'edit_item' => __('Edit News', 'nihongo'),
            'new_item' => __('New News', 'nihongo'),
            'view_item' => __('View News', 'nihongo'),
            'search_items' => __('Search News', 'nihongo'),
            'not_found' => __('No news found', 'nihongo'),
            'not_found_in_trash' => __('No news found in trash', 'nihongo'),
        ),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'news'),
        'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'),
        'menu_icon' => 'dashicons-megaphone',
        'show_in_rest' => true,
    ));
}
add_action('init', 'nihongo_register_post_types');

/**
 * Custom Taxonomies
 */
function nihongo_register_taxonomies() {
    // Course Categories
    register_taxonomy('course_category', 'course', array(
        'labels' => array(
            'name' => __('Course Categories', 'nihongo'),
            'singular_name' => __('Course Category', 'nihongo'),
        ),
        'hierarchical' => true,
        'public' => true,
        'rewrite' => array('slug' => 'course-category'),
        'show_in_rest' => true,
    ));
    
    // Course Levels
    register_taxonomy('course_level', 'course', array(
        'labels' => array(
            'name' => __('Course Levels', 'nihongo'),
            'singular_name' => __('Course Level', 'nihongo'),
        ),
        'hierarchical' => true,
        'public' => true,
        'rewrite' => array('slug' => 'course-level'),
        'show_in_rest' => true,
    ));
}
add_action('init', 'nihongo_register_taxonomies');

/**
 * Custom Meta Boxes
 */
function nihongo_add_meta_boxes() {
    add_meta_box(
        'course_details',
        __('Course Details', 'nihongo'),
        'nihongo_course_details_callback',
        'course',
        'normal',
        'high'
    );
    
    add_meta_box(
        'testimonial_details',
        __('Testimonial Details', 'nihongo'),
        'nihongo_testimonial_details_callback',
        'testimonial',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'nihongo_add_meta_boxes');

/**
 * Course Details Meta Box Callback
 */
function nihongo_course_details_callback($post) {
    wp_nonce_field('nihongo_save_course_details', 'nihongo_course_details_nonce');
    
    $level = get_post_meta($post->ID, '_course_level', true);
    $duration = get_post_meta($post->ID, '_course_duration', true);
    $price = get_post_meta($post->ID, '_course_price', true);
    $features = get_post_meta($post->ID, '_course_features', true);
    
    echo '<table class="form-table">';
    echo '<tr><th><label for="course_level">' . __('Level', 'nihongo') . '</label></th>';
    echo '<td><input type="text" id="course_level" name="course_level" value="' . esc_attr($level) . '" /></td></tr>';
    
    echo '<tr><th><label for="course_duration">' . __('Duration', 'nihongo') . '</label></th>';
    echo '<td><input type="text" id="course_duration" name="course_duration" value="' . esc_attr($duration) . '" /></td></tr>';
    
    echo '<tr><th><label for="course_price">' . __('Price', 'nihongo') . '</label></th>';
    echo '<td><input type="text" id="course_price" name="course_price" value="' . esc_attr($price) . '" /></td></tr>';
    
    echo '<tr><th><label for="course_features">' . __('Features (one per line)', 'nihongo') . '</label></th>';
    echo '<td><textarea id="course_features" name="course_features" rows="5" cols="50">' . esc_textarea($features) . '</textarea></td></tr>';
    echo '</table>';
}

/**
 * Testimonial Details Meta Box Callback
 */
function nihongo_testimonial_details_callback($post) {
    wp_nonce_field('nihongo_save_testimonial_details', 'nihongo_testimonial_details_nonce');
    
    $name = get_post_meta($post->ID, '_testimonial_name', true);
    $country = get_post_meta($post->ID, '_testimonial_country', true);
    $course = get_post_meta($post->ID, '_testimonial_course', true);
    $rating = get_post_meta($post->ID, '_testimonial_rating', true);
    
    echo '<table class="form-table">';
    echo '<tr><th><label for="testimonial_name">' . __('Name', 'nihongo') . '</label></th>';
    echo '<td><input type="text" id="testimonial_name" name="testimonial_name" value="' . esc_attr($name) . '" /></td></tr>';
    
    echo '<tr><th><label for="testimonial_country">' . __('Country', 'nihongo') . '</label></th>';
    echo '<td><input type="text" id="testimonial_country" name="testimonial_country" value="' . esc_attr($country) . '" /></td></tr>';
    
    echo '<tr><th><label for="testimonial_course">' . __('Course', 'nihongo') . '</label></th>';
    echo '<td><input type="text" id="testimonial_course" name="testimonial_course" value="' . esc_attr($course) . '" /></td></tr>';
    
    echo '<tr><th><label for="testimonial_rating">' . __('Rating (1-5)', 'nihongo') . '</label></th>';
    echo '<td><input type="number" id="testimonial_rating" name="testimonial_rating" value="' . esc_attr($rating) . '" min="1" max="5" /></td></tr>';
    echo '</table>';
}

/**
 * Save Meta Box Data
 */
function nihongo_save_meta_boxes($post_id) {
    // Course details
    if (isset($_POST['nihongo_course_details_nonce']) && wp_verify_nonce($_POST['nihongo_course_details_nonce'], 'nihongo_save_course_details')) {
        if (isset($_POST['course_level'])) {
            update_post_meta($post_id, '_course_level', sanitize_text_field($_POST['course_level']));
        }
        if (isset($_POST['course_duration'])) {
            update_post_meta($post_id, '_course_duration', sanitize_text_field($_POST['course_duration']));
        }
        if (isset($_POST['course_price'])) {
            update_post_meta($post_id, '_course_price', sanitize_text_field($_POST['course_price']));
        }
        if (isset($_POST['course_features'])) {
            update_post_meta($post_id, '_course_features', sanitize_textarea_field($_POST['course_features']));
        }
    }
    
    // Testimonial details
    if (isset($_POST['nihongo_testimonial_details_nonce']) && wp_verify_nonce($_POST['nihongo_testimonial_details_nonce'], 'nihongo_save_testimonial_details')) {
        if (isset($_POST['testimonial_name'])) {
            update_post_meta($post_id, '_testimonial_name', sanitize_text_field($_POST['testimonial_name']));
        }
        if (isset($_POST['testimonial_country'])) {
            update_post_meta($post_id, '_testimonial_country', sanitize_text_field($_POST['testimonial_country']));
        }
        if (isset($_POST['testimonial_course'])) {
            update_post_meta($post_id, '_testimonial_course', sanitize_text_field($_POST['testimonial_course']));
        }
        if (isset($_POST['testimonial_rating'])) {
            update_post_meta($post_id, '_testimonial_rating', intval($_POST['testimonial_rating']));
        }
    }
}
add_action('save_post', 'nihongo_save_meta_boxes');

/**
 * Handle language switching
 */
function nihongo_handle_language_switch() {
    if (isset($_GET['lang'])) {
        $lang = $_GET['lang'];
        if (in_array($lang, ['jp', 'en'])) {
            nihongo_set_language($lang);
            // Redirect back to the same page without the lang parameter
            $redirect_url = strtok($_SERVER['REQUEST_URI'], '?');
            if (isset($_GET['id'])) {
                $redirect_url .= '?id=' . $_GET['id'];
            }
            wp_redirect($redirect_url);
            exit;
        }
    }
}
add_action('init', 'nihongo_handle_language_switch');

/**
 * Language Functions (WordPress compatible)
 */
function nihongo_get_current_language() {
    // Check if language is set in cookie
    if (isset($_COOKIE['nihongo_language'])) {
        return $_COOKIE['nihongo_language'];
    }
    
    // Check browser language preference
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $browser_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
        if (in_array($browser_lang, ['en', 'ja'])) {
            $lang = ($browser_lang === 'ja') ? 'jp' : 'en';
            return $lang;
        }
    }
    
    // Default to Japanese
    return 'jp';
}

/**
 * Set language preference
 */
function nihongo_set_language($lang) {
    if (in_array($lang, ['jp', 'en'])) {
        setcookie('nihongo_language', $lang, time() + (365 * 24 * 60 * 60), '/');
        $_COOKIE['nihongo_language'] = $lang;
    }
}

/**
 * Get translation for current language
 */
function nihongo_translate($key) {
    $translations = nihongo_get_translations();
    $current_lang = nihongo_get_current_language();
    
    if (isset($translations[$key][$current_lang])) {
        return $translations[$key][$current_lang];
    }
    
    // Fallback to English if translation not found
    if (isset($translations[$key]['en'])) {
        return $translations[$key]['en'];
    }
    
    // Return key if no translation found
    return $key;
}

/**
 * Get all translations
 */
function nihongo_get_translations() {
    return array(
        'home_title' => array(
            'jp' => 'nihongo.net - 日本語学習サービス',
            'en' => 'nihongo.net - Japanese Learning Service'
        ),
        'courses_title' => array(
            'jp' => 'コース紹介 - nihongo.net',
            'en' => 'Course Introduction - nihongo.net'
        ),
        'j_bridge_title' => array(
            'jp' => 'J-Bridge - 外国人材マッチング - nihongo.net',
            'en' => 'J-Bridge - Foreign Talent Matching - nihongo.net'
        ),
        'contact_title' => array(
            'jp' => 'お問い合わせ - nihongo.net',
            'en' => 'Contact Us - nihongo.net'
        ),
        'news_title' => array(
            'jp' => 'ニュース・ブログ - nihongo.net',
            'en' => 'News & Blog - nihongo.net'
        ),
        'voices_title' => array(
            'jp' => '受講生の声 - nihongo.net',
            'en' => 'Student Voices - nihongo.net'
        ),
        // ... existing code ...
    );
}

/**
 * Helper function to get courses
 */
function nihongo_get_courses($limit = -1) {
    $args = array(
        'post_type' => 'course',
        'posts_per_page' => $limit,
        'post_status' => 'publish',
        'orderby' => 'menu_order',
        'order' => 'ASC'
    );
    
    $courses = get_posts($args);
    $formatted_courses = array();
    
    foreach ($courses as $course) {
        $formatted_courses[] = array(
            'id' => $course->post_name,
            'title' => $course->post_title,
            'description' => $course->post_excerpt,
            'level' => get_post_meta($course->ID, '_course_level', true),
            'duration' => get_post_meta($course->ID, '_course_duration', true),
            'price' => get_post_meta($course->ID, '_course_price', true),
            'features' => explode("\n", get_post_meta($course->ID, '_course_features', true)),
            'image' => get_the_post_thumbnail_url($course->ID, 'course-thumbnail'),
            'url' => get_permalink($course->ID)
        );
    }
    
    return $formatted_courses;
}

/**
 * Helper function to get testimonials
 */
function nihongo_get_testimonials($limit = -1) {
    $args = array(
        'post_type' => 'testimonial',
        'posts_per_page' => $limit,
        'post_status' => 'publish',
        'orderby' => 'menu_order',
        'order' => 'ASC'
    );
    
    $testimonials = get_posts($args);
    $formatted_testimonials = array();
    
    foreach ($testimonials as $testimonial) {
        $formatted_testimonials[] = array(
            'name' => get_post_meta($testimonial->ID, '_testimonial_name', true),
            'country' => get_post_meta($testimonial->ID, '_testimonial_country', true),
            'course' => get_post_meta($testimonial->ID, '_testimonial_course', true),
            'comment' => $testimonial->post_content,
            'rating' => get_post_meta($testimonial->ID, '_testimonial_rating', true),
            'title' => $testimonial->post_title,
            'date' => get_the_date('Y年n月j日', $testimonial->ID),
            'image' => get_the_post_thumbnail_url($testimonial->ID, 'testimonial-thumbnail')
        );
    }
    
    return $formatted_testimonials;
}

/**
 * Helper function to get news
 */
function nihongo_get_news($limit = -1) {
    $args = array(
        'post_type' => 'news',
        'posts_per_page' => $limit,
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC'
    );
    
    $news = get_posts($args);
    $formatted_news = array();
    
    foreach ($news as $news_item) {
        $formatted_news[] = array(
            'title' => $news_item->post_title,
            'excerpt' => $news_item->post_excerpt,
            'date' => get_the_date('Y年n月j日', $news_item->ID),
            'image' => get_the_post_thumbnail_url($news_item->ID, 'news-thumbnail'),
            'url' => get_permalink($news_item->ID)
        );
    }
    
    return $formatted_news;
}

/**
 * Customizer Settings
 */
function nihongo_customize_register($wp_customize) {
    // Add section for theme options
    $wp_customize->add_section('nihongo_theme_options', array(
        'title' => __('Theme Options', 'nihongo'),
        'priority' => 30,
    ));
    
    // Hero background image
    $wp_customize->add_setting('nihongo_hero_bg', array(
        'default' => '',
        'sanitize_callback' => 'esc_url_raw',
    ));
    
    $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'nihongo_hero_bg', array(
        'label' => __('Hero Background Image', 'nihongo'),
        'section' => 'nihongo_theme_options',
        'settings' => 'nihongo_hero_bg',
    )));
    
    // Contact information
    $wp_customize->add_setting('nihongo_contact_email', array(
        'default' => '',
        'sanitize_callback' => 'sanitize_email',
    ));
    
    $wp_customize->add_control('nihongo_contact_email', array(
        'label' => __('Contact Email', 'nihongo'),
        'section' => 'nihongo_theme_options',
        'type' => 'email',
    ));
    
    $wp_customize->add_setting('nihongo_contact_phone', array(
        'default' => '',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    
    $wp_customize->add_control('nihongo_contact_phone', array(
        'label' => __('Contact Phone', 'nihongo'),
        'section' => 'nihongo_theme_options',
        'type' => 'text',
    ));
}
add_action('customize_register', 'nihongo_customize_register');

/**
 * AJAX handler for contact form
 */
function nihongo_handle_contact_form() {
    check_ajax_referer('nihongo_nonce', 'nonce');
    
    $name = sanitize_text_field($_POST['name']);
    $email = sanitize_email($_POST['email']);
    $phone = sanitize_text_field($_POST['phone']);
    $inquiry_type = sanitize_text_field($_POST['inquiry_type']);
    $subject = sanitize_text_field($_POST['subject']);
    $message = sanitize_textarea_field($_POST['message']);
    
    // Basic validation
    if (empty($name) || empty($email) || empty($message)) {
        wp_send_json_error(array('message' => __('Please fill in all required fields.', 'nihongo')));
    }
    
    if (!is_email($email)) {
        wp_send_json_error(array('message' => __('Please enter a valid email address.', 'nihongo')));
    }
    
    // Send email
    $to = get_option('admin_email');
    $email_subject = sprintf(__('New Contact Form Submission: %s', 'nihongo'), $subject);
    $email_message = sprintf(
        __("Name: %s\nEmail: %s\nPhone: %s\nInquiry Type: %s\nSubject: %s\n\nMessage:\n%s", 'nihongo'),
        $name, $email, $phone, $inquiry_type, $subject, $message
    );
    
    $headers = array('Content-Type: text/plain; charset=UTF-8');
    
    if (wp_mail($to, $email_subject, $email_message, $headers)) {
        wp_send_json_success(array('message' => __('Thank you for your message. We will contact you soon.', 'nihongo')));
    } else {
        wp_send_json_error(array('message' => __('Sorry, there was an error sending your message.', 'nihongo')));
    }
}
add_action('wp_ajax_nihongo_contact_form', 'nihongo_handle_contact_form');
add_action('wp_ajax_nopriv_nihongo_contact_form', 'nihongo_handle_contact_form');

/**
 * Add custom body classes
 */
function nihongo_body_classes($classes) {
    $classes[] = 'nihongo-theme';
    $classes[] = 'lang-' . nihongo_get_current_language();
    
    if (is_front_page()) {
        $classes[] = 'page-bg';
    }
    
    return $classes;
}
add_filter('body_class', 'nihongo_body_classes');

/**
 * Custom excerpt length
 */
function nihongo_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'nihongo_excerpt_length');

/**
 * Custom excerpt more
 */
function nihongo_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'nihongo_excerpt_more');

/**
 * Include template parts
 */
function nihongo_get_template_part($template_name, $args = array()) {
    if (!empty($args)) {
        extract($args);
    }
    
    $template_path = get_template_directory() . '/template-parts/' . $template_name . '.php';
    
    if (file_exists($template_path)) {
        include $template_path;
    }
}

/**
 * Navigation Helper Functions
 */

/**
 * Get current URL for language switching
 */
function get_current_url() {
    global $wp;
    return home_url(add_query_arg(array(), $wp->request));
}

/**
 * Get navigation items with proper links and icons
 */
function nihongo_get_nav_items() {
    return array(
        array(
            'title' => nihongo_translate('nav_home'),
            'url' => home_url(),
            'icon' => '🏠',
            'class' => 'nav-home',
            'is_current' => is_front_page()
        ),
        array(
            'title' => nihongo_translate('nav_courses'),
            'url' => nihongo_get_page_url('courses'),
            'icon' => '📚',
            'class' => 'nav-courses',
            'is_current' => is_page('courses') || is_post_type_archive('course') || is_singular('course')
        ),
        array(
            'title' => nihongo_translate('nav_j_bridge'),
            'url' => nihongo_get_page_url('j-bridge'),
            'icon' => '🌉',
            'class' => 'nav-j-bridge',
            'is_current' => is_page('j-bridge')
        ),
        array(
            'title' => nihongo_translate('nav_contact'),
            'url' => nihongo_get_page_url('contact'),
            'icon' => '📞',
            'class' => 'nav-contact',
            'is_current' => is_page('contact')
        )
    );
}

/**
 * Get page URL by slug with fallback
 */
function nihongo_get_page_url($page_slug) {
    $page = get_page_by_path($page_slug);
    if ($page) {
        return get_permalink($page->ID);
    }
    
    // Fallback URLs for common pages
    $fallback_urls = array(
        'courses' => home_url('/courses/'),
        'j-bridge' => home_url('/j-bridge/'),
        'news' => home_url('/news/'),
        'voices' => home_url('/voices/'),
        'contact' => home_url('/contact/')
    );
    
    return isset($fallback_urls[$page_slug]) ? $fallback_urls[$page_slug] : home_url();
}

/**
 * Get post type archive URL
 */
function nihongo_get_archive_url($post_type) {
    return get_post_type_archive_link($post_type);
}

/**
 * Get custom post type URLs
 */
function nihongo_get_course_url($course_id = null) {
    if ($course_id) {
        return get_permalink($course_id);
    }
    return nihongo_get_archive_url('course');
}

function nihongo_get_testimonial_url($testimonial_id = null) {
    if ($testimonial_id) {
        return get_permalink($testimonial_id);
    }
    return nihongo_get_archive_url('testimonial');
}

function nihongo_get_news_url($news_id = null) {
    if ($news_id) {
        return get_permalink($news_id);
    }
    return nihongo_get_archive_url('news');
}

/**
 * Generate navigation HTML
 */
function nihongo_render_navigation($nav_items = null, $class = 'nav-list') {
    if ($nav_items === null) {
        $nav_items = nihongo_get_nav_items();
    }
    
    $html = '<ul class="' . esc_attr($class) . '">';
    
    foreach ($nav_items as $item) {
        $active_class = $item['is_current'] ? ' active' : '';
        $html .= '<li class="nav-item' . $active_class . '">';
        $html .= '<a href="' . esc_url($item['url']) . '" class="nav-link ' . esc_attr($item['class']) . '">';
        $html .= '<span class="nav-icon">' . esc_html($item['icon']) . '</span>';
        $html .= '<span class="nav-text">' . esc_html($item['title']) . '</span>';
        $html .= '</a>';
        $html .= '</li>';
    }
    
    $html .= '</ul>';
    
    return $html;
}

/**
 * Fallback menu for primary navigation
 */
function nihongo_fallback_menu() {
    echo nihongo_render_navigation();
}

/**
 * Fallback menu for mobile navigation
 */
function nihongo_fallback_mobile_menu() {
    echo nihongo_render_navigation(null, 'mobile-nav-list');
}

/**
 * Breadcrumb Navigation
 */
function nihongo_breadcrumbs() {
    if (is_front_page()) {
        return;
    }
    
    $breadcrumbs = array();
    $breadcrumbs[] = array(
        'title' => nihongo_translate('nav_home'),
        'url' => home_url()
    );
    
    if (is_page()) {
        $page = get_post();
        $ancestors = get_post_ancestors($page->ID);
        
        if ($ancestors) {
            $ancestors = array_reverse($ancestors);
            foreach ($ancestors as $ancestor) {
                $breadcrumbs[] = array(
                    'title' => get_the_title($ancestor),
                    'url' => get_permalink($ancestor)
                );
            }
        }
        
        $breadcrumbs[] = array(
            'title' => get_the_title(),
            'url' => get_permalink()
        );
    } elseif (is_singular('course')) {
        $breadcrumbs[] = array(
            'title' => nihongo_translate('nav_courses'),
            'url' => nihongo_get_page_url('courses')
        );
        $breadcrumbs[] = array(
            'title' => get_the_title(),
            'url' => get_permalink()
        );
    } elseif (is_singular('testimonial')) {
        $breadcrumbs[] = array(
            'title' => nihongo_translate('nav_voices'),
            'url' => nihongo_get_page_url('voices')
        );
        $breadcrumbs[] = array(
            'title' => get_the_title(),
            'url' => get_permalink()
        );
    } elseif (is_singular('news')) {
        $breadcrumbs[] = array(
            'title' => nihongo_translate('nav_news'),
            'url' => nihongo_get_page_url('news')
        );
        $breadcrumbs[] = array(
            'title' => get_the_title(),
            'url' => get_permalink()
        );
    } elseif (is_post_type_archive('course')) {
        $breadcrumbs[] = array(
            'title' => nihongo_translate('nav_courses'),
            'url' => nihongo_get_page_url('courses')
        );
    } elseif (is_post_type_archive('testimonial')) {
        $breadcrumbs[] = array(
            'title' => nihongo_translate('nav_voices'),
            'url' => nihongo_get_page_url('voices')
        );
    } elseif (is_post_type_archive('news')) {
        $breadcrumbs[] = array(
            'title' => nihongo_translate('nav_news'),
            'url' => nihongo_get_page_url('news')
        );
    }
    
    if (count($breadcrumbs) <= 1) {
        return;
    }
    
    $html = '<nav class="breadcrumbs" aria-label="Breadcrumb">';
    $html .= '<ol class="breadcrumb-list">';
    
    foreach ($breadcrumbs as $index => $breadcrumb) {
        $is_last = ($index === count($breadcrumbs) - 1);
        
        $html .= '<li class="breadcrumb-item' . ($is_last ? ' current' : '') . '">';
        
        if ($is_last) {
            $html .= '<span class="breadcrumb-current">' . esc_html($breadcrumb['title']) . '</span>';
        } else {
            $html .= '<a href="' . esc_url($breadcrumb['url']) . '" class="breadcrumb-link">' . esc_html($breadcrumb['title']) . '</a>';
        }
        
        $html .= '</li>';
        
        if (!$is_last) {
            $html .= '<li class="breadcrumb-separator" aria-hidden="true">›</li>';
        }
    }
    
    $html .= '</ol>';
    $html .= '</nav>';
    
    return $html;
}

/**
 * Get related content links
 */
function nihongo_get_related_links($post_id = null) {
    if (!$post_id) {
        global $post;
        $post_id = $post->ID;
    }
    
    $related_links = array();
    
    if (is_singular('course')) {
        $related_links[] = array(
            'title' => nihongo_translate('view_all_courses'),
            'url' => nihongo_get_page_url('courses'),
            'icon' => '📚'
        );
        $related_links[] = array(
            'title' => nihongo_translate('contact_us'),
            'url' => nihongo_get_page_url('contact'),
            'icon' => '📞'
        );
    } elseif (is_singular('testimonial')) {
        $related_links[] = array(
            'title' => nihongo_translate('view_all_testimonials'),
            'url' => nihongo_get_page_url('voices'),
            'icon' => '💬'
        );
        $related_links[] = array(
            'title' => nihongo_translate('start_your_journey'),
            'url' => nihongo_get_page_url('contact'),
            'icon' => '🚀'
        );
    } elseif (is_singular('news')) {
        $related_links[] = array(
            'title' => nihongo_translate('view_all_news'),
            'url' => nihongo_get_page_url('news'),
            'icon' => '📰'
        );
        $related_links[] = array(
            'title' => nihongo_translate('subscribe_newsletter'),
            'url' => nihongo_get_page_url('contact'),
            'icon' => '📧'
        );
    }
    
    return $related_links;
}

/**
 * Get social sharing links
 */
function nihongo_get_social_links($post_id = null) {
    if (!$post_id) {
        global $post;
        $post_id = $post->ID;
    }
    
    $url = get_permalink($post_id);
    $title = get_the_title($post_id);
    $encoded_url = urlencode($url);
    $encoded_title = urlencode($title);
    
    return array(
        'twitter' => array(
            'title' => nihongo_translate('share_on_twitter'),
            'url' => "https://twitter.com/intent/tweet?url={$encoded_url}&text={$encoded_title}",
            'icon' => '🐦'
        ),
        'facebook' => array(
            'title' => nihongo_translate('share_on_facebook'),
            'url' => "https://www.facebook.com/sharer/sharer.php?u={$encoded_url}",
            'icon' => '📘'
        ),
        'linkedin' => array(
            'title' => nihongo_translate('share_on_linkedin'),
            'url' => "https://www.linkedin.com/sharing/share-offsite/?url={$encoded_url}",
            'icon' => '💼'
        ),
        'whatsapp' => array(
            'title' => nihongo_translate('share_on_whatsapp'),
            'url' => "https://wa.me/?text={$encoded_title}%20{$encoded_url}",
            'icon' => '💬'
        )
    );
}

/**
 * Theme activation hook
 */
function nihongo_theme_activation() {
    // Flush rewrite rules
    flush_rewrite_rules();
    
    // Create default pages
    $pages = array(
        'Home' => 'home.php',
        'Courses' => 'courses.php',
        'J-Bridge' => 'j-bridge.php',
        'Contact' => 'contact.php',
        'News' => 'news.php',
        'Voices' => 'voices.php'
    );
    
    foreach ($pages as $title => $template) {
        $page = get_page_by_title($title);
        if (!$page) {
            wp_insert_post(array(
                'post_title' => $title,
                'post_name' => strtolower(str_replace(' ', '-', $title)),
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'page',
                'page_template' => $template
            ));
        }
    }
}
add_action('after_switch_theme', 'nihongo_theme_activation');
