<?php
/**
 * Navier Instruments Theme Functions
 *
 * @package Navier_Instruments
 * @version 1.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Define theme constants
 */
define('NAVIER_VERSION', '1.0.0');
define('NAVIER_DIR', get_template_directory());
define('NAVIER_URI', get_template_directory_uri());

/**
 * Theme Setup
 */
function navier_setup() {
    // Load text domain for translations
    load_theme_textdomain('navier-instruments', NAVIER_DIR . '/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',
    ));

    // Custom logo support
    add_theme_support('custom-logo', array(
        'height'      => 100,
        'width'       => 300,
        'flex-height' => true,
        'flex-width'  => true,
    ));

    // Custom header support
    add_theme_support('custom-header', array(
        'default-image'      => '',
        'width'              => 1920,
        'height'             => 1080,
        'flex-width'         => true,
        'flex-height'        => true,
    ));

    // Custom background support
    add_theme_support('custom-background', array(
        'default-color' => 'ffffff',
    ));

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

    // Block editor features
    add_theme_support('wp-block-styles');
    add_theme_support('responsive-embeds');
    add_theme_support('align-wide');

    // Custom color palette for Gutenberg
    add_theme_support('editor-color-palette', array(
        array(
            'name'  => __('Primary Blue', 'navier-instruments'),
            'slug'  => 'primary',
            'color' => '#0A4D8C',
        ),
        array(
            'name'  => __('Eco Green', 'navier-instruments'),
            'slug'  => 'secondary',
            'color' => '#2ECC71',
        ),
        array(
            'name'  => __('Accent Cyan', 'navier-instruments'),
            'slug'  => 'accent',
            'color' => '#00B4D8',
        ),
        array(
            'name'  => __('Dark', 'navier-instruments'),
            'slug'  => 'dark',
            'color' => '#1A1A2E',
        ),
        array(
            'name'  => __('Light Gray', 'navier-instruments'),
            'slug'  => 'light-gray',
            'color' => '#F4F4F8',
        ),
        array(
            'name'  => __('White', 'navier-instruments'),
            'slug'  => 'white',
            'color' => '#FFFFFF',
        ),
    ));

    // Image sizes
    add_image_size('navier-hero', 1200, 800, true);
    add_image_size('navier-card', 600, 450, true);
    add_image_size('navier-thumbnail', 400, 300, true);
    add_image_size('navier-product', 800, 600, true);

    // Register navigation menus
    register_nav_menus(array(
        'primary'   => __('Primary Menu', 'navier-instruments'),
        'footer'    => __('Footer Menu', 'navier-instruments'),
        'footer-2'  => __('Footer Menu 2', 'navier-instruments'),
        'legal'     => __('Legal Menu', 'navier-instruments'),
    ));
}
add_action('after_setup_theme', 'navier_setup');

/**
 * Content Width
 */
function navier_content_width() {
    $GLOBALS['content_width'] = apply_filters('navier_content_width', 1200);
}
add_action('after_setup_theme', 'navier_content_width', 0);

/**
 * Enqueue Scripts and Styles
 */
function navier_scripts() {
    // Google Fonts - Inter & Montserrat
    wp_enqueue_style(
        'navier-google-fonts',
        'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Montserrat:wght@600;700;800&display=swap',
        array(),
        null
    );

    // Main stylesheet
    wp_enqueue_style(
        'navier-style',
        get_stylesheet_uri(),
        array(),
        NAVIER_VERSION
    );

    // Additional CSS
    wp_enqueue_style(
        'navier-custom',
        NAVIER_URI . '/assets/css/custom.css',
        array('navier-style'),
        NAVIER_VERSION
    );

    // Main JavaScript
    wp_enqueue_script(
        'navier-main',
        NAVIER_URI . '/assets/js/main.js',
        array(),
        NAVIER_VERSION,
        true
    );

    // Localize script
    wp_localize_script('navier-main', 'navierData', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('navier_nonce'),
        'homeUrl' => home_url(),
    ));

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

/**
 * Admin Scripts and Styles
 */
function navier_admin_scripts() {
    wp_enqueue_style(
        'navier-admin',
        NAVIER_URI . '/assets/css/admin.css',
        array(),
        NAVIER_VERSION
    );
}
add_action('admin_enqueue_scripts', 'navier_admin_scripts');

/**
 * Register Widget Areas
 */
function navier_widgets_init() {
    register_sidebar(array(
        'name'          => __('Sidebar', 'navier-instruments'),
        'id'            => 'sidebar-1',
        'description'   => __('Add widgets here to appear in the sidebar.', 'navier-instruments'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ));

    register_sidebar(array(
        'name'          => __('Footer Widget 1', 'navier-instruments'),
        'id'            => 'footer-1',
        'description'   => __('Add widgets here to appear in footer column 1.', 'navier-instruments'),
        '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'          => __('Footer Widget 2', 'navier-instruments'),
        'id'            => 'footer-2',
        'description'   => __('Add widgets here to appear in footer column 2.', 'navier-instruments'),
        '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'          => __('Footer Widget 3', 'navier-instruments'),
        'id'            => 'footer-3',
        'description'   => __('Add widgets here to appear in footer column 3.', 'navier-instruments'),
        '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', 'navier_widgets_init');

/**
 * Custom Walker for Navigation Menu
 */
class Navier_Nav_Walker extends Walker_Nav_Menu {
    public function start_lvl(&$output, $depth = 0, $args = null) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class=\"sub-menu\">\n";
    }

    public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        $indent = ($depth) ? str_repeat("\t", $depth) : '';

        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        if (in_array('menu-item-has-children', $classes)) {
            $classes[] = 'has-dropdown';
        }

        $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args, $depth));
        $class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';

        $id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth);
        $id = $id ? ' id="' . esc_attr($id) . '"' : '';

        $output .= $indent . '<li' . $id . $class_names . '>';

        $atts = array();
        $atts['title']  = !empty($item->attr_title) ? $item->attr_title : '';
        $atts['target'] = !empty($item->target) ? $item->target : '';
        $atts['rel']    = !empty($item->xfn) ? $item->xfn : '';
        $atts['href']   = !empty($item->url) ? $item->url : '';

        $atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args, $depth);

        $attributes = '';
        foreach ($atts as $attr => $value) {
            if (!empty($value)) {
                $value = ('href' === $attr) ? esc_url($value) : esc_attr($value);
                $attributes .= ' ' . $attr . '="' . $value . '"';
            }
        }

        $title = apply_filters('the_title', $item->title, $item->ID);
        $title = apply_filters('nav_menu_item_title', $title, $item, $args, $depth);

        $item_output = $args->before;
        $item_output .= '<a' . $attributes . '>';
        $item_output .= $args->link_before . $title . $args->link_after;

        // Add dropdown arrow for items with children
        if (in_array('menu-item-has-children', $classes) && $depth === 0) {
            $item_output .= '<svg class="dropdown-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6,9 12,15 18,9"></polyline></svg>';
        }

        $item_output .= '</a>';
        $item_output .= $args->after;

        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    }
}

/**
 * Custom Excerpt Length
 */
function navier_excerpt_length($length) {
    return 25;
}
add_filter('excerpt_length', 'navier_excerpt_length');

/**
 * Custom Excerpt More
 */
function navier_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'navier_excerpt_more');

/**
 * Add preconnect for Google Fonts
 */
function navier_resource_hints($urls, $relation_type) {
    if ($relation_type === 'preconnect') {
        $urls[] = array(
            'href' => 'https://fonts.googleapis.com',
            'crossorigin',
        );
        $urls[] = array(
            'href' => 'https://fonts.gstatic.com',
            'crossorigin',
        );
    }
    return $urls;
}
add_filter('wp_resource_hints', 'navier_resource_hints', 10, 2);

/**
 * Remove default WordPress emoji scripts
 */
function navier_disable_emojis() {
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_action('admin_print_styles', 'print_emoji_styles');
    remove_filter('the_content_feed', 'wp_staticize_emoji');
    remove_filter('comment_text_rss', 'wp_staticize_emoji');
    remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
}
add_action('init', 'navier_disable_emojis');

/**
 * Include additional files
 */
require_once NAVIER_DIR . '/inc/customizer.php';
require_once NAVIER_DIR . '/inc/template-tags.php';
require_once NAVIER_DIR . '/inc/template-functions.php';
require_once NAVIER_DIR . '/inc/theme-setup-content.php';
require_once NAVIER_DIR . '/inc/create-flo-product.php';

/**
 * Flush rewrite rules on theme activation
 */
function navier_flush_rewrite_rules() {
    navier_register_post_types();
    flush_rewrite_rules();
}
add_action('after_switch_theme', 'navier_flush_rewrite_rules');

// Flush rewrite rules once (remove after first load)
if (get_option('navier_flush_rewrite') !== '1') {
    add_action('init', function() {
        flush_rewrite_rules();
        update_option('navier_flush_rewrite', '1');
    }, 99);
}

/**
 * Register Custom Post Types
 */
function navier_register_post_types() {
    // Products CPT
    register_post_type('navier_product', array(
        'labels' => array(
            'name'               => __('Products', 'navier-instruments'),
            'singular_name'      => __('Product', 'navier-instruments'),
            'menu_name'          => __('Products', 'navier-instruments'),
            'add_new'            => __('Add New', 'navier-instruments'),
            'add_new_item'       => __('Add New Product', 'navier-instruments'),
            'edit_item'          => __('Edit Product', 'navier-instruments'),
            'new_item'           => __('New Product', 'navier-instruments'),
            'view_item'          => __('View Product', 'navier-instruments'),
            'search_items'       => __('Search Products', 'navier-instruments'),
            'not_found'          => __('No products found', 'navier-instruments'),
            'not_found_in_trash' => __('No products found in Trash', 'navier-instruments'),
        ),
        'public'              => true,
        'has_archive'         => true,
        'rewrite'             => array('slug' => 'produits'),
        'supports'            => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'),
        'menu_icon'           => 'dashicons-archive',
        'show_in_rest'        => true,
    ));

    // Product Categories Taxonomy
    register_taxonomy('product_category', 'navier_product', array(
        'labels' => array(
            'name'              => __('Product Categories', 'navier-instruments'),
            'singular_name'     => __('Product Category', 'navier-instruments'),
            'search_items'      => __('Search Categories', 'navier-instruments'),
            'all_items'         => __('All Categories', 'navier-instruments'),
            'parent_item'       => __('Parent Category', 'navier-instruments'),
            'parent_item_colon' => __('Parent Category:', 'navier-instruments'),
            'edit_item'         => __('Edit Category', 'navier-instruments'),
            'update_item'       => __('Update Category', 'navier-instruments'),
            'add_new_item'      => __('Add New Category', 'navier-instruments'),
            'new_item_name'     => __('New Category Name', 'navier-instruments'),
            'menu_name'         => __('Categories', 'navier-instruments'),
        ),
        'hierarchical'      => true,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'categorie-produit'),
        'show_in_rest'      => true,
    ));

    // Testimonials CPT
    register_post_type('navier_testimonial', array(
        'labels' => array(
            'name'               => __('Testimonials', 'navier-instruments'),
            'singular_name'      => __('Testimonial', 'navier-instruments'),
            'menu_name'          => __('Testimonials', 'navier-instruments'),
            'add_new'            => __('Add New', 'navier-instruments'),
            'add_new_item'       => __('Add New Testimonial', 'navier-instruments'),
            'edit_item'          => __('Edit Testimonial', 'navier-instruments'),
        ),
        'public'              => false,
        'show_ui'             => true,
        'supports'            => array('title', 'editor', 'thumbnail', 'custom-fields'),
        'menu_icon'           => 'dashicons-format-quote',
        'show_in_rest'        => true,
    ));
}
add_action('init', 'navier_register_post_types');

/**
 * ACF Options Page (if ACF Pro is active)
 */
if (function_exists('acf_add_options_page')) {
    acf_add_options_page(array(
        'page_title'    => __('Theme Settings', 'navier-instruments'),
        'menu_title'    => __('Navier Settings', 'navier-instruments'),
        'menu_slug'     => 'navier-settings',
        'capability'    => 'edit_posts',
        'redirect'      => false,
        'icon_url'      => 'dashicons-admin-generic',
    ));

    acf_add_options_sub_page(array(
        'page_title'    => __('Header Settings', 'navier-instruments'),
        'menu_title'    => __('Header', 'navier-instruments'),
        'parent_slug'   => 'navier-settings',
    ));

    acf_add_options_sub_page(array(
        'page_title'    => __('Footer Settings', 'navier-instruments'),
        'menu_title'    => __('Footer', 'navier-instruments'),
        'parent_slug'   => 'navier-settings',
    ));

    acf_add_options_sub_page(array(
        'page_title'    => __('Social Media', 'navier-instruments'),
        'menu_title'    => __('Social Media', 'navier-instruments'),
        'parent_slug'   => 'navier-settings',
    ));
}

/**
 * AJAX Contact Form Handler
 */
function navier_contact_form_handler() {
    check_ajax_referer('navier_nonce', 'nonce');

    $name    = sanitize_text_field($_POST['name'] ?? '');
    $email   = sanitize_email($_POST['email'] ?? '');
    $phone   = sanitize_text_field($_POST['phone'] ?? '');
    $subject = sanitize_text_field($_POST['subject'] ?? '');
    $message = sanitize_textarea_field($_POST['message'] ?? '');

    if (empty($name) || empty($email) || empty($message)) {
        wp_send_json_error(array(
            'message' => __('Please fill in all required fields.', 'navier-instruments')
        ));
    }

    if (!is_email($email)) {
        wp_send_json_error(array(
            'message' => __('Please enter a valid email address.', 'navier-instruments')
        ));
    }

    $to = get_option('admin_email');
    $email_subject = sprintf(__('[Navier Instruments] New Contact: %s', 'navier-instruments'), $subject ?: __('General Inquiry', 'navier-instruments'));

    $body = sprintf(
        __("Name: %s\nEmail: %s\nPhone: %s\nSubject: %s\n\nMessage:\n%s", 'navier-instruments'),
        $name,
        $email,
        $phone,
        $subject,
        $message
    );

    $headers = array(
        'Content-Type: text/plain; charset=UTF-8',
        'Reply-To: ' . $name . ' <' . $email . '>',
    );

    $sent = wp_mail($to, $email_subject, $body, $headers);

    if ($sent) {
        wp_send_json_success(array(
            'message' => __('Thank you for your message. We will get back to you soon!', 'navier-instruments')
        ));
    } else {
        wp_send_json_error(array(
            'message' => __('There was an error sending your message. Please try again later.', 'navier-instruments')
        ));
    }
}
add_action('wp_ajax_navier_contact', 'navier_contact_form_handler');
add_action('wp_ajax_nopriv_navier_contact', 'navier_contact_form_handler');

/**
 * Body Classes
 */
function navier_body_classes($classes) {
    if (is_front_page()) {
        $classes[] = 'front-page';
    }

    if (is_singular()) {
        $classes[] = 'singular';
    }

    if (!is_active_sidebar('sidebar-1')) {
        $classes[] = 'no-sidebar';
    }

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

/**
 * SVG Support
 */
function navier_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter('upload_mimes', 'navier_mime_types');

/**
 * Sanitize SVG uploads
 */
function navier_fix_svg($data, $file, $filename, $mimes) {
    $ext = isset($data['ext']) ? $data['ext'] : '';
    if ($ext === '' && strpos($filename, '.svg') !== false) {
        $data['ext'] = 'svg';
        $data['type'] = 'image/svg+xml';
    }
    return $data;
}
add_filter('wp_check_filetype_and_ext', 'navier_fix_svg', 10, 4);
