<?php

/**
 * Product metabox for configuring the 3D customizer per product.
 *
 * Provides the UI for uploading a 3D model, defining customization steps,
 * assigning textures to options, and controlling geometry visibility.
 *
 * @package ProductCustomizer
 */
// admin/product-metabox.php
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Renders the disabled Bulk Add Materials button for free users.
 */
function dprcu_render_bulk_add_button_disabled() {
    ?>
  <div class="premium-only-notice">
    <span class="dashicons dashicons-lock"></span>
    <?php 
    esc_html_e( 'Bulk adding multiple options at once requires Premium.', '3d-product-customizer' );
    ?>
    <a href="<?php 
    echo esc_url( dprcu_checkout_url() );
    ?>" target="_blank" rel="noopener noreferrer">
      <?php 
    esc_html_e( 'Unlock Pro &rarr;', '3d-product-customizer' );
    ?>
    </a>
  </div>
  <?php 
}

/**
 * Renders the locked geometry controls message for free users.
 */
function dprcu_render_geometry_controls_locked() {
    ?>
  <div class="psc-geo-locked premium-only-notice">
    <span class="dashicons dashicons-lock"></span>
    <?php 
    esc_html_e( 'Show/Hide mesh and step controls require Premium.', '3d-product-customizer' );
    ?>
    <a href="<?php 
    echo esc_url( dprcu_checkout_url() );
    ?>" target="_blank"
      rel="noopener noreferrer"><?php 
    esc_html_e( 'Unlock Pro &rarr;', '3d-product-customizer' );
    ?></a>
  </div>
  <?php 
}

function dprcu_add_product_metabox() {
    add_meta_box(
        'dprcu_config_metabox',
        '3D Configurator',
        'dprcu_metabox_html',
        'product',
        'normal',
        'high'
    );
}

add_action( 'add_meta_boxes', 'dprcu_add_product_metabox' );
/**
 * Returns all model_texture posts as a lightweight array for JS localisation.
 *
 * Result is cached in a transient and invalidated whenever a model_texture
 * post is saved or deleted, keeping the admin UI always up-to-date while
 * avoiding a full get_posts() call on every product edit page load.
 *
 * @return array[]
 */
function dprcu_get_all_textures() {
    $cache_key = 'dprcu_all_textures';
    $data = get_transient( $cache_key );
    if ( false !== $data ) {
        return $data;
    }
    $posts = get_posts( array(
        'post_type'      => 'dprcu_model_texture',
        'posts_per_page' => -1,
        'orderby'        => 'title',
        'order'          => 'ASC',
    ) );
    $data = array();
    foreach ( $posts as $p ) {
        $terms = get_the_terms( $p->ID, 'dprcu_texture_category' );
        $cats = array();
        if ( $terms && !is_wp_error( $terms ) ) {
            foreach ( $terms as $term ) {
                $cats[] = array(
                    'id'   => $term->term_id,
                    'name' => $term->name,
                );
            }
        }
        $data[] = array(
            'id'         => $p->ID,
            'name'       => $p->post_title,
            'img'        => ( get_the_post_thumbnail_url( $p->ID, 'thumbnail' ) ? get_the_post_thumbnail_url( $p->ID, 'thumbnail' ) : '' ),
            'color'      => ( get_post_meta( $p->ID, '_dprcu_texture_color', true ) ? get_post_meta( $p->ID, '_dprcu_texture_color', true ) : '' ),
            'categories' => $cats,
        );
    }
    // Cache for one hour; cleared by dprcu_bust_textures_cache() below.
    set_transient( $cache_key, $data, HOUR_IN_SECONDS );
    return $data;
}

/**
 * Busts the texture list transient whenever a model_texture is saved or deleted.
 *
 * @param int $post_id Post ID.
 */
function dprcu_bust_textures_cache(  $post_id  ) {
    if ( 'dprcu_model_texture' === get_post_type( $post_id ) ) {
        delete_transient( 'dprcu_all_textures' );
    }
}

add_action( 'save_post', 'dprcu_bust_textures_cache' );
add_action( 'delete_post', 'dprcu_bust_textures_cache' );
function dprcu_metabox_html(  $post  ) {
    $model_url = get_post_meta( $post->ID, '_dprcu_3d_model_url', true );
    $viewer_only = get_post_meta( $post->ID, '_dprcu_3d_viewer_only', true );
    $config_json = get_post_meta( $post->ID, '_dprcu_customizer_config', true );
    $steps_data = ( $config_json ? json_decode( $config_json, true ) : array() );
    $camera_pos = get_post_meta( $post->ID, '_dprcu_camera_position', true );
    wp_nonce_field( 'dprcu_save_metabox', 'dprcu_metabox_nonce' );
    ?>
  <div class="model-uploader-container">
    <label class="drcpu-label"
      for="_3d_model_url_field"><?php 
    esc_html_e( '3D Model (.glb)', '3d-product-customizer' );
    ?></label>
    <div class="model-uploader-inner">
      <input class="dprcu_input" type="text" name="_dprcu_3d_model_url" id="_3d_model_url_field"
        value="<?php 
    echo esc_url( $model_url );
    ?>" />
      <button type="button" class="button"
        id="upload-model-button"><?php 
    esc_html_e( 'Select Model', '3d-product-customizer' );
    ?></button>
    </div>

  </div>


  <div class="dprcu-model-scan-row">
    <div id="admin-model-preview">
      <div class="dprcu-cam-toolbar">
        <button type="button" class="button button-small"
          id="cam-save-btn"><?php 
    esc_html_e( 'Save View', '3d-product-customizer' );
    ?></button>
        <button type="button" class="button button-small"
          id="cam-reset-btn"><?php 
    esc_html_e( 'Reset View', '3d-product-customizer' );
    ?></button>
      </div>
    </div>

    <div class="detected-parts-panel">
      <h4><?php 
    esc_html_e( 'Detected Meshes from Model', '3d-product-customizer' );
    ?></h4>
      <div class="detected-parts-list" id="detected-parts-list">
        <em><?php 
    esc_html_e( 'Load a 3D model to detect meshes...', '3d-product-customizer' );
    ?></em>
      </div>
    </div>
  </div>


  <input type="hidden" name="_dprcu_camera_position" id="_dprcu_camera_position"
    value="<?php 
    echo esc_attr( ( $camera_pos ?: '' ) );
    ?>" />

  <div class="psc-viewer-only-row">
    <label class="psc-viewer-only-label">
      <input type="checkbox" name="_dprcu_3d_viewer_only" id="psc_viewer_only" value="1" <?php 
    checked( $viewer_only, '1' );
    ?> />
      <span>
        <strong><?php 
    esc_html_e( 'Viewer Only Mode', '3d-product-customizer' );
    ?></strong><br>
        <small><?php 
    esc_html_e( 'Show the 3D model in the product gallery without customization steps.', '3d-product-customizer' );
    ?></small>
      </span>
    </label>
  </div>

  <div id="psc-steps-area">

    <div id="steps-container">
      <?php 
    if ( empty( $steps_data ) ) {
        ?>
        <div class="empty-message" id="empty-msg">
          <?php 
        esc_html_e( 'No steps yet. Click "+ Add Step" to begin.', '3d-product-customizer' );
        ?>
        </div>
        <?php 
    } else {
        foreach ( $steps_data as $step_id => $step ) {
            ?>
          <div class="config-step closed" data-step-id="<?php 
            echo esc_attr( $step_id );
            ?>">
            <div class="step-header">

              <span class="step-drag-handle" title="Drag to reorder">☰</span>

              <input type="text" class="name-input" name="steps[<?php 
            echo esc_attr( $step_id );
            ?>][name]"
                value="<?php 
            echo esc_attr( $step['name'] ?? 'Step' );
            ?>" placeholder="Step Name (e.g. Upper, Sole, Logo)" />
              <div class="filler"></div>


              <button type="button"
                class="button button-delete remove-step-btn"><?php 
            esc_html_e( 'Remove Step', '3d-product-customizer' );
            ?>
                <span class="dashicons dashicons-trash"></span>
              </button>
              <span class="step-toggle-btn dashicons dashicons-arrow-down-alt2" title="Toggle Step"></span>

            </div>

            <div class="step-body">
              <div class="step-description">
                <label class="drcpu-label"
                  for="steps[<?php 
            echo esc_attr( $step_id );
            ?>][description]"><?php 
            esc_html_e( 'Step Description', '3d-product-customizer' );
            ?></label>
                <textarea class="step-description-input" name="steps[<?php 
            echo esc_attr( $step_id );
            ?>][description]"
                  placeholder="<?php 
            esc_attr_e( '(Optional) Step Description', '3d-product-customizer' );
            ?>"><?php 
            echo esc_textarea( $step['description'] ?? '' );
            ?></textarea>
              </div>
              <div class="icon-picker">
                <label class="drcpu-label"
                  for="steps[<?php 
            echo esc_attr( $step_id );
            ?>][icon]"><?php 
            esc_html_e( 'Icon Image', '3d-product-customizer' );
            ?>
                  <small>(<?php 
            esc_html_e( 'shown on mobile devices', '3d-product-customizer' );
            ?>)</small></label>
                <div>
                  <?php 
            if ( !empty( $step['icon'] ) ) {
                ?>
                    <img class="icon-preview step" src="<?php 
                echo esc_url( $step['icon'] );
                ?>">
                  <?php 
            } else {
                ?>
                    <img class="icon-preview step" src="" alt="Icon Preview">
                  <?php 
            }
            ?>
                  <button type="button"
                    class="button button-small choose-step-icon-btn"><?php 
            esc_html_e( 'Choose Image', '3d-product-customizer' );
            ?></button>
                  <button type="button" class="button button-small button-link-delete clear-step-icon-btn" <?php 
            echo ( empty( $step['icon'] ) ? 'style="display:none"' : '' );
            ?>><?php 
            esc_html_e( 'Clear', '3d-product-customizer' );
            ?></button>
                  <input type="hidden" class="step-icon-input" name="steps[<?php 
            echo esc_attr( $step_id );
            ?>][icon]"
                    value="<?php 
            echo esc_attr( $step['icon'] ?? '' );
            ?>">
                </div>
              </div>
              <div class="step-targets">
                <label class="drcpu-label"><?php 
            esc_html_e( 'Target Meshes', '3d-product-customizer' );
            ?>
                  <small><?php 
            esc_html_e( '(which parts of the model this step customizes)', '3d-product-customizer' );
            ?></small></label>
                <select multiple
                  class="dprcu-s2 dprcu-mesh-select"
                  name="steps[<?php 
            echo esc_attr( $step_id );
            ?>][targets][]"
                  data-selected="<?php 
            echo esc_attr( implode( ',', $step['targets'] ?? array() ) );
            ?>"
                  data-placeholder="<?php 
            esc_attr_e( 'Select meshes…', '3d-product-customizer' );
            ?>">
                </select>
              </div>

              <div class="step-options-container">
                <h3><?php 
            esc_html_e( 'Options', '3d-product-customizer' );
            ?></h3>
                <div class="options-list">
                  <?php 
            if ( !empty( $step['options'] ) ) {
                foreach ( $step['options'] as $opt_id => $option ) {
                    $tex_ids_raw = $option['texture_ids'] ?? $option['texture_id'] ?? '';
                    $tex_ids = ( is_array( $tex_ids_raw ) ? $tex_ids_raw : array_filter( explode( ',', $tex_ids_raw ) ) );
                    ?>
                      <div class="option-card" data-option-id="<?php 
                    echo esc_attr( $opt_id );
                    ?>">
                        <div class="option-header">
                          <div class="option-header-left">
                            <span class="option-drag-handle" title="Drag to reorder">☰</span>
                            <input type="text" class="name-input"
                              name="steps[<?php 
                    echo esc_attr( $step_id );
                    ?>][options][<?php 
                    echo esc_attr( $opt_id );
                    ?>][name]"
                              value="<?php 
                    echo esc_attr( $option['name'] ?? 'Option' );
                    ?>"
                              placeholder="<?php 
                    esc_attr_e( 'Option Name', '3d-product-customizer' );
                    ?>" />
                          </div>
                          <button type="button" class="button button-small button-delete remove-option-btn">
                            <span class="dashicons dashicons-trash"></span>
                          </button>
                        </div>
                        <div class="option-body">
                          <div class="option-price">
                            <label class="drcpu-label"
                              for="option-price-<?php 
                    echo esc_attr( $opt_id );
                    ?>"><?php 
                    esc_html_e( 'Additional Price', '3d-product-customizer' );
                    ?>
                              (<?php 
                    echo esc_html( get_woocommerce_currency_symbol() );
                    ?>)</label>
                            <input type="number" step="0.01" min="0" class="option-price-input"
                              name="steps[<?php 
                    echo esc_attr( $step_id );
                    ?>][options][<?php 
                    echo esc_attr( $opt_id );
                    ?>][price]"
                              value="<?php 
                    echo esc_attr( $option['price'] ?? '0' );
                    ?>" placeholder="0.00"
                              id="option-price-<?php 
                    echo esc_attr( $opt_id );
                    ?>" />
                          </div>
                          <div class="icon-picker">
                            <label class="drcpu-label"
                              for="steps[<?php 
                    echo esc_attr( $step_id );
                    ?>][options][<?php 
                    echo esc_attr( $opt_id );
                    ?>][icon]"><?php 
                    esc_html_e( 'Icon Image', '3d-product-customizer' );
                    ?></strong>
                              <small>(<?php 
                    esc_html_e( 'shown on mobile devices', '3d-product-customizer' );
                    ?>)</small></label>
                            <div style="display:flex;align-items:center;gap:10px;margin-top:4px;">
                              <?php 
                    if ( !empty( $option['icon'] ) ) {
                        ?>
                                <img class="icon-preview option" src="<?php 
                        echo esc_url( $option['icon'] );
                        ?>" alt="Icon Preview">
                              <?php 
                    } else {
                        ?>
                                <img class="icon-preview option" src="" alt="Icon Preview">
                              <?php 
                    }
                    ?>
                              <button type="button"
                                class="button button-small choose-option-icon-btn"><?php 
                    esc_html_e( 'Choose Image', '3d-product-customizer' );
                    ?></button>
                              <button type="button" class="button button-small button-link-delete clear-option-icon-btn" <?php 
                    echo ( empty( $option['icon'] ) ? 'style="display:none"' : '' );
                    ?>><?php 
                    esc_html_e( 'Clear', '3d-product-customizer' );
                    ?></button>
                              <input type="hidden" class="option-icon-input"
                                name="steps[<?php 
                    echo esc_attr( $step_id );
                    ?>][options][<?php 
                    echo esc_attr( $opt_id );
                    ?>][icon]"
                                value="<?php 
                    echo esc_attr( $option['icon'] ?? '' );
                    ?>">
                            </div>
                          </div>
                          <div class="option-texture">
                            <label class="drcpu-label"
                              for="option-materials-<?php 
                    echo esc_attr( $opt_id );
                    ?>"><?php 
                    esc_html_e( 'Materials/Textures', '3d-product-customizer' );
                    ?>:
                              <small><?php 
                    esc_html_e( '(select multiple = multiple frontend options)', '3d-product-customizer' );
                    ?></small></label>
                            <div class="texture-preview-multi" data-texture-ids="<?php 
                    echo esc_attr( implode( ',', $tex_ids ) );
                    ?>"
                              id="option-materials-<?php 
                    echo esc_attr( $opt_id );
                    ?>">
                              <?php 
                    if ( !empty( $tex_ids ) ) {
                        ?>
                                <?php 
                        foreach ( $tex_ids as $tid ) {
                            $tname = get_the_title( $tid );
                            $timg = get_the_post_thumbnail_url( $tid, 'thumbnail' );
                            ?>
                                  <div class="texture-thumb" data-id="<?php 
                            echo esc_attr( $tid );
                            ?>">
                                    <img src="<?php 
                            echo esc_url( $timg );
                            ?>" title="<?php 
                            echo esc_attr( $tname );
                            ?>">
                                    <span class="remove-tex">&times;</span>
                                  </div>
                                <?php 
                        }
                        ?>
                              <?php 
                    } else {
                        ?>
                                <span
                                  class="no-texture"><?php 
                        esc_html_e( 'None (geometry only)', '3d-product-customizer' );
                        ?></span>
                              <?php 
                    }
                    ?>
                            </div>
                            <button type="button" class="button button-small choose-texture-btn">+
                              <?php 
                    esc_html_e( 'Add Materials', '3d-product-customizer' );
                    ?></button>
                            <button type="button"
                              class="button button-small clear-texture-btn"><?php 
                    esc_html_e( 'Clear All', '3d-product-customizer' );
                    ?></button>
                            <input type="hidden" class="texture-ids-input"
                              name="steps[<?php 
                    echo esc_attr( $step_id );
                    ?>][options][<?php 
                    echo esc_attr( $opt_id );
                    ?>][texture_ids]"
                              value="<?php 
                    echo esc_attr( implode( ',', $tex_ids ) );
                    ?>">



                          </div>
                          <?php 
                    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
                        dprcu_render_geometry_controls__premium_only( $option, $step_id, $opt_id );
                    } else {
                        dprcu_render_geometry_controls_locked();
                    }
                    ?>
                        </div>
                      </div>
                      <?php 
                }
            }
            ?>
                </div>
                <div class="options-actions">
                  <button type="button" class="button button-small add-option-btn">+
                    <?php 
            esc_html_e( 'Add Option', '3d-product-customizer' );
            ?></button>
                  <?php 
            if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
                dprcu_render_bulk_add_button__premium_only();
            } else {
                dprcu_render_bulk_add_button_disabled();
            }
            ?>
                </div>
              </div>
            </div>
          </div>
          <?php 
        }
    }
    ?>
    </div>

    <p style="text-align: right;"><button type="button" class="button button-primary" id="add-step-btn">
        <span class="dashicons dashicons-plus"></span>
        <?php 
    esc_html_e( 'Add Step', '3d-product-customizer' );
    ?></button></p>

  </div><!-- /#psc-steps-area -->

  <?php 
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        dprcu_render_bulk_modal__premium_only();
        ?>
    <script type="text/html" id="tmpl-option">
          <div class="option-card" data-option-id="__OPT_ID__">
            <div class="option-header">
              <div class="option-header-left">
                <span class="option-drag-handle" title="Drag to reorder">☰</span>
                <input type="text" class="name-input" name="steps[__STEP_ID__][options][__OPT_ID__][name]" value="New Option" placeholder="Option Name" />
              </div>
              <button type="button" class="button button-small button-delete remove-option-btn">
                <span class="dashicons dashicons-trash"></span>
              </button>
            </div>
            <div class="option-body">
              <div class="option-price">
                <label class="drcpu-label" for="option-price-__OPT_ID__"><?php 
        esc_html_e( 'Additional Price', '3d-product-customizer' );
        ?> (<?php 
        echo esc_html( get_woocommerce_currency_symbol() );
        ?>)</label>
                <input type="number" step="0.01" min="0" class="option-price-input" name="steps[__STEP_ID__][options][__OPT_ID__][price]" value="0" placeholder="0.00" id="option-price-__OPT_ID__" />
              </div>
              <div class="icon-picker">
                <label class="drcpu-label"><?php 
        esc_html_e( 'Icon Image', '3d-product-customizer' );
        ?> <small><?php 
        esc_html_e( '(shown in geometry swatch)', '3d-product-customizer' );
        ?></small></label>
                <div style="display:flex;align-items:center;gap:10px;margin-top:4px;">
                  <img class="icon-preview option" src="" alt="Icon Preview">
                  <button type="button" class="button button-small choose-option-icon-btn"><?php 
        esc_html_e( 'Choose Image', '3d-product-customizer' );
        ?></button>
                  <button type="button" class="button button-small button-link-delete clear-option-icon-btn" style="display:none"><?php 
        esc_html_e( 'Clear', '3d-product-customizer' );
        ?></button>
                  <input type="hidden" class="option-icon-input" name="steps[__STEP_ID__][options][__OPT_ID__][icon]" value="">
                </div>
              </div>
              <div class="option-texture">
                <label class="drcpu-label" for="option-materials-__OPT_ID__"><?php 
        esc_html_e( 'Materials/Textures', '3d-product-customizer' );
        ?>: <small><?php 
        esc_html_e( 'select multiple = multiple frontend options', '3d-product-customizer' );
        ?></small></label>
                <div class="texture-preview-multi" data-texture-ids="" id="option-materials-__OPT_ID__">
                  <span class="no-texture"><?php 
        esc_html_e( 'None (geometry only)', '3d-product-customizer' );
        ?></span>
                </div>
                <button type="button" class="button button-small choose-texture-btn">+ <?php 
        esc_html_e( 'Add Materials', '3d-product-customizer' );
        ?></button>
                <button type="button" class="button button-small clear-texture-btn"><?php 
        esc_html_e( 'Clear All', '3d-product-customizer' );
        ?></button>
                <input type="hidden" class="texture-ids-input" name="steps[__STEP_ID__][options][__OPT_ID__][texture_ids]" value="">
              </div>
              <?php 
        dprcu_render_geometry_controls__premium_only( array(), '__STEP_ID__', '__OPT_ID__' );
        ?>
            </div>
          </div>
        </script>
    <?php 
    }
    ?>

  <div id="tex-modal">
    <div class="modal-content modal-wide">
      <div class="modal-head"><?php 
    esc_html_e( 'Select Materials/Textures', '3d-product-customizer' );
    ?>
        <small><?php 
    esc_html_e( 'Select 1 texture (Free plan)', '3d-product-customizer' );
    ?></small>
      </div>
      <div class="modal-body">
        <?php 
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        esc_html_e( 'Select one or more textures to assign to this option.', '3d-product-customizer' );
    } else {
        ?>
          <div class="premium-only-notice">
            <span class="dashicons dashicons-lock"></span>
            <?php 
        esc_html_e( 'Free plan: 1 texture per option.', '3d-product-customizer' );
        ?>
            <a href="<?php 
        echo esc_url( dprcu_checkout_url() );
        ?>" target="_blank"
              rel="noopener noreferrer"><?php 
        esc_html_e( 'Unlock multiple &rarr;', '3d-product-customizer' );
        ?></a>
          </div>
        <?php 
    }
    ?>
        <div class="bulk-actions">
          <button type="button" class="button button-small"
            id="tex-modal-select-none"><?php 
    esc_html_e( 'Select None', '3d-product-customizer' );
    ?></button>
          <?php 
    $tex_cats = get_terms( array(
        'taxonomy'   => 'dprcu_texture_category',
        'hide_empty' => false,
    ) );
    if ( $tex_cats && !is_wp_error( $tex_cats ) ) {
        ?>
            <select id="tex-modal-cat-filter" class="button button-small">
              <option value=""><?php 
        esc_html_e( 'All Categories', '3d-product-customizer' );
        ?></option>
              <?php 
        foreach ( $tex_cats as $cat ) {
            ?>
                <option value="<?php 
            echo esc_attr( $cat->term_id );
            ?>"><?php 
            echo esc_html( $cat->name );
            ?>
                </option>
              <?php 
        }
        ?>
            </select>
          <?php 
    }
    ?>
          <span class="bulk-count" id="tex-modal-count"><?php 
    esc_html_e( '0 selected', '3d-product-customizer' );
    ?></span>
        </div>
        <div class="modal-grid" id="tex-modal-grid"></div>
      </div>
      <div class="modal-foot">
        <button type="button" class="button"
          id="tex-modal-cancel"><?php 
    esc_html_e( 'Cancel', '3d-product-customizer' );
    ?></button>
        <button type="button" class="button button-primary"
          id="tex-modal-select"><?php 
    esc_html_e( 'Add Selected', '3d-product-customizer' );
    ?></button>
      </div>
    </div>
  </div>
  <?php 
}

/**
 * AJAX handler to render a new step's HTML.
 *
 * Returns sanitized HTML for a new empty step wrapping.
 */
function dprcu_ajax_render_step() {
    check_ajax_referer( 'dprcu_metabox_nonce', 'nonce' );
    $step_id = ( isset( $_POST['step_id'] ) ? sanitize_text_field( wp_unslash( $_POST['step_id'] ) ) : '' );
    if ( !$step_id ) {
        wp_send_json_error( 'Missing step_id' );
    }
    ob_start();
    ?>
  <div class="config-step" data-step-id="<?php 
    echo esc_attr( $step_id );
    ?>">
    <div class="step-header">
      <span class="step-drag-handle" title="Drag to reorder">☰</span>
      <input type="text" class="name-input" name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][name]" value="New Step"
        placeholder="Step Name (e.g. Upper, Sole, Logo)" />

      <div class="filler">

      </div>

      <button type="button"
        class="button button-delete remove-step-btn"><?php 
    esc_html_e( 'Remove Step', '3d-product-customizer' );
    ?>
        <span class="dashicons dashicons-trash"></span>
      </button>
      <span class="step-toggle-btn dashicons dashicons-arrow-down-alt2" title="Toggle Step"></span>

    </div>
    <div class="step-body">
      <div class="step-description">
        <label><strong><?php 
    esc_html_e( 'Step Description', '3d-product-customizer' );
    ?></strong></label>
        <textarea class="step-description-input" name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][description]"
          placeholder="(Optional) Step Description" style="margin-top:4px;font-size:12px;color:#666;"></textarea>
      </div>
      <div class="icon-picker">
        <label class="drcpu-label"
          for="steps[<?php 
    echo esc_attr( $step_id );
    ?>][icon]"><?php 
    esc_html_e( 'Icon Image', '3d-product-customizer' );
    ?></strong>
          <small><?php 
    esc_html_e( '(shown for geometry-only options)', '3d-product-customizer' );
    ?></small></label>
        <div>
          <img class="icon-preview step" src="" alt="Icon Preview">
          <button type="button"
            class="button button-small choose-step-icon-btn"><?php 
    esc_html_e( 'Choose Image', '3d-product-customizer' );
    ?></button>
          <button type="button" class="button button-small button-delete clear-step-icon-btn" style="display:none">
            <span class="dashicons dashicons-trash"></span>
          </button>
          <input type="hidden" class="step-icon-input" name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][icon]" value="">
        </div>
      </div>
      <div class="step-targets">
        <label><strong><?php 
    esc_html_e( 'Target Meshes', '3d-product-customizer' );
    ?></strong> <small>(which parts
            of the model this step customizes)</small></label>
        <select multiple
          class="dprcu-s2 dprcu-mesh-select"
          name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][targets][]"
          data-selected=""
          data-placeholder="<?php 
    esc_attr_e( 'Select meshes…', '3d-product-customizer' );
    ?>">
        </select>
      </div>
      <div class="step-options-container">
        <h3><?php 
    esc_html_e( 'Options', '3d-product-customizer' );
    ?></h3>
        <div class="options-list"></div>
        <div class="options-actions">
          <button type="button" class="button button-small add-option-btn">+
            <?php 
    esc_html_e( 'Add Option', '3d-product-customizer' );
    ?></button>
          <?php 
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        dprcu_render_bulk_add_button__premium_only();
    } else {
        dprcu_render_bulk_add_button_disabled();
    }
    ?>
        </div>
      </div>
    </div>
  </div>
  <?php 
    $html = ob_get_clean();
    wp_send_json_success( array(
        'html' => $html,
    ) );
}

add_action( 'wp_ajax_dprcu_render_step', 'dprcu_ajax_render_step' );
/**
 * AJAX handler to render a new option's HTML.
 *
 * Returns sanitized HTML for a new empty option card.
 */
function dprcu_ajax_render_option() {
    check_ajax_referer( 'dprcu_metabox_nonce', 'nonce' );
    $step_id = ( isset( $_POST['step_id'] ) ? sanitize_text_field( wp_unslash( $_POST['step_id'] ) ) : '' );
    $opt_id = ( isset( $_POST['opt_id'] ) ? sanitize_text_field( wp_unslash( $_POST['opt_id'] ) ) : '' );
    if ( !$step_id || !$opt_id ) {
        wp_send_json_error( 'Missing step_id or opt_id' );
    }
    ob_start();
    ?>
  <div class="option-card" data-option-id="<?php 
    echo esc_attr( $opt_id );
    ?>">
    <div class="option-header">
      <div class="option-header-left">
        <span class="option-drag-handle" title="Drag to reorder">☰</span>
        <input type="text" class="name-input"
          name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][options][<?php 
    echo esc_attr( $opt_id );
    ?>][name]"
          value="New Option" placeholder="Option Name" />
      </div>
      <button type="button" class="button button-small button-delete remove-option-btn">
        <span class="dashicons dashicons-trash"></span>
      </button>
    </div>
    <div class="option-body">
      <div class="option-price">
        <label class="drcpu-label"
          for="option-price-<?php 
    echo esc_attr( $opt_id );
    ?>"><?php 
    esc_html_e( 'Additional Price', '3d-product-customizer' );
    ?>
          (<?php 
    echo esc_html( get_woocommerce_currency_symbol() );
    ?>)</label>
        <input type="number" step="0.01" min="0" class="option-price-input"
          name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][options][<?php 
    echo esc_attr( $opt_id );
    ?>][price]" value="0"
          placeholder="0.00" id="option-price-<?php 
    echo esc_attr( $opt_id );
    ?>" />
      </div>
      <div class="icon-picker">
        <label class="drcpu-label"><?php 
    esc_html_e( 'Icon Image', '3d-product-customizer' );
    ?>
          <small><?php 
    esc_html_e( '(shown in geometry swatch)', '3d-product-customizer' );
    ?></small></label>
        <div style="display:flex;align-items:center;gap:10px;margin-top:4px;">
          <span class="icon-preview option">
          </span>
          <button type="button"
            class="button button-small choose-option-icon-btn"><?php 
    esc_html_e( 'Choose Image', '3d-product-customizer' );
    ?></button>
          <button type="button" class="button button-small button-delete clear-option-icon-btn" style="display:none">
            <span class="dashicons dashicons-trash"></span>
          </button>
          <input type="hidden" class="option-icon-input"
            name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][options][<?php 
    echo esc_attr( $opt_id );
    ?>][icon]" value="">
        </div>
      </div>
      <div class="option-texture">
        <label class="drcpu-label"
          for="option-materials-<?php 
    echo esc_attr( $opt_id );
    ?>"><?php 
    esc_html_e( 'Materials/Textures', '3d-product-customizer' );
    ?>:
          <small>
            <?php 
    esc_html_e( 'select multiple = multiple frontend options', '3d-product-customizer' );
    ?></small></label>
        <div class="texture-preview-multi" data-texture-ids="" id="option-materials-<?php 
    echo esc_attr( $opt_id );
    ?>">
          <span class="no-texture"><?php 
    esc_html_e( 'None (geometry only)', '3d-product-customizer' );
    ?></span>
        </div>
        <button type="button" class="button button-small choose-texture-btn">+
          <?php 
    esc_html_e( 'Add Materials', '3d-product-customizer' );
    ?></button>
        <button type="button"
          class="button button-small clear-texture-btn"><?php 
    esc_html_e( 'Clear All', '3d-product-customizer' );
    ?></button>
        <input type="hidden" class="texture-ids-input"
          name="steps[<?php 
    echo esc_attr( $step_id );
    ?>][options][<?php 
    echo esc_attr( $opt_id );
    ?>][texture_ids]"
          value="">

      </div>
      <?php 
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        dprcu_render_geometry_controls__premium_only( array(), $step_id, $opt_id );
    } else {
        dprcu_render_geometry_controls_locked();
    }
    ?>
    </div>
  </div>
  <?php 
    $html = ob_get_clean();
    wp_send_json_success( array(
        'html' => $html,
    ) );
}

add_action( 'wp_ajax_dprcu_render_option', 'dprcu_ajax_render_option' );
/**
 * Enqueue scripts and styles for the product metabox.
 */
function dprcu_enqueue_metabox_assets() {
    $screen = get_current_screen();
    if ( !$screen || 'product' !== $screen->id ) {
        return;
    }
    wp_enqueue_media();
    // Enqueue CSS
    wp_enqueue_style(
        'dprcu-metabox-styles',
        plugins_url( 'css/metabox-styles.css', __FILE__ ),
        array(),
        ( filemtime( plugin_dir_path( __FILE__ ) . 'css/metabox-styles.css' ) ?: '1.0' )
    );
    // Enqueue jQuery UI Sortable
    wp_enqueue_script( 'jquery-ui-sortable' );
    // Enqueue admin model scanner (for the 3D preview)
    wp_enqueue_script(
        'dprcu-admin-model-scanner',
        plugin_dir_url( dirname( __FILE__ ) ) . 'dist/adminScanner.bundle.js',
        array('jquery'),
        '1.0',
        true
    );
    // Pass scene settings (HDR env map, background color) so the admin preview
    // can mirror the front-end customizer.js scene setup.
    $global_settings = get_option( 'dprcu_settings', array() );
    $bg_colors_str = $global_settings['bg_colors'] ?? "#f0f0f0\n#ffffff\n#222222";
    $bg_colors = array_values( array_filter( preg_split( '/\\r\\n|[\\r\\n]/', $bg_colors_str ) ) );
    wp_localize_script( 'dprcu-admin-model-scanner', 'dprcu_model_scanner', array(
        'hdrFile' => esc_url( $global_settings['hdr_file'] ?? '' ),
        'bgColor' => $bg_colors[0] ?? '#f0f0f0',
    ) );
    // Enqueue JS — full free or full premium version of the metabox scripts.
    // The if-block is stripped from the free build by Freemius; only the else remains.
    if ( dprcu_fs()?->can_use_premium_code__premium_only() ) {
        wp_enqueue_script(
            'dprcu-metabox-scripts',
            plugins_url( 'js/metabox-scripts__premium_only.js', __FILE__ ),
            array('jquery', 'jquery-ui-sortable'),
            ( filemtime( plugin_dir_path( __FILE__ ) . 'js/metabox-scripts__premium_only.js' ) ?: '1.0' ),
            true
        );
    } else {
        wp_enqueue_script(
            'dprcu-metabox-scripts',
            plugins_url( 'js/metabox-scripts.js', __FILE__ ),
            array('jquery', 'jquery-ui-sortable'),
            ( filemtime( plugin_dir_path( __FILE__ ) . 'js/metabox-scripts.js' ) ?: '1.0' ),
            true
        );
    }
    // Pass textures data and nonce to JS
    $textures = dprcu_get_all_textures();
    wp_localize_script( 'dprcu-metabox-scripts', 'dprcu_availableTextures', $textures );
    wp_localize_script( 'dprcu-metabox-scripts', 'dprcu_ajax', array(
        'nonce'   => wp_create_nonce( 'dprcu_metabox_nonce' ),
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
    ) );
}

add_action( 'admin_enqueue_scripts', 'dprcu_enqueue_metabox_assets' );
/**
 * Normalises a multi-select field that may arrive as a PHP array (from
 * <select multiple name="...[]">) or as a legacy comma-separated string.
 *
 * @param mixed $data Raw POST value.
 * @return array<int,string>
 */
function dprcu_parse_multiselect(  $data  ) : array {
    if ( is_array( $data ) ) {
        return array_values( array_filter( array_map( 'sanitize_text_field', $data ) ) );
    }
    return array_values( array_filter( array_map( 'sanitize_text_field', explode( ',', (string) $data ) ) ) );
}

// SAVE
function dprcu_save_metabox(  $post_id  ) {
    if ( !isset( $_POST['dprcu_metabox_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['dprcu_metabox_nonce'] ) ), 'dprcu_save_metabox' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( !current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    if ( isset( $_POST['_dprcu_3d_model_url'] ) ) {
        update_post_meta( $post_id, '_dprcu_3d_model_url', esc_url_raw( wp_unslash( $_POST['_dprcu_3d_model_url'] ) ) );
    }
    // Save viewer-only toggle. Unchecked checkboxes are absent from $_POST,
    // so the absence of the key means it was unchecked — delete the meta.
    if ( isset( $_POST['_dprcu_3d_viewer_only'] ) && '1' === $_POST['_dprcu_3d_viewer_only'] ) {
        update_post_meta( $post_id, '_dprcu_3d_viewer_only', '1' );
    } else {
        delete_post_meta( $post_id, '_dprcu_3d_viewer_only' );
    }
    // Save camera position. Stored as JSON {position:{x,y,z},target:{x,y,z}}.
    // An empty value means auto-frame (no saved position).
    if ( isset( $_POST['_dprcu_camera_position'] ) && '' !== $_POST['_dprcu_camera_position'] ) {
        $camera_raw = sanitize_text_field( wp_unslash( $_POST['_dprcu_camera_position'] ) );
        $camera_decoded = json_decode( $camera_raw, true );
        if ( $camera_decoded && isset( $camera_decoded['position'], $camera_decoded['target'] ) ) {
            update_post_meta( $post_id, '_dprcu_camera_position', wp_json_encode( array(
                'position' => $camera_decoded['position'],
                'target'   => $camera_decoded['target'],
            ) ) );
        } else {
            delete_post_meta( $post_id, '_dprcu_camera_position' );
        }
    } else {
        delete_post_meta( $post_id, '_dprcu_camera_position' );
    }
    $raw_steps = ( isset( $_POST['steps'] ) && is_array( $_POST['steps'] ) ? map_deep( wp_unslash( $_POST['steps'] ), 'sanitize_text_field' ) : null );
    if ( null === $raw_steps ) {
        delete_post_meta( $post_id, '_dprcu_customizer_config' );
        return;
    }
    $final = array();
    foreach ( $raw_steps as $raw_step_id => $step_data ) {
        // sanitize_key() strips anything that isn't [a-z0-9_-], preventing
        // unexpected characters from polluting the stored JSON structure.
        $step_id = sanitize_key( $raw_step_id );
        $step = array(
            'name'        => sanitize_text_field( $step_data['name'] ?? 'Step' ),
            'description' => sanitize_text_field( $step_data['description'] ?? '' ),
            'icon'        => sanitize_text_field( $step_data['icon'] ?? '' ),
            'targets'     => dprcu_parse_multiselect( $step_data['targets'] ?? [] ),
            'options'     => array(),
        );
        if ( !empty( $step_data['options'] ) ) {
            foreach ( $step_data['options'] as $raw_opt_id => $opt_data ) {
                $opt_id = sanitize_key( $raw_opt_id );
                $opt_name = sanitize_text_field( $opt_data['name'] ?? 'Option' );
                $show_meshes = [];
                $hide_meshes = [];
                $show_steps = [];
                $hide_steps = [];
                /* <fs_premium_only> */
                $show_meshes = dprcu_parse_multiselect( $opt_data['show'] ?? [] );
                $hide_meshes = dprcu_parse_multiselect( $opt_data['hide'] ?? [] );
                $show_steps = dprcu_parse_multiselect( $opt_data['show_steps'] ?? [] );
                $hide_steps = dprcu_parse_multiselect( $opt_data['hide_steps'] ?? [] );
                /* </fs_premium_only> */
                // Get texture IDs (supports both old single and new multi format)
                $texture_ids_raw = $opt_data['texture_ids'] ?? $opt_data['texture_id'] ?? '';
                $texture_ids = array_filter( array_map( 'intval', explode( ',', $texture_ids_raw ) ) );
                $opt_price = floatval( $opt_data['price'] ?? 0 );
                $opt_icon = sanitize_text_field( $opt_data['icon'] ?? '' );
                if ( empty( $texture_ids ) ) {
                    // Geometry-only option
                    $step['options'][$opt_id] = array(
                        'name'        => $opt_name,
                        'texture_ids' => '',
                        'show'        => $show_meshes,
                        'hide'        => $hide_meshes,
                        'show_steps'  => $show_steps,
                        'hide_steps'  => $hide_steps,
                        'price'       => $opt_price,
                        'icon'        => $opt_icon,
                    );
                } else {
                    // Store all texture IDs together for admin display
                    $step['options'][$opt_id] = array(
                        'name'        => $opt_name,
                        'texture_ids' => implode( ',', $texture_ids ),
                        'show'        => $show_meshes,
                        'hide'        => $hide_meshes,
                        'show_steps'  => $show_steps,
                        'hide_steps'  => $hide_steps,
                        'price'       => $opt_price,
                        'icon'        => $opt_icon,
                    );
                }
            }
        }
        // Only save steps that have options
        if ( !empty( $step['options'] ) ) {
            $final[$step_id] = $step;
        }
    }
    update_post_meta( $post_id, '_dprcu_customizer_config', wp_json_encode( $final, JSON_UNESCAPED_UNICODE ) );
}

add_action( 'save_post', 'dprcu_save_metabox' );