<?php

namespace MODELORA\Integrations;

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

class WooCommerce
{
    public function register(): void
    {
        add_action('add_meta_boxes', [$this, 'meta_box']);
        add_action('save_post_product', [$this, 'save_meta'], 10, 2);
        add_action('woocommerce_before_single_product_summary', [$this, 'inject_viewer'], 19);
        add_action('woocommerce_product_after_variable_attributes', [$this, 'variation_field'], 10, 3);
        add_action('woocommerce_save_product_variation', [$this, 'save_variation_field'], 10, 2);
    }

    public function meta_box(): void
    {
        add_meta_box('modelora_product_model', __('Modelora Model', 'modelora-3d-product-viewer'), [$this, 'render_meta_box'], 'product', 'side');
    }

    public function render_meta_box(\WP_Post $post): void
    {
        wp_nonce_field('modelora_product_model_nonce', 'modelora_product_model_nonce_field');

        $selected = (int) get_post_meta($post->ID, '_modelora_model_id', true);
        $models = get_posts([
            'post_type' => 'modelora_model',
            'post_status' => 'publish',
            'posts_per_page' => 200,
        ]);

        echo '<p>' . esc_html__('One-click Add to Product:', 'modelora-3d-product-viewer') . '</p>';
        echo '<select name="modelora_model_id" style="width:100%;">';
        echo '<option value="0">' . esc_html__('None', 'modelora-3d-product-viewer') . '</option>';

        foreach ($models as $model) {
            printf(
                '<option value="%1$d" %3$s>%2$s</option>',
                (int) $model->ID,
                esc_html($model->post_title),
                selected($selected, (int) $model->ID, false)
            );
        }

        echo '</select>';
    }

    public function save_meta(int $post_id, \WP_Post $post): void
    {
        if (! isset($_POST['modelora_product_model_nonce_field']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['modelora_product_model_nonce_field'])), 'modelora_product_model_nonce')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (! current_user_can('edit_post', $post_id)) {
            return;
        }

        $model_id = isset($_POST['modelora_model_id']) ? (int) $_POST['modelora_model_id'] : 0;
        update_post_meta($post_id, '_modelora_model_id', $model_id);
    }

    public function inject_viewer(): void
    {
        if (! is_product()) {
            return;
        }

        global $product;
        if (! $product instanceof \WC_Product) {
            return;
        }

        $product_id = $product->get_id();
        $model_id = (int) get_post_meta($product_id, '_modelora_model_id', true);

        if (! $model_id) {
            return;
        }

        echo do_shortcode('[modelora_viewer id="' . $model_id . '" product_id="' . $product_id . '" ar="1"]');
    }

    public function variation_field($loop, $variation_data, $variation): void
    {
        $value = (int) get_post_meta($variation->ID, '_modelora_model_id', true);
        ?>
        <p class="form-row form-row-full">
            <label><?php esc_html_e('Modelora Model ID', 'modelora-3d-product-viewer'); ?></label>
            <input type="number" name="modelora_variation_model_id[<?php echo esc_attr((string) $variation->ID); ?>]" value="<?php echo esc_attr((string) $value); ?>" min="0" step="1" />
        </p>
        <?php
    }

    public function save_variation_field($variation_id, $i): void
    {
        if (! isset($_POST['security']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'save-variations')) {
            return;
        }

        $all = filter_input(INPUT_POST, 'modelora_variation_model_id', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        if (! is_array($all)) {
            $all = [];
        }

        $value = isset($all[$variation_id]) ? absint($all[$variation_id]) : 0;
        update_post_meta((int) $variation_id, '_modelora_model_id', $value);
    }
}

