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

add_action('stakmv_auctions_settings_tabs', function ($current_tab) {
    printf(
        '<a href="?page=stakmv-auctions&tab=form" class="nav-tab %s">Form</a>',
        $current_tab === 'form' ? 'nav-tab-active' : ''
    );
});

add_action('stakmv_auctions_render_tab_form', function () {
    $defaults = function_exists('stakmv_get_listing_form_defaults')
        ? stakmv_get_listing_form_defaults()
        : array('sections' => array(), 'fields' => array());

    $locked = function_exists('stakmv_get_listing_form_locked_controls')
        ? stakmv_get_listing_form_locked_controls()
        : array('sections' => array(), 'fields' => array());

    if (isset($_POST['save_form_settings'])) {
        check_admin_referer('stakmv_save_form_settings', 'stakmv_save_form_settings_nonce');

        $submitted_sections = array();
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Presence check only; values are sanitized below.
        if (isset($_POST['stakmv_form_sections']) && is_array($_POST['stakmv_form_sections'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Checkbox array keys are sanitized in the loop below.
            $submitted_sections_raw = wp_unslash($_POST['stakmv_form_sections']);
            foreach ((array) $submitted_sections_raw as $section_key => $_section_value) {
                $submitted_sections[sanitize_key((string) $section_key)] = '1';
            }
        }

        $submitted_fields = array();
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Presence check only; values are sanitized below.
        if (isset($_POST['stakmv_form_fields']) && is_array($_POST['stakmv_form_fields'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Checkbox array keys are sanitized in the loop below.
            $submitted_fields_raw = wp_unslash($_POST['stakmv_form_fields']);
            foreach ((array) $submitted_fields_raw as $field_key => $_field_value) {
                $submitted_fields[sanitize_key((string) $field_key)] = '1';
            }
        }

        $sections = array();
        foreach ($defaults['sections'] as $key => $_default_state) {
            $is_checked = isset($submitted_sections[$key]);
            $sections[$key] = $is_checked ? 'yes' : 'no';
            if (in_array($key, $locked['sections'], true)) {
                $sections[$key] = 'yes';
            }
        }

        $fields = array();
        foreach ($defaults['fields'] as $key => $_default_state) {
            $is_checked = isset($submitted_fields[$key]);
            $fields[$key] = $is_checked ? 'yes' : 'no';
            if (in_array($key, $locked['fields'], true)) {
                $fields[$key] = 'yes';
            }
        }

        stakmv_update_option('listing_form_settings', array(
            'sections' => $sections,
            'fields'   => $fields,
        ));

        echo '<div class="updated"><p>Form settings saved.</p></div>';
    }

    $settings = function_exists('stakmv_get_listing_form_settings')
        ? stakmv_get_listing_form_settings()
        : $defaults;

    $section_labels = array(
        'item_details'      => 'Item Details section',
        'category_filters'  => 'Category & Filters section',
        'pricing_auction'   => 'Pricing & Auction section',
        'location_shipping' => 'Location & Shipping section',
        'faq'               => 'FAQ section',
        'photos'            => 'Photos section',
    );

    $field_labels = array(
        'title'                 => 'Title',
        'description'           => 'Description',
        'condition'             => 'Condition',
        'quantity'              => 'Quantity',
        'category'              => 'Category',
        'attributes'            => 'Attribute filters',
        'listing_type'          => 'Listing type (mode tabs)',
        'start_price'           => 'Starting price',
        'buy_now_price'         => 'Buy now price',
        'end_date'              => 'Auction end date',
        'location'              => 'Item location',
        'shipping_mode'         => 'Shipping type',
        'shipping_scope'        => 'Shipping scope + country selectors',
        'handling_time'         => 'Handling time',
        'returns_policy'        => 'Returns fields',
        'flat_shipping_cost'    => 'Flat shipping cost',
        'package_metrics'       => 'Package metrics (weight/dimensions)',
        'supported_carriers'    => 'Supported carriers',
        'faq_builder'           => 'FAQ builder fields',
        'photo_upload'          => 'Photo uploader + previews',
        'delete_listing_action' => 'Delete listing button',
    );

    ?>
    <form method="post">
        <?php wp_nonce_field('stakmv_save_form_settings', 'stakmv_save_form_settings_nonce'); ?>

        <p class="description" style="max-width:780px; margin: 6px 0 14px;">
            Control what vendors see on Create/Edit Listing forms. Items marked <strong>Core Required</strong> cannot be disabled.
        </p>

        <h3>Sections</h3>
        <table class="form-table">
            <?php foreach ($defaults['sections'] as $key => $_default_state) :
                $is_locked = in_array($key, $locked['sections'], true);
                $is_enabled = isset($settings['sections'][$key]) ? $settings['sections'][$key] === 'yes' : true;
                ?>
                <tr>
                    <th scope="row"><?php echo esc_html($section_labels[$key] ?? $key); ?></th>
                    <td>
                        <label>
                            <input
                                type="checkbox"
                                name="stakmv_form_sections[<?php echo esc_attr($key); ?>]"
                                value="1"
                                <?php checked($is_enabled); ?>
                                <?php disabled($is_locked); ?>
                            >
                            Show
                        </label>
                        <?php if ($is_locked) : ?>
                            <span class="description" style="margin-left:10px;"><strong>Core Required</strong></span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>

        <h3>Fields</h3>
        <table class="form-table">
            <?php foreach ($defaults['fields'] as $key => $_default_state) :
                $is_locked = in_array($key, $locked['fields'], true);
                $is_enabled = isset($settings['fields'][$key]) ? $settings['fields'][$key] === 'yes' : true;
                ?>
                <tr>
                    <th scope="row"><?php echo esc_html($field_labels[$key] ?? $key); ?></th>
                    <td>
                        <label>
                            <input
                                type="checkbox"
                                name="stakmv_form_fields[<?php echo esc_attr($key); ?>]"
                                value="1"
                                <?php checked($is_enabled); ?>
                                <?php disabled($is_locked); ?>
                            >
                            Show
                        </label>
                        <?php if ($is_locked) : ?>
                            <span class="description" style="margin-left:10px;"><strong>Core Required</strong></span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>

        <p><button class="button button-primary" name="save_form_settings" value="1">Save Changes</button></p>
    </form>
    <?php
});
