<?php
if (!defined('ABSPATH')) exit;
function drop_print_save_product_meta($post_id) {
    if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || !current_user_can('edit_product', $post_id)) return;
    $product = wc_get_product($post_id);
    if (!$product || !$product->is_type('variable')) return;
    $meta_data = $product->get_meta('_drop_print_meta', true);
    if (!is_array($meta_data)) $meta_data = [];
    $original_meta_data_for_comparison = $meta_data;
    $product_needs_save = false;
    $attributes_updated = false;
    $clear_transients = false;
    $taxonomy = 'pa_print_dimensions';
    $is_reset_scenario = isset($meta_data['doing_reset']) && true === $meta_data['doing_reset'];
    if (function_exists('drop_print_use_legacy_product_panel') && drop_print_use_legacy_product_panel()) {
        $new_active_status = isset($_POST['_drop_print_enable']) ? 'yes' : 'no';
    } elseif ($is_reset_scenario) {
        $new_active_status = 'no';
    } else {
        $has_drop_print_data = !empty($meta_data['file'])
            || (!empty($meta_data['variations']) && is_array($meta_data['variations']));
        $new_active_status = ('yes' === ($meta_data['active'] ?? 'no') || $has_drop_print_data) ? 'yes' : 'no';
    }
    if (!isset($meta_data['active']) || $meta_data['active'] !== $new_active_status) {
        $meta_data['active'] = $new_active_status;
    }
    if ($is_reset_scenario) {
        $existing_variation_ids = $product->get_children();
        if (!empty($existing_variation_ids)) {
            foreach ($existing_variation_ids as $variation_id) {
                $variation_product_obj = wc_get_product($variation_id);
                if ($variation_product_obj && $variation_product_obj->is_type('variation')) {
                    $variation_attributes = $variation_product_obj->get_attributes();
                    if (isset($variation_attributes[$taxonomy])) {
                        wp_delete_post($variation_id, true);
                    }
                }
                unset($variation_product_obj);
            }
        }
        $product = wc_get_product($post_id);
        if (!$product) {
            $current_meta = get_post_meta($post_id, '_drop_print_meta', true);
            if(is_array($current_meta) && isset($current_meta['doing_reset'])){
                unset($current_meta['doing_reset']);
                update_post_meta($post_id, '_drop_print_meta', $current_meta);
            }
            return;
        }
        $attributes = $product->get_attributes();
        if (isset($attributes[$taxonomy])) {
            unset($attributes[$taxonomy]);
            $product->set_attributes($attributes);
            $attributes_updated = true;
            $product_needs_save = true;
        }
        wp_set_object_terms($post_id, null, $taxonomy, false);
        $meta_data = ['active' => $new_active_status];
        $clear_transients = true;
    } elseif (('yes' === ($meta_data['active'] ?? 'no')) && isset($meta_data['variations']) && is_array($meta_data['variations']) && !empty($meta_data['variations']) && empty($meta_data['variations_processed'])) {
        if (!taxonomy_exists($taxonomy)) {
            $meta_data['variations_processed'] = true;
        } else {
            $existing_variation_ids = $product->get_children();
            if (!empty($existing_variation_ids)) {
                foreach ($existing_variation_ids as $variation_id) {
                    $variation_product_obj = wc_get_product($variation_id);
                    if ($variation_product_obj && $variation_product_obj->is_type('variation')) {
                        $variation_attributes = $variation_product_obj->get_attributes();
                        if (isset($variation_attributes[$taxonomy])) {
                           wp_delete_post($variation_id, true);
                        }
                    }
                    unset($variation_product_obj);
                }
            }
            $product = wc_get_product($post_id);
            if (!$product) {
                $meta_data['variations_processed'] = true;
            } else {
                $staged_variations = $meta_data['variations'];
                $created_count = 0;
                $attribute_term_ids = [];
                $updated_meta_variations = [];
                foreach ($staged_variations as $key => $variation_data) {
                    $sku = $variation_data['sku'] ?? null;
                    $price = $variation_data['price'] ?? null;
                    $title = $variation_data['title'] ?? null;
                    $sizing = $variation_data['sizing'] ?? 'fillPrintArea';
                    if (empty($sku) || null === $price || !is_numeric($price) || $price < 0 || empty($title)) {
                        $updated_meta_variations[] = $variation_data;
                        continue;
                    }
                    $term_slug = sanitize_title($sku);
                    $term_name = $title;
                    $term_id = null;
                    $term = get_term_by('slug', $term_slug, $taxonomy);
                    if (!$term) {
                        $term_result = wp_insert_term($term_name, $taxonomy, ['slug' => $term_slug]);
                        if (is_wp_error($term_result)) {
                            $updated_meta_variations[] = $variation_data;
                            continue;
                        }
                        $term_id = $term_result['term_id'];
                    } else {
                        $term_id = $term->term_id;
                        $term_slug = $term->slug;
                        if ($term->name !== $term_name) {
                            wp_update_term($term_id, $taxonomy, ['name' => $term_name]);
                        }
                    }
                    if (!$term_id) {
                        $updated_meta_variations[] = $variation_data;
                        continue;
                    }
                    $attribute_term_ids[$term_id] = $term_id;
                    $variation = new WC_Product_Variation();
                    $variation->set_parent_id($post_id);
                    $variation->set_status('publish');
                    $variation->set_menu_order($created_count);
                    $variation->set_attributes([$taxonomy => $term_slug]);
                    $variation->set_regular_price($price);
                    $variation->set_price($price);
                    $variation->set_manage_stock(false);
                    $variation->set_virtual(false);
                    $variation->set_downloadable(false);
                    $variation->set_description($title);
                    $variation_id_saved = $variation->save();
                    if (is_wp_error($variation_id_saved) || !$variation_id_saved) {
                        $updated_meta_variations[] = $variation_data;
                        continue;
                    }
                    $current_variation_data_for_meta = $variation_data;
                    $current_variation_data_for_meta['wc_variation_id'] = $variation_id_saved;
                    $updated_meta_variations[] = $current_variation_data_for_meta;
                    wp_update_post(['ID' => $variation_id_saved, 'post_title' => $title]);
                    update_post_meta($variation_id_saved, '_drop_print_sku', $sku);
                    update_post_meta($variation_id_saved, '_drop_print_sizing', $sizing);
                    $created_count++;
                }
                $meta_data['variations'] = $updated_meta_variations;
                $attributes = $product->get_attributes();
                if ($created_count > 0 && !empty($attribute_term_ids)) {
                    $term_ids_to_set = array_values($attribute_term_ids);
                    wp_set_object_terms($post_id, $term_ids_to_set, $taxonomy, false);
                    $attribute_object = $attributes[$taxonomy] ?? new WC_Product_Attribute();
                    if (!$attribute_object->get_id() && function_exists('wc_attribute_taxonomy_id_by_name')) {
                        $taxonomy_id = wc_attribute_taxonomy_id_by_name($taxonomy);
                        if ($taxonomy_id) $attribute_object->set_id($taxonomy_id);
                    }
                    $attribute_object->set_name($taxonomy);
                    $attribute_object->set_options($term_ids_to_set);
                    $attribute_object->set_visible(true);
                    $attribute_object->set_variation(true);
                    $attributes[$taxonomy] = $attribute_object;
                    $attributes_updated = true;
                    $meta_data['variations_currency'] = get_woocommerce_currency();
                } else {
                    wp_set_object_terms($post_id, null, $taxonomy, false);
                    if (isset($attributes[$taxonomy])) {
                        unset($attributes[$taxonomy]);
                        $attributes_updated = true;
                    }
                    if (isset($meta_data['variations_currency'])) {
                        unset($meta_data['variations_currency']);
                    }
                }
                if ($attributes_updated) {
                    $product->set_attributes($attributes);
                    $product_needs_save = true;
                }
                $meta_data['variations_processed'] = true;
                $clear_transients = true;
            }
        }
    }
    $final_meta_changed_flag = ($meta_data !== $original_meta_data_for_comparison);
    if ($product_needs_save) {
        $product->save();
    }
    if ($final_meta_changed_flag) {
        update_post_meta($post_id, '_drop_print_meta', $meta_data);
    }
    if ($final_meta_changed_flag || $product_needs_save || $is_reset_scenario) {
        $current_dp_meta_for_thumbnail = $final_meta_changed_flag ? $meta_data : get_post_meta($post_id, '_drop_print_meta', true);
        if (is_array($current_dp_meta_for_thumbnail) && !empty($current_dp_meta_for_thumbnail['preview_id']) && absint($current_dp_meta_for_thumbnail['preview_id']) > 0) {
            if (!has_post_thumbnail($post_id)) {
                set_post_thumbnail($post_id, absint($current_dp_meta_for_thumbnail['preview_id']));
            }
        }
    }
    if ($clear_transients && function_exists('wc_delete_product_transients')) {
        wc_delete_product_transients($post_id);
    }
}
add_action('woocommerce_process_product_meta_variable', 'drop_print_save_product_meta', 20);
function drop_print_stage_variations_handler() {
    check_ajax_referer('drop_print_nonce', 'nonce');
    $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
    $raw_prospective_variations = isset($_POST['prospective_variations']) ? wp_unslash($_POST['prospective_variations']) : [];
    $prospective_variations = is_array($raw_prospective_variations) ? $raw_prospective_variations : [];
    if (!current_user_can('edit_product', $product_id) || $product_id <= 0) {
        wp_send_json_error(['message' => __('Invalid request or insufficient permissions.', 'drop-print')], 403);
        return;
    }
    $meta = get_post_meta($product_id, '_drop_print_meta', true);
    if (!is_array($meta)) $meta = [];
    $variations_to_stage = [];
    if (!empty($prospective_variations)) {
        foreach ($prospective_variations as $variation_data) {
            $sku = isset($variation_data['sku']) ? sanitize_text_field($variation_data['sku']) : null;
            $price_raw = $variation_data['price'] ?? null;
            $title = isset($variation_data['title']) ? sanitize_text_field($variation_data['title']) : null;
            $sizing = isset($variation_data['sizing']) ? sanitize_text_field($variation_data['sizing']) : 'fillPrintArea';
            $price = (is_numeric($price_raw) && $price_raw >= 0) ? wc_format_decimal($price_raw) : false;
            if (!empty($sku) && false !== $price && !empty($title)) {
                $variations_to_stage[] = [
                    'sku' => $sku,
                    'price' => $price,
                    'title' => $title,
                    'sizing' => $sizing
                ];
            }
        }
    }
    $meta_updated_by_staging = false;
    if (!empty($variations_to_stage)) {
        if (!isset($meta['variations']) || $meta['variations'] !== $variations_to_stage) {
            $meta['variations'] = $variations_to_stage;
            $meta_updated_by_staging = true;
        }
        $meta['variations_processed'] = false;
        $meta_updated_by_staging = true;
        if (isset($meta['doing_reset'])) {
            unset($meta['doing_reset']);
            $meta_updated_by_staging = true;
        }
        if (!isset($meta['active']) || 'yes' !== $meta['active']) {
            $meta['active'] = 'yes';
            $meta_updated_by_staging = true;
        }
    } else {
        if (isset($meta['variations'])) {
            unset($meta['variations']);
            $meta_updated_by_staging = true;
        }
        if (isset($meta['variations_processed'])) {
            unset($meta['variations_processed']);
            $meta_updated_by_staging = true;
        }
    }
    if ($meta_updated_by_staging) {
        if (update_post_meta($product_id, '_drop_print_meta', $meta)) {
            wp_send_json_success(['message' => __('Variations staged successfully. Save the product to apply changes.', 'drop-print')]);
        } else {
            wp_send_json_error(['message' => __('Failed to stage variations (meta update failed).', 'drop-print')], 500);
        }
    } else {
        wp_send_json_success(['message' => __('No changes to stage for variations.', 'drop-print')]);
    }
}
add_action('wp_ajax_drop_print_stage_variations', 'drop_print_stage_variations_handler');
function drop_print_stage_reset_handler() {
    check_ajax_referer('drop_print_nonce', 'nonce');
    $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
    if (!current_user_can('edit_product', $product_id) || $product_id <= 0) {
        wp_send_json_error(['message' => __('Invalid request or insufficient permissions.', 'drop-print')], 403);
        return;
    }
    $meta = get_post_meta($product_id, '_drop_print_meta', true);
    if (!is_array($meta)) $meta = [];
    $meta_changed_by_reset_staging = false;
    if (!isset($meta['doing_reset']) || true !== $meta['doing_reset']) {
        $meta['doing_reset'] = true;
        $meta_changed_by_reset_staging = true;
    }
    if (isset($meta['variations'])) {
        unset($meta['variations']);
        $meta_changed_by_reset_staging = true;
    }
    if (isset($meta['variations_processed'])) {
        unset($meta['variations_processed']);
        $meta_changed_by_reset_staging = true;
    }
    if ($meta_changed_by_reset_staging) {
        if (update_post_meta($product_id, '_drop_print_meta', $meta)) {
            wp_send_json_success(['message' => __('Reset successfully staged.', 'drop-print')]);
        } else {
            wp_send_json_error(['message' => __('Failed to stage reset (meta update failed).', 'drop-print')], 500);
        }
    } else {
         wp_send_json_success(['message' => __('Reset flag already staged or no variations to clear from stage.', 'drop-print')]);
    }
}
add_action('wp_ajax_drop_print_stage_reset', 'drop_print_stage_reset_handler');
function drop_print_prepare_product_handler() {
    check_ajax_referer('drop_print_nonce', 'nonce');
    $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
    if ($product_id <= 0 || !current_user_can('edit_product', $product_id)) {
        wp_send_json_error(['message' => __('Invalid request or insufficient permissions.', 'drop-print')], 403);
        return;
    }
    $post = get_post($product_id);
    if (!$post || 'product' !== $post->post_type) {
        wp_send_json_error(['message' => __('Product not found.', 'drop-print')], 404);
        return;
    }
    $status_promoted = false;
    if ('auto-draft' === $post->post_status) {
        $update = ['ID' => $product_id, 'post_status' => 'draft'];
        $title = isset($_POST['post_title']) ? sanitize_text_field(wp_unslash($_POST['post_title'])) : '';
        if ('' !== $title) {
            $update['post_title'] = $title;
        }
        $result = wp_update_post($update, true);
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()], 500);
            return;
        }
        $status_promoted = true;
    }
    $type_changed = false;
    $product = wc_get_product($product_id);
    if (!$product || !$product->is_type('variable')) {
        wp_set_object_terms($product_id, 'variable', 'product_type', false);
        $type_changed = true;
    }
    wp_send_json_success([
        'status_promoted' => $status_promoted,
        'type_changed'    => $type_changed,
        'message'         => __('Product prepared for Drop Print.', 'drop-print'),
    ]);
}
add_action('wp_ajax_drop_print_prepare_product', 'drop_print_prepare_product_handler');
function drop_print_handle_product_duplication_pv($duplicate_product_obj, $original_product_obj) {
    if (!is_a($duplicate_product_obj, 'WC_Product') || !is_a($original_product_obj, 'WC_Product')) {
        return;
    }
    $new_product_id = $duplicate_product_obj->get_id();
    $meta = $duplicate_product_obj->get_meta('_drop_print_meta', true);
    if (is_array($meta) && !empty($meta['file'])) {
        $afp_base_filename = $meta['file'];
        if(function_exists('drop_print_files_add_product_ref')){
            drop_print_files_add_product_ref( $afp_base_filename, $new_product_id );
        }
    }
}
add_action('woocommerce_product_duplicate', 'drop_print_handle_product_duplication_pv', 20, 2);
function drop_print_handle_before_delete_post_pv($post_id, $post) {
    if ('product' !== $post->post_type || !current_user_can('delete_post', $post_id)) {
        return;
    }
    $product = wc_get_product($post_id);
    if (!$product) return;
    $meta = $product->get_meta('_drop_print_meta', true);
    if (is_array($meta) && !empty($meta['file'])) {
        $afp_base_filename = $meta['file'];
        $container_ext_pv  = defined('DROP_PRINT_CONTAINER_EXT') ? DROP_PRINT_CONTAINER_EXT : '.drop';
        $now_unreferenced = function_exists('drop_print_files_remove_product_ref')
            ? drop_print_files_remove_product_ref($afp_base_filename, $post_id)
            : true;
        $should_delete_physical_file = $now_unreferenced
            && !(function_exists('drop_print_is_file_in_live_order') && drop_print_is_file_in_live_order($afp_base_filename));
        if ($should_delete_physical_file) {
            $uploads = wp_upload_dir();
            if (empty($uploads['error'])) {
                $drop_print_dir = trailingslashit($uploads['basedir']) . 'drop-print';
                $full_path      = function_exists('drop_print_container_path') ? drop_print_container_path($drop_print_dir, $afp_base_filename) : trailingslashit($drop_print_dir) . $afp_base_filename . $container_ext_pv;
                $real_base_dir  = realpath($drop_print_dir);
                $real_file_path = realpath($full_path);
                if ($real_base_dir && $real_file_path && 0 === strpos($real_file_path, untrailingslashit($real_base_dir)) && file_exists($full_path)) {
                    if (wp_delete_file($full_path) !== false && function_exists('drop_print_files_delete_record')) {
                        drop_print_files_delete_record($afp_base_filename);
                    }
                }
            }
        }
    }
    $preview_id_from_meta_array = is_array($meta) ? ($meta['preview_id'] ?? null) : null;
    if(empty($preview_id_from_meta_array) && $product->meta_exists('_drop_print_preview_id_standalone')){
         $preview_id_from_meta_array = $product->get_meta('_drop_print_preview_id_standalone', true);
    }
    $preview_id_to_delete = !empty($preview_id_from_meta_array) ? absint($preview_id_from_meta_array) : 0;
    if ($preview_id_to_delete > 0) {
        $attachment_post = get_post($preview_id_to_delete);
        if ($attachment_post && 'attachment' === $attachment_post->post_type) {
            $current_featured_id = (int) get_post_thumbnail_id($post_id);
            if ($current_featured_id === $preview_id_to_delete) {
            } else {
                 wp_delete_attachment($preview_id_to_delete, true);
            }
        }
    }
}
add_action('before_delete_post', 'drop_print_handle_before_delete_post_pv', 20, 2);
