<?php
/**
 * Flavor – Restaurant Menu
 *
 * Meta boxes for the Menu Item edit screen (Free version).
 * Price Variants: single price only.
 * Badges, Allergens & Nutrition: informational upsell notices — no Pro code included.
 *
 * @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_Metaboxes {

    public static function init() {
        add_action( 'add_meta_boxes',             array( __CLASS__, 'add_meta_boxes' ) );
        add_action( 'save_post_flavor_menu_item', array( __CLASS__, 'save_meta' ), 10, 2 );
        add_action( 'save_post_flavor_menu_item', array( __CLASS__, 'save_categories' ), 11, 1 );
    }

    /**
     * Register meta boxes.
     */
    public static function add_meta_boxes() {
        // Replace the default WordPress taxonomy meta box with a custom one.
        remove_meta_box( 'flavor_menu_catdiv',    'flavor_menu_item', 'side' );
        remove_meta_box( 'tagsdiv-flavor_menu_cat', 'flavor_menu_item', 'side' );

        add_meta_box(
            'flavor_menu_cat_custom',
            __( 'Category', 'flavor-restaurant-menu' ),
            array( __CLASS__, 'render_category_metabox' ),
            'flavor_menu_item',
            'side',
            'high'
        );

        add_meta_box(
            'flavor_menu_prices',
            __( 'Price & Details', 'flavor-restaurant-menu' ),
            array( __CLASS__, 'render_prices_metabox' ),
            'flavor_menu_item',
            'normal',
            'high'
        );

        add_meta_box(
            'flavor_menu_settings',
            __( 'Item Settings', 'flavor-restaurant-menu' ),
            array( __CLASS__, 'render_settings_metabox' ),
            'flavor_menu_item',
            'side',
            'default'
        );
    }

    /**
     * Price & details metabox (Free: single price, subtitle).
     */
    public static function render_prices_metabox( $post ) {
        wp_nonce_field( 'flavor_menu_prices_nonce', 'flavor_prices_nonce' );

        $prices   = get_post_meta( $post->ID, '_flavor_prices', true );
        $subtitle = get_post_meta( $post->ID, '_flavor_subtitle', true );

        $price_val = ( is_array( $prices ) && ! empty( $prices[0]['price'] ) )
            ? $prices[0]['price']
            : '';
        ?>
        <table class="form-table" style="margin:0;">
            <tr>
                <th style="width:140px;padding:8px 10px 8px 0;">
                    <label for="flavor_subtitle"><strong><?php esc_html_e( 'Subtitle', 'flavor-restaurant-menu' ); ?></strong></label>
                </th>
                <td style="padding:8px 0;">
                    <input
                        type="text"
                        id="flavor_subtitle"
                        name="flavor_subtitle"
                        value="<?php echo esc_attr( $subtitle ); ?>"
                        class="widefat"
                        placeholder="<?php esc_attr_e( 'Short description shown below the title', 'flavor-restaurant-menu' ); ?>"
                    />
                </td>
            </tr>
            <tr>
                <th style="padding:8px 10px 8px 0;">
                    <label for="flavor_price_single"><strong><?php esc_html_e( 'Price', 'flavor-restaurant-menu' ); ?></strong></label>
                </th>
                <td style="padding:8px 0;">
                    <input
                        type="hidden"
                        name="flavor_prices[0][label]"
                        value=""
                    />
                    <input
                        type="text"
                        id="flavor_price_single"
                        name="flavor_prices[0][price]"
                        value="<?php echo esc_attr( $price_val ); ?>"
                        placeholder="<?php esc_attr_e( 'e.g. 12.90 €', 'flavor-restaurant-menu' ); ?>"
                        class="regular-text"
                    />
                    <p class="description" style="margin-top:6px;">
                        <?php
                        printf(
                            /* translators: %s: link to Flavor Pro */
                            esc_html__( 'Need multiple prices with labels (Small / Large)? %s', 'flavor-restaurant-menu' ),
                            '<a href="https://flavor-menu.com/#pricing" target="_blank" rel="noopener">'
                            . esc_html__( 'Available in Flavor Pro →', 'flavor-restaurant-menu' )
                            . '</a>'
                        );
                        ?>
                    </p>
                </td>
            </tr>
        </table>
        <?php
    }

    /**
     * Settings metabox (sort order only — badges are a Pro feature shown via upsell).
     */
    public static function render_settings_metabox( $post ) {
        $sort_order = get_post_meta( $post->ID, '_flavor_sort_order', true );
        ?>
        <p>
            <label for="flavor_sort_order"><strong><?php esc_html_e( 'Sort Order', 'flavor-restaurant-menu' ); ?></strong></label><br>
            <input
                type="number"
                id="flavor_sort_order"
                name="flavor_sort_order"
                value="<?php echo esc_attr( $sort_order ?: 0 ); ?>"
                class="widefat"
                min="0"
                step="1"
            />
            <span class="description"><?php esc_html_e( 'Lower number = higher position.', 'flavor-restaurant-menu' ); ?></span>
        </p>
        <?php
    }

    /**
     * Save meta data.
     */
    public static function save_meta( $post_id, $post ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( ! isset( $_POST['flavor_prices_nonce'] ) ) return;
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['flavor_prices_nonce'] ) ), 'flavor_menu_prices_nonce' ) ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;

        // Prices (Free: single price, no label)
        $raw_prices   = isset( $_POST['flavor_prices'] ) ? wp_unslash( $_POST['flavor_prices'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each field sanitized via sanitize_text_field() in the loop below.
        $clean_prices = array();
        foreach ( $raw_prices as $variant ) {
            $label = sanitize_text_field( $variant['label'] ?? '' );
            $price = sanitize_text_field( $variant['price'] ?? '' );
            if ( $label !== '' || $price !== '' ) {
                $clean_prices[] = array( 'label' => $label, 'price' => $price );
            }
        }
        update_post_meta( $post_id, '_flavor_prices', $clean_prices );

        // Subtitle
        if ( isset( $_POST['flavor_subtitle'] ) ) {
            update_post_meta( $post_id, '_flavor_subtitle', sanitize_text_field( wp_unslash( $_POST['flavor_subtitle'] ) ) );
        }

        // Sort order
        if ( isset( $_POST['flavor_sort_order'] ) ) {
            update_post_meta( $post_id, '_flavor_sort_order', absint( $_POST['flavor_sort_order'] ) );
        }
    }

    /**
     * Save custom category metabox.
     */
    public static function save_categories( $post_id ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( get_post_type( $post_id ) !== 'flavor_menu_item' ) return;
        if ( ! isset( $_POST['flavor_cat_nonce'] ) ) return;
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['flavor_cat_nonce'] ) ), 'flavor_menu_cat_nonce' ) ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;

        $term_ids = isset( $_POST['flavor_menu_cat'] ) ? array_map( 'absint', (array) $_POST['flavor_menu_cat'] ) : array();
        wp_set_object_terms( $post_id, $term_ids, 'flavor_menu_cat' );
    }

    /**
     * Custom category metabox — reliable hierarchical display.
     */
    public static function render_category_metabox( $post ) {
        wp_nonce_field( 'flavor_menu_cat_nonce', 'flavor_cat_nonce' );

        $all_cats = get_terms( array(
            'taxonomy'   => 'flavor_menu_cat',
            'hide_empty' => false,
            'orderby'    => 'name',
        ) );

        if ( is_wp_error( $all_cats ) || empty( $all_cats ) ) {
            echo '<p class="description">' . esc_html__( 'No categories found.', 'flavor-restaurant-menu' ) . ' ';
            echo '<a href="' . esc_url( admin_url( 'edit-tags.php?taxonomy=flavor_menu_cat&post_type=flavor_menu_item' ) ) . '">' . esc_html__( 'Create categories →', 'flavor-restaurant-menu' ) . '</a></p>';
            return;
        }

        $selected = wp_get_object_terms( $post->ID, 'flavor_menu_cat', array( 'fields' => 'ids' ) );
        if ( is_wp_error( $selected ) ) $selected = array();

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

        echo '<div class="flavor-cat-metabox" style="max-height:300px;overflow-y:auto;">';
        foreach ( $parents as $parent ) {
            $checked = in_array( $parent->term_id, $selected, true ) ? ' checked' : '';
            echo '<label style="display:block;padding:4px 0;font-weight:600;">';
            echo '<input type="checkbox" name="flavor_menu_cat[]" value="' . esc_attr( $parent->term_id ) . '"' . esc_attr( $checked ) . '> ';
            echo esc_html( $parent->name );
            echo '</label>';

            if ( ! empty( $children[ $parent->term_id ] ) ) {
                foreach ( $children[ $parent->term_id ] as $child ) {
                    $checked_c = in_array( $child->term_id, $selected, true ) ? ' checked' : '';
                    echo '<label style="display:block;padding:3px 0 3px 20px;">';
                    echo '<input type="checkbox" name="flavor_menu_cat[]" value="' . esc_attr( $child->term_id ) . '"' . esc_attr( $checked_c ) . '> ';
                    echo '↳ ' . esc_html( $child->name );
                    echo '</label>';
                }
            }
        }
        echo '</div>';
    }
}
