<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

?>
<?php if (!empty($common_top_note)) : ?>
    <div class="integrazo-wczo-setup-step2-note-bottom" style="margin-left: 170px !important;max-width: 71.5% !important;">
        <?php echo wp_kses_post($common_top_note); ?>
    </div>
<?php endif; ?>
<form method="post" id="integrazo-wczo-setup-mapping-area" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
    <?php
    // WordPress nonce and action field for security
    wp_nonce_field('integrazo_wczo_save_mapping_action', 'integrazo_wczo_save_mapping_nonce');
    ?>
    <input type="hidden" name="action" value="integrazo_wczo_save_mapping" />
    <input type="hidden" name="integration_id" value="<?php echo esc_attr($integration_id); ?>" />
    <input type="hidden" name="record_action" value="" />
    <input type="hidden" name="primary_key" value="" />
    <input type="hidden" name="filter_criteria" value="" />
    <input type="hidden" name="filter_criteria_json" value="" />
    <input type="hidden" name="final_json" value="" />

    <?php
    $raw_form_fields = INTEGRAZO_WCZO_Fields_Details::render($integration_details);

    if (! is_array($raw_form_fields)) {
        echo '<p style="text-align: center;">' . esc_html($raw_form_fields) . '</p>';
        return;
    }

    $normalized_form_fields = [];
    if (!empty($raw_form_fields)) {
        foreach ($raw_form_fields as $field) {
            $normalized_form_fields[] = [
                'name'      => $field['name'] ?? '',
                'label'     => $field['label'] ?? ($field['name'] ?? ''),
                'data_type' => $field['type'] ?? '',
                'identifier' => $field['identifier'] ?? '',
            ];
        }
    }

    $crm_fields = $normalized_crm_fields;
    $all_fields = $normalized_form_fields;

    // Prepare form fields including system fields
    $form_fields = [
        'form_fields'   => [],
        'system_fields' => [
            ['name' => 'custom_value', 'label' => 'Custom Value'],
            // ['name' => 'submitted_url', 'label' => 'Submitted Url'],
        ],
    ];

    foreach ($all_fields as $field) {
        $form_fields['form_fields'][] = [
            'name'      => $field['name'],
            'label'     => $field['label'],
            'data_type' => $field['data_type'],
            'identifier' => $field['identifier'] ?? '',
        ];
    }

    // Pass form fields to JS
    wp_localize_script('integrazo-wczo-custom-js', 'integrazoFCData', [
        'form_fields' => $form_fields['form_fields'],
    ]);

    $field_mapping = json_decode($integration_details['field_mapping'] ?? '', true);

    if (empty($field_mapping)) {
        require_once INTEGRAZO_WCZO_PLUGIN_DIR . 'src/products/mapping.php';
    } else {
        $mandatory_mappings     = [];
        $non_mandatory_mappings = [];

        if (!empty($field_mapping)) {
            $mandatory_crm_fields = array_filter($crm_fields, function ($field) {
                return !empty($field['system_mandatory']);
            });

            $mandatory_crm_api_names = array_column($mandatory_crm_fields, 'api_name');

            foreach ($field_mapping as $map) {
                if (in_array($map['product_field'], $mandatory_crm_api_names, true)) {
                    $mandatory_mappings[] = $map;
                } else {
                    $non_mandatory_mappings[] = $map;
                }
            }
        }

        require_once INTEGRAZO_WCZO_PLUGIN_DIR . 'src/products/ex-mapping.php';
    }


    // Load filter section
    require_once INTEGRAZO_WCZO_PLUGIN_DIR . 'src/products/filter.php';
    ?>

    <!-- Submit Button -->
    <div class="integrazo-wczo-setup-next-btn-wrapper">
        <button type="submit" class="button button-primary" id="integrazo-wczo-save-mapping"
            style="<?php echo empty($integration_data) ? 'display:none;' : ''; ?>">
            <?php esc_html_e('Save Mapping', 'integrazo-wc-zoho-integration'); ?>
        </button>
    </div>

</form>