<?php
if (!defined('ABSPATH')) exit;

add_filter('product_type_selector', function ($types) {
    $types['auction'] = 'Auction';
    return $types;
});

add_action('init', function () {
    if (!class_exists('STAKMV_Product_Auction')) {
        class STAKMV_Product_Auction extends WC_Product_Simple {
            public function get_type() {
                return 'auction';
            }
        }
    }

});

/**
 * Ensure WooCommerce resolves `product_type=auction` to our custom product class.
 * Keeps admin/editor/API behavior consistent.
 */
add_filter('woocommerce_product_class', function ($classname, $product_type, $post_type = '', $product_id = 0) {
    if ($product_type === 'auction') {
        return 'STAKMV_Product_Auction';
    }
    return $classname;
}, 10, 4);

add_action('woocommerce_product_options_general_product_data', function () {
    echo '<div class="options_group show_if_auction">';
    woocommerce_wp_text_input([
        'id' => '_stakmv_auction_start_price',
        'label' => 'Start Price',
        'type' => 'number',
    ]);

    woocommerce_wp_text_input([
    'id'                => '_stakmv_auction_buy_now_price',
    'label'             => 'Buy Now Price',
    'type'              => 'number',
    'custom_attributes' => [
        'step' => '0.01',
        'min'  => '0'
    ],
    'desc_tip'    => true,
    'description' => 'Optional. Buyers can instantly purchase at this price.',
]);

    woocommerce_wp_text_input([
        'id' => '_stakmv_auction_end_time',
        'label' => 'End Time',
        'type' => 'datetime-local',
    ]);
    woocommerce_wp_select([
    'id'      => '_stakmv_auction_sale_mode',
    'label'   => 'Sale Mode',
    'options' => [
        'auction' => 'Auction only',
        'buy_now' => 'Buy Now only',
        'both'    => 'Auction + Buy Now',
    ],
    'desc_tip' => true,
    'description' => 'Choose how this item can be purchased.',
]);



    echo '</div>';
});

add_action('woocommerce_admin_process_product_object', function ($product) {
    if ($product->get_type() !== 'auction') return;

    // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified explicitly below.
    if (
        !isset($_POST['_wpnonce']) ||
        !wp_verify_nonce(
            sanitize_text_field((string) wp_unslash($_POST['_wpnonce'])),
            'update-post_' . $product->get_id()
        )
    ) {
        return;
    }
    $product_input = isset($_POST) && is_array($_POST)
        ? map_deep(wp_unslash($_POST), 'sanitize_text_field')
        : array();

    $start_price = isset($product_input['_stakmv_auction_start_price'])
        ? wc_clean((string) $product_input['_stakmv_auction_start_price'])
        : '';
    $product->update_meta_data('_stakmv_auction_start_price', $start_price);

    $raw_end = isset($product_input['_stakmv_auction_end_time']) ? wc_clean((string) $product_input['_stakmv_auction_end_time']) : '';
    $end_ts  = is_numeric($raw_end) ? (int) $raw_end : ( ( $raw_end !== '' ) ? strtotime($raw_end) : 0 );
    $product->update_meta_data('_stakmv_auction_end_time', $end_ts);
    $product->update_meta_data('_stakmv_auction_status', 'active');

    if (isset($product_input['_stakmv_auction_sale_mode'])) {
        $product->update_meta_data(
            '_stakmv_auction_sale_mode',
            wc_clean((string) $product_input['_stakmv_auction_sale_mode'])
        );
    } else {
        $product->update_meta_data('_stakmv_auction_sale_mode', 'auction');
    }

    if (isset($product_input['_stakmv_auction_buy_now_price'])) {
        $product->update_meta_data(
            '_stakmv_auction_buy_now_price',
            wc_clean((string) $product_input['_stakmv_auction_buy_now_price'])
        );
    }
    // phpcs:enable WordPress.Security.NonceVerification.Missing
});

add_action('admin_enqueue_scripts', function ($hook_suffix) {
    if ($hook_suffix !== 'post.php' && $hook_suffix !== 'post-new.php') {
        return;
    }

    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    if (!$screen || $screen->post_type !== 'product') {
        return;
    }

    wp_enqueue_script(
        'stakmv-admin-auction-product',
        STAKMV_PLUGIN_URL . 'assets/js/admin-auction-product.js',
        array('jquery'),
        file_exists(STAKMV_PLUGIN_PATH . 'assets/js/admin-auction-product.js')
            ? (string) filemtime(STAKMV_PLUGIN_PATH . 'assets/js/admin-auction-product.js')
            : (defined('STAKMV_VERSION') ? STAKMV_VERSION : '1.0.0'),
        true
    );
});
