<?php
/**
 * Flavor – Restaurant Menu
 *
 * @package    FlavorMenu
 * @copyright  Copyright (c) 2024 Flavor Studio
 * @license    GPL-2.0-or-later
 * @link       https://flavor-menu.com
 */

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

class Flavor_Category_Sort {

    public static function init() {
        add_action( 'init', array( __CLASS__, 'register_term_meta' ) );
        add_action( 'admin_menu', array( __CLASS__, 'add_sort_page' ) );
        add_action( 'wp_ajax_flavor_save_cat_order', array( __CLASS__, 'ajax_save_order' ) );
    }

    /**
     * Register the sort_order term meta.
     */
    public static function register_term_meta() {
        register_term_meta( 'flavor_menu_cat', 'flavor_sort_order', array(
            'type'              => 'integer',
            'single'            => true,
            'default'           => 0,
            'sanitize_callback' => 'absint',
            'show_in_rest'      => false,
        ) );
    }

    /**
     * Add submenu page under Menu.
     */
    public static function add_sort_page() {
        add_submenu_page(
            'edit.php?post_type=flavor_menu_item',
            __( 'Sort Categories', 'flavor-restaurant-menu' ),
            __( 'Sort Categories', 'flavor-restaurant-menu' ),
            'manage_categories',
            'flavor-category-sort',
            array( __CLASS__, 'render_sort_page' )
        );
    }

    /**
     * Render the drag & drop sort page.
     */
    public static function render_sort_page() {
        $cats = get_terms( array(
            'taxonomy'   => 'flavor_menu_cat',
            'hide_empty' => false,
        ) );

        if ( is_wp_error( $cats ) ) {
            $cats = array();
        }

        $parents  = array();
        $children = array();

        foreach ( $cats as $cat ) {
            if ( $cat->parent == 0 ) {
                $parents[] = $cat;
            } else {
                if ( ! isset( $children[ $cat->parent ] ) ) {
                    $children[ $cat->parent ] = array();
                }
                $children[ $cat->parent ][] = $cat;
            }
        }

        usort( $parents, function( $a, $b ) {
            $oa = (int) get_term_meta( $a->term_id, 'flavor_sort_order', true );
            $ob = (int) get_term_meta( $b->term_id, 'flavor_sort_order', true );
            return $oa - $ob;
        } );

        foreach ( $children as $pid => &$child_list ) {
            usort( $child_list, function( $a, $b ) {
                $oa = (int) get_term_meta( $a->term_id, 'flavor_sort_order', true );
                $ob = (int) get_term_meta( $b->term_id, 'flavor_sort_order', true );
                return $oa - $ob;
            } );
        }
        unset( $child_list );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Sort Categories', 'flavor-restaurant-menu' ); ?></h1>
            <?php flavor_docs_link_html( '#dishes' ); ?>
            <p class="description" style="margin-bottom: 16px;">
                <?php esc_html_e( 'Drag categories into the desired order. Subcategories can only be sorted within their parent category. The order is saved automatically.', 'flavor-restaurant-menu' ); ?>
            </p>

            <?php if ( empty( $parents ) ) : ?>
                <p><?php esc_html_e( 'No categories found.', 'flavor-restaurant-menu' ); ?>
                    <a href="<?php echo esc_url( admin_url( 'edit-tags.php?taxonomy=flavor_menu_cat&post_type=flavor_menu_item' ) ); ?>">
                        <?php esc_html_e( 'Create categories →', 'flavor-restaurant-menu' ); ?>
                    </a>
                </p>
            <?php else : ?>
                <div id="flavor-cat-sort-feedback" style="display:none;" class="notice notice-success is-dismissible">
                    <p><?php esc_html_e( 'Order saved!', 'flavor-restaurant-menu' ); ?></p>
                </div>

                <ul id="flavor-cat-sort-list" class="flavor-cat-sort-list">
                    <?php foreach ( $parents as $parent ) : ?>
                        <li class="flavor-cat-sort-item flavor-cat-sort-item--parent" data-term-id="<?php echo esc_attr( $parent->term_id ); ?>">
                            <div class="flavor-cat-sort-row">
                                <span class="flavor-cat-sort-handle dashicons dashicons-menu"></span>
                                <span class="flavor-cat-sort-name"><?php echo esc_html( $parent->name ); ?></span>
                                <span class="flavor-cat-sort-count"><?php echo esc_html( sprintf(
                                    /* translators: %s: number of menu items in this category */
                                    _n( '%s item', '%s items', $parent->count, 'flavor-restaurant-menu' ),
                                    $parent->count
                                ) ); ?></span>
                                <span class="flavor-cat-sort-slug"><?php echo esc_html( $parent->slug ); ?></span>
                            </div>
                            <?php if ( ! empty( $children[ $parent->term_id ] ) ) : ?>
                                <ul class="flavor-cat-sort-children">
                                    <?php foreach ( $children[ $parent->term_id ] as $child ) : ?>
                                        <li class="flavor-cat-sort-item flavor-cat-sort-item--child" data-term-id="<?php echo esc_attr( $child->term_id ); ?>">
                                            <span class="flavor-cat-sort-handle dashicons dashicons-menu"></span>
                                            <span class="flavor-cat-sort-child-indent">↳</span>
                                            <span class="flavor-cat-sort-name"><?php echo esc_html( $child->name ); ?></span>
                                            <span class="flavor-cat-sort-count"><?php echo esc_html( sprintf(
                                                /* translators: %s: number of menu items in this category */
                                                _n( '%s item', '%s items', $child->count, 'flavor-restaurant-menu' ),
                                                $child->count
                                            ) ); ?></span>
                                            <span class="flavor-cat-sort-slug"><?php echo esc_html( $child->slug ); ?></span>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * AJAX handler to save category order.
     */
    public static function ajax_save_order() {
        check_ajax_referer( 'flavor_cat_sort_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_categories' ) ) {
            wp_send_json_error( __( 'Insufficient permissions.', 'flavor-restaurant-menu' ) );
        }

        $order = isset( $_POST['order'] ) ? array_map( 'absint', $_POST['order'] ) : array();

        if ( empty( $order ) ) {
            wp_send_json_error( __( 'No order data submitted.', 'flavor-restaurant-menu' ) );
        }

        foreach ( $order as $position => $term_id ) {
            update_term_meta( $term_id, 'flavor_sort_order', $position );
        }

        wp_send_json_success( array( 'message' => 'Order saved' ) );
    }

    /**
     * Get sorted categories.
     */
    public static function get_sorted_categories( $args = array() ) {
        $defaults = array(
            'taxonomy'   => 'flavor_menu_cat',
            'hide_empty' => false,
        );

        $terms = get_terms( array_merge( $defaults, $args ) );

        if ( is_wp_error( $terms ) || empty( $terms ) ) {
            return array();
        }

        usort( $terms, function( $a, $b ) {
            $order_a = (int) get_term_meta( $a->term_id, 'flavor_sort_order', true );
            $order_b = (int) get_term_meta( $b->term_id, 'flavor_sort_order', true );
            return $order_a - $order_b;
        } );

        return $terms;
    }
}
