<?php

function create_technology_items_post_type() {
    $labels = array(
        'name'               => _x('Technologies', 'post type general name'),
        'singular_name'      => _x('Technology', 'post type singular name'),
        'menu_name'          => _x('Technologies', 'admin menu'),
        'name_admin_bar'     => _x('Technology', 'add new on admin bar'),
        'add_new'            => _x('Add New', 'technology'),
        'add_new_item'       => __('Add New Technology'),
        'new_item'           => __('New Technology'),
        'edit_item'          => __('Edit Technology'),
        'view_item'          => __('View Technology'),
        'all_items'          => __('All Technologies'),
        'search_items'       => __('Search Technologies'),
        'not_found'          => __('No technologies found.'),
        'not_found_in_trash' => __('No technologies found in Trash.'),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'items'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array('title', 'editor', 'thumbnail'),
    );

    register_post_type('technology_item', $args);
}
add_action('init', 'create_technology_items_post_type');


function create_technologies_taxonomy() {
    $labels = array(
        'name'              => _x('Technology Categories', 'taxonomy general name'),
        'singular_name'     => _x('Technology Category', 'taxonomy singular name'),
        'search_items'      => __('Search Technology Categories'),
        'all_items'         => __('All Technology Categories'),
        'parent_item'       => __('Parent Technology Category'),
        'parent_item_colon' => __('Parent Technology Category:'),
        'edit_item'         => __('Edit Technology Category'),
        'update_item'       => __('Update Technology Category'),
        'add_new_item'      => __('Add New Technology Category'),
        'new_item_name'     => __('New Technology Category Name'),
        'menu_name'         => __('Technology Categories'),
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'has_archive'       => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'technologies'),
    );

    register_taxonomy('technologies', array('technology_item'), $args);
}
add_action('init', 'create_technologies_taxonomy');


function add_favorite_meta_box() {
    add_meta_box(
        'favorite_item_meta_box',
        __('Favorite Item'),
        'render_favorite_meta_box',
        'technology_item',
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'add_favorite_meta_box');

function render_favorite_meta_box($post) {
    $value = get_post_meta($post->ID, '_favorite_item', true);
    ?>
<label for="favorite_item">
    <input type="checkbox" name="favorite_item" id="favorite_item" value="1" <?php checked($value, '1'); ?> />
    <?php _e('Mark as favorite'); ?>
</label>
<?php
}

function save_favorite_meta_box_data($post_id) {
    if (array_key_exists('favorite_item', $_POST)) {
        update_post_meta($post_id, '_favorite_item', '1');
    } else {
        update_post_meta($post_id, '_favorite_item', '0');
    }
}
add_action('save_post', 'save_favorite_meta_box_data');


function display_technologies_shortcode($atts) {
   // Get shortcode attributes
    $atts = shortcode_atts(array(
        'id' => '',
    ), $atts, 'technologies');

// Initialize output
$output = '';
$main_technology_term = get_term_by('id', $atts['id'], 'technologies');

if ($main_technology_term) {
    $output .= '<section>
                    <section class="w-full px-6 lg:px-16 mx-auto max-w-screen-2xl py-10 sm:py-20 flex flex-col lg:flex-row gap-10" >
                        <div class="w-full lg:max-w-sm">
                            <h2 class="font-medium mb-5"> ' . esc_html($main_technology_term->name) . '</h2>
                            <p class="max-w-3xl content-1"> ' . esc_html($main_technology_term->description) . '</p>
                        </div>';

    // Fetch child terms of the main technology term
    $child_terms = get_terms(array(
        'taxonomy'   => 'technologies',
        'parent'     => $main_technology_term->term_id,
        'hide_empty' => false,
        'orderby' => 'date',
        'order' => 'ASC',
    ));

    // If there are child terms
    if (!empty($child_terms)) {
        $output .= '<div class="flex flex-col gap-8">';
        
            
        foreach ($child_terms as $child_term) {
            $output .= '<div class="flex flex-col gap-10">
            <div>';
            $output .= '<h3 class="font-medium mb-3 h4-styles">' . esc_html($child_term->name) . '</h3>';


            // Fetch posts in each child term (technology_item)
            $child_term_posts = new WP_Query(array(
                'post_type' => 'technology_item',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'technologies',
                        'field'    => 'term_id',
                        'terms'    => $child_term->term_id,
                    ),
                ),
            ));

            if ($child_term_posts->have_posts()) {
                $output .= '<ul class="list-disc technologies-list list-inside grid grid-cols-2 sm:grid-cols-4 gap-4 lg:flex lg:flex-wrap">';
                while ($child_term_posts->have_posts()) : $child_term_posts->the_post();
                $output .= '<li class="bg-white rounded-lg shadow-lg relative px-4 py-2">';
                    if (has_post_thumbnail()) {
                        $imageUrl =  wp_get_attachment_image_src(get_post_thumbnail_id(), array(70,70));

                        $output .=  '<img class="mx-auto" alt="'. get_the_title() .'"  src="' . esc_url($imageUrl[0]) . '">';
                    }
                    $output .= '<span class="mx-auto w-fit block mt-2">' . get_the_title() . '</span>';

                    

                    $output .= '</li>';
                endwhile;
                $output .= '</ul>';
            } else {
                $output .= '<p>No items found under ' . esc_html($child_term->name) . '</p>';
            }

            wp_reset_postdata();
            $output .= '</div></div>';
        }
        $output .= '</section></section>';
        
    } else {
        // If no child terms, fetch posts directly under the main term
        $main_term_posts = new WP_Query(array(
            'post_type' => 'technology_item',
            'tax_query' => array(
                array(
                    'taxonomy' => 'technologies',
                    'field'    => 'term_id',
                    'terms'    => $main_technology_term->term_id,
                ),
            ),
        ));

        if ($main_term_posts->have_posts()) {
            $output .= '<ul class="list-disc list-inside grid grid-cols-2 sm:grid-cols-4 gap-4 lg:flex lg:flex-wrap">';
                while ($main_term_posts->have_posts()) : $main_term_posts->the_post();
                $output .= '<div class="bg-white rounded-lg shadow-lg relative px-4 py-2">';
                    if (has_post_thumbnail()) {
                        $imageUrl =  wp_get_attachment_image_src(get_post_thumbnail_id(), array(70,70));

                        $output .=  '<img alt="'. get_the_title() .'"  src="' . esc_url($imageUrl[0]) . '">';
                    }
                    $output .= '<span class="mx-auto w-fit block mt-2">' . get_the_title() . '</span>';
                    $output .= '</div>';
                endwhile;
                $output .= '</ul>';
        } else {
            $output .= '<p>No items found under ' . esc_html($main_technology_term->name) . '</p>';
        }

        $output .= '</section></section>';
        wp_reset_postdata();
    }
} else {
    $output .= '<p>Main technology term not found.</p>';
}


return $output;
}
add_shortcode('technologies', 'display_technologies_shortcode');

function display_technology_shortcode($atts) {
    $atts = shortcode_atts(null, $atts, 'favorite_technologies');

    $args = array(
        'post_type' => 'technology_item',
        'meta_key' => '_favorite_item',
        'meta_value' => '1',
    );

    $query = new WP_Query($args);
    $output = "";
    
    if ($query->have_posts()) {
        $output .= '<section class="relative">
                    <section class="w-full px-6 lg:px-16 mx-auto max-w-screen-2xl py-10 sm:py-20 relative z-10"> 
                    <div class="translate: none; rotate: none; scale: none; transform: translate(0px, 0px); opacity: 1;">
                    <div class="text-center shadow-xl rounded-xl p-10 flex flex-col gap-7 bg-white">
                    <h2>Our technologies</h2>
                    <p class=" text-xl max-w-4xl mx-auto">We build with tomorrow in mind, ensuring your digital platform remains innovative and competitive.</p>
                    <div class="flex gap-10 items-center justify-center flex-wrap">
                    ';

        while ($query->have_posts()) {
            $query->the_post();
            $imageUrl =  wp_get_attachment_image_src(get_post_thumbnail_id(), array(50,50));
            $output .=  '<img width="50" height="50" alt="'. get_the_title() .'"  src="' . esc_url($imageUrl[0]) . '">';
        }
        $output .= '</div></div></div></section></section>';
        wp_reset_postdata();
    }
    return $output;
}
add_shortcode('favorite_technologies', 'display_technology_shortcode');



// function enqueue_admin_sortable_script($hook) {
//     if ('edit-tags.php' !== $hook || !isset($_GET['taxonomy']) || 'technologies' !== $_GET['taxonomy']) {
//         return;
//     }

//     // Enqueue jQuery UI Sortable
//     wp_enqueue_script('jquery-ui-sortable');

//     // Enqueue custom script
//     wp_enqueue_script('custom-taxonomy-sort', get_template_directory_uri() . '/js/custom-taxonomy-sort.js', array('jquery-ui-sortable'), null, true);

//     // Add AJAX URL and nonce for security
//     wp_localize_script('custom-taxonomy-sort', 'customSort', array(
//         'ajax_url' => admin_url('admin-ajax.php'),
//         'nonce'    => wp_create_nonce('taxonomy_sort_nonce'),
//     ));
// }
// add_action('admin_enqueue_scripts', 'enqueue_admin_sortable_script');


// function save_taxonomy_order() {
//     // Check nonce for security
//     check_ajax_referer('taxonomy_sort_nonce', 'nonce');

//     if (!current_user_can('manage_options') || !isset($_POST['order'])) {
//         wp_send_json_error('Unauthorized request.');
//         return;
//     }

//     // Get the list of term IDs in the new order
//     $order = $_POST['order'];
//     foreach ($order as $index => $term_id) {
//         update_term_meta($term_id, 'taxonomy_order', $index + 1);
//     }

//     wp_send_json_success('Order updated successfully.');
// }
// add_action('wp_ajax_save_taxonomy_order', 'save_taxonomy_order');

// function custom_taxonomy_order_in_admin($query) {
//     if (!is_admin()) return;


//     // // Check if we are on the specific taxonomy edit screen
//     // if ($query->query_vars['taxonomy'] === 'technologies') { // Replace 'technologies' with your taxonomy
//     //     $query->query_vars['orderby'] = 'meta_value_num';
//     //     $query->query_vars['meta_key'] = 'taxonomy_order';
//     //     $query->query_vars['order'] = 'ASC';
//     // }

//     if (isset($query->query_vars['taxonomy']) && $query->query_vars['taxonomy'] === 'technologies') {
//         // Set meta query to fetch the custom order
//         $query->query_vars['meta_key'] = 'taxonomy_order';
//         $query->query_vars['orderby'] = array(
//             'meta_value_num' => 'ASC',  // Sort by custom field
//             'name'           => 'ASC'   // Secondary sort by name in case meta field is missing
//         );
//         $query->query_vars['order'] = 'ASC';
//     }
// }
// add_action('pre_get_terms', 'custom_taxonomy_order_in_admin');