<?php

/**
 * Debug script to check variation attribute data
 * Access via: /wp-content/plugins/woonoow/debug-variation.php
 * DELETE THIS FILE AFTER DEBUGGING
 */

require_once dirname(__DIR__, 3) . '/wp-load.php';

header('Content-Type: application/json');

$variation_id = isset($_GET['variation_id']) ? intval($_GET['variation_id']) : 515;
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 512;

$result = [];

// Get parent product
$product = wc_get_product($product_id);
if ($product && $product->is_type('variable')) {
    $result['parent_product'] = [
        'id' => $product->get_id(),
        'name' => $product->get_name(),
        'type' => $product->get_type(),
    ];

    // Get parent product attributes
    $result['parent_attributes'] = [];
    foreach ($product->get_attributes() as $key => $attribute) {
        $result['parent_attributes'][$key] = [
            'name' => $attribute->get_name(),
            'label' => wc_attribute_label($attribute->get_name()),
            'is_taxonomy' => $attribute->is_taxonomy(),
            'is_variation' => $attribute->get_variation(),
            'options' => $attribute->get_options(),
            'sanitized_name' => sanitize_title($attribute->get_name()),
        ];
    }

    // Get available variations from parent
    $result['available_variations'] = $product->get_available_variations();
}

// Get variation directly
$variation = wc_get_product($variation_id);
if ($variation && $variation->is_type('variation')) {
    $result['variation'] = [
        'id' => $variation->get_id(),
        'name' => $variation->get_name(),
        'type' => $variation->get_type(),
        'parent_id' => $variation->get_parent_id(),
    ];

    // Get variation attributes using WooCommerce method
    $result['variation_attributes_wc'] = $variation->get_variation_attributes();

    // Get raw post meta
    global $wpdb;
    $meta_rows = $wpdb->get_results($wpdb->prepare(
        "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key LIKE 'attribute_%%'",
        $variation_id
    ));
    $result['variation_meta_raw'] = $meta_rows;

    // Get all meta for this variation
    $result['all_meta'] = get_post_meta($variation_id);
}

echo json_encode($result, JSON_PRETTY_PRINT);
