<?php
if (!defined('ABSPATH')) {
    exit;
}
/* phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange */

$active_tab = 'advance-filter-tab';
$error = false;
if (isset($_POST['settings_action']) && isset($_POST['csrf_settings_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['csrf_settings_nonce'])), 'settings_action')) {
    if (sanitize_text_field(wp_unslash($_POST['settings_action'])) == 'settings') {
        $settings = array();
        $settings['primary_color'] = isset($_POST['primary_color']) ? sanitize_hex_color(wp_unslash($_POST['primary_color'])) : '';
        $settings['accent_color'] = isset($_POST['accent_color']) ? sanitize_hex_color(wp_unslash($_POST['accent_color'])) : '';
        $settings['products_per_page'] = isset($_POST['products_per_page']) ? absint(wp_unslash($_POST['products_per_page'])) : 0;
        $settings['engagement_ring_catg'] = isset($_POST['engagement_ring_catg']) ? sanitize_text_field(wp_unslash($_POST['engagement_ring_catg'])) : '';
        $settings['wedding_ring_catg'] = isset($_POST['wedding_ring_catg']) ? sanitize_text_field(wp_unslash($_POST['wedding_ring_catg'])) : '';

        //////////////////////////////////////////////////////////////////
        // START: Attribute mapping settings with updated configuration //
        //////////////////////////////////////////////////////////////////
        // START: Attribute mapping settings with updated configuration
        $attributes = [
            'engagement_ring_style' => [
                'meta_key' => 'style_attr_advance_filters',
                'group' => 'engagement_ring_style_terms',
                'prefix' => '', // We want keys like "solitaire", "halo", etc.
                'remove_prefix' => 'style_', // Remove "style_" from meta slug (e.g., "style_solitaire" becomes "solitaire")
                'post_term_prefix' => 'engagement_ring_terms_style_' // Must match the POST names from the frontend
            ],
            'engagement_ring_side_stone' => [
                'meta_key' => 'side_stone_attr_advance_filters',
                'group' => 'engagement_ring_sidestone_terms',
                'prefix' => '', // We want keys like "lab", "morganite", etc.
                'remove_prefix' => 'sidestone_', // Remove "sidestone_" from meta slug (e.g., "sidestone_lab" becomes "lab")
                'post_term_prefix' => 'engagement_ring_terms_sidestone_', // Must match the POST names from the frontend
                'json_key' => 'engagement_ring_sidestone' // Save the attribute value under this key in final JSON
            ],
            'wedding_ring_wed_men' => [
                'meta_key' => 'wed_men_attr_advance_filters',
                'group' => 'wedding_ring_terms_wedmen',
                'prefix' => '', // Final keys will be "classic", "carved", etc.
                'remove_prefix' => 'wedmen_',  // Remove "wedmen_" from meta slug
                'post_term_prefix' => 'wedding_ring_terms_wedmen_' // Must match the POST names
            ],
            'wedding_ring_wed_women' => [
                'meta_key' => 'wed_women_attr_advance_filters',
                'group' => 'wedding_ring_terms_wedwomen',
                'prefix' => '', // Final keys will be as provided in the meta data (after removal)
                'remove_prefix' => 'wedwomen_', // Remove "wedwomen_" from meta slug
                'post_term_prefix' => 'wedding_ring_terms_wedwomen_' // Must match the POST names
            ],
            'metal' => [
                'meta_key' => 'metal_attr_advance_filters',
                'group' => 'metal_terms',
                'prefix' => '', // Use the term slug after removal
                'remove_prefix' => 'metal_', // Remove "metal_" so that "metal_white_gold_14k" becomes "white_gold_14k"
                'post_term_prefix' => 'terms_metal_' // Must match the POST names
            ],
            'shape' => [
                'meta_key' => 'shape_attr_advance_filters',
                'group' => 'shape_terms',
                'prefix' => '', // Use the term slug after removal
                'remove_prefix' => 'shape_', // Remove "shape_" so that "shape_round" becomes "round"
                'post_term_prefix' => 'terms_shape_' // Must match the POST names
            ]
        ];

        $attributes_mapping = [];

        // Process each attribute based on the configuration
        foreach ($attributes as $attr_key => $config) {
            // Get the attribute value from POST
            $attr_value = isset($_POST[$attr_key]) ? sanitize_text_field(wp_unslash($_POST[$attr_key])) : '';

            // Use the provided json_key if available; otherwise, use the attribute key
            $top_key = isset($config['json_key']) ? $config['json_key'] : $attr_key;
            $attributes_mapping[$top_key] = $attr_value;

            // Retrieve the meta data (assumed to be a JSON string) and decode it.
            $terms = json_decode(krfsapp_getMeta($config['meta_key']), true);
            if (is_array($terms)) {
                // Ensure the group exists for term keys.
                if (!isset($attributes_mapping[$config['group']])) {
                    $attributes_mapping[$config['group']] = [];
                }

                foreach ($terms as $term) {
                    // Get the term slug from meta data.
                    $term_slug = $term['slug'];

                    // Remove the unwanted prefix from the meta slug if it exists.
                    if (!empty($config['remove_prefix']) && strpos($term_slug, $config['remove_prefix']) === 0) {
                        $term_slug = substr($term_slug, strlen($config['remove_prefix']));
                    }

                    // Build the final JSON key using the desired prefix (empty here) and the modified slug.
                    $final_key = $config['prefix'] . $term_slug;

                    // Build the POST key using the post_term_prefix and the modified slug.
                    $post_key = $config['post_term_prefix'] . $term_slug;

                    // Retrieve the term value from POST using the constructed key.
                    $attributes_mapping[$config['group']][$final_key] = isset($_POST[$post_key]) ? sanitize_text_field(wp_unslash($_POST[$post_key])) : '';
                }
            }
        }

        // Finally, encode the organized mapping as JSON and save it.
        krfsapp_addMeta('attributes_mapping', wp_json_encode($attributes_mapping));
        ////////////////////////////////////////////////////////////////
        // END: Attribute mapping settings with updated configuration //
        ////////////////////////////////////////////////////////////////


        // Generate primary color filter
        $rgb = krfsHexToRgb($settings['primary_color']);
        $color = new KRFSAPPColor($rgb[0], $rgb[1], $rgb[2]);
        $solver = new KRFSAPPSolver($color);
        $result = $solver->solve();
        $settings['primary_color_filter'] = $result['filter'];
        $catg_control = array();

        foreach (KRFSAPP_ALL_CATEGORIES as $catg) {
            $catg_control[$catg] = isset($_POST[str_replace(" ", "_", $catg)]) ? true : false;
            if (isset(KRFSAPP_ALL_CATEGORIES_MAP[$catg])) {
                krfsapp_update_page_status(KRFSAPP_ALL_CATEGORIES_MAP[$catg], $catg_control[$catg]);
            }
        }

        $settings['catg_control'] = wp_json_encode($catg_control);
        foreach ($settings as $key => $value) {
            krfsapp_addMeta('_setting_' . $key, $value);
        }

        // Sanitize array inputs prior to JSON encoding
        $ring_wedding_catg = '[]';
        if (isset($_POST['ring_wedding_catg'])) {
            $ring_wedding_catg_arr = (array) wp_unslash($_POST['ring_wedding_catg']);
            $ring_wedding_catg = wp_json_encode(map_deep($ring_wedding_catg_arr, 'sanitize_text_field'));
        }
        $engraving_catg = '[]';
        if (isset($_POST['engraving_catg'])) {
            $engraving_catg_arr = (array) wp_unslash($_POST['engraving_catg']);
            $engraving_catg = wp_json_encode(map_deep($engraving_catg_arr, 'sanitize_text_field'));
        }

        krfsapp_addMeta('_setting_ring_wedding_catg', $ring_wedding_catg);
        krfsapp_addMeta('_setting_engraving_catg', $engraving_catg);

        $sectionSettings = json_decode(krfsapp_getMeta('_setting_section_controls'), true) ?? [];
        
        krfsapp_addMeta('_setting_section_controls', wp_json_encode($sectionSettings));

        $toast_msg = "Settings saved successfully!";

        krfsapp_set_initial_active_tab(sanitize_text_field(wp_unslash($_POST['settings_action'])));

        krfsapp_set_completed_tab('initial-tab', true);
        krfsapp_set_active_tab('initial-tab');
    } else if (isset($_POST['settings_action']) && sanitize_text_field(wp_unslash($_POST['settings_action'])) == 'sendMail') {
        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $phone_number = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';
        $message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['phone'])) : '';

        $msg_body = "You've got a new message on" . gmdate('F j, Y g:i a T') . " from " . '<a href="' . site_url() . '">' . site_url() . '</a><br><br>';
        $msg_body .= "Email: " . $email . "<br>";
        $msg_body .= "Phone Number: " . $phone_number . "<br>";
        $msg_body .= "Message: " . $message . "<br>";

        $subject = 'New support request from: ' . $email;
        $admin_email = get_option('admin_email');
        $headers = "From: $admin_email" . "\r\n" .
            "Reply-To: $admin_email" . "\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n";

        $mail_sent = mail(KRFSAPP_SUPPORT_REQUEST_MAIL, $subject, $msg_body, $headers);

        if ($mail_sent) {
            $toast_msg = "Support request sent successfully!";
        } else {
            $toast_msg = "Failed to send support request!<br>Error: " . error_get_last()['message'];
        }
        global $krfsapp_hide_support_form;
        $krfsapp_hide_support_form = true;
        krfsapp_set_active_tab('help-tab');
    }
    // krfsapp_set_active_tab('initial-tab');
} else if (isset($_POST['language_action'])) {
    $lang_data = isset($_POST['user_defined_localization']) ? sanitize_textarea_field(wp_unslash($_POST['user_defined_localization'])) : '';
    $lang_data = json_decode(stripslashes($lang_data), true);
    $regional_lang_data = isset($_POST['regional_lang_data']) ? sanitize_textarea_field(wp_unslash($_POST['regional_lang_data'])) : '';

    if (!empty($regional_lang_data)) {
        $regional_lang_data = json_decode(stripslashes($regional_lang_data), true);
        $regional_data = json_decode(krfsapp_getMeta('_regional_data'), true);
        foreach ($regional_data as $lang => $r_data) {
            if ($lang != 'en_US') {
                $regional_data[$lang]['enabled'] = false;
            }
        }
        foreach ($regional_lang_data as $reg_data) {
            $regional_data[$reg_data['lang']]['enabled'] = true;
            $regional_data[$reg_data['lang']]['ring_size'] = $reg_data['ring_size'];
        }
        krfsapp_addMeta('_regional_data', wp_json_encode($regional_data));
    }

    global $krfsapp_language_current_page;
    $krfsapp_language_current_page = isset($_POST['current_page']) ? sanitize_text_field(wp_unslash($_POST['current_page'])) : '';

    global $krfsapp_active_lang_tab_config;
    if (isset($krfsapp_active_lang_tab_config[sanitize_text_field(wp_unslash($_POST['current_tab']))])) {
        foreach ($krfsapp_active_lang_tab_config as $key => $value) {
            $krfsapp_active_lang_tab_config[$key] = false;
        }
        $krfsapp_active_lang_tab_config[sanitize_text_field(wp_unslash($_POST['current_tab']))] = true;
    }

    if (json_last_error() === JSON_ERROR_NONE) {
        $lang_json_output = wp_json_encode($lang_data, JSON_PRETTY_PRINT);

        krfsapp_file_put_contents(KRFSAPP_BASE_DIR . 'languages' . DIRECTORY_SEPARATOR . 'user-defined-localization.json', $lang_json_output);

        // Validate and update all language files
        $all_langs = array("en_US", "en_GB", "fr_FR", "de_DE", "es_ES", "it_IT");
        foreach ($all_langs as $lang) {
            $curr_lang_data = krfsapp_file_get_contents(KRFSAPP_PLUGIN_DIR . '/languages/' . $lang . '.json');
            $curr_lang_data = json_decode($curr_lang_data, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                krfsapp_file_put_contents(KRFSAPP_BASE_DIR . 'languages' . DIRECTORY_SEPARATOR . $lang . '.json', wp_json_encode($curr_lang_data));
            }
        }

        $toast_msg = "Languges & Region Updated successfully!";
    } else {
        $toast_msg = "Something Went Wrong!";
    }
    krfsapp_set_active_tab('lang_region');
    krfsapp_set_completed_tab('lang_region', true);
} else if (isset($_POST['krfs_plugin_activation']) && isset($_POST['csrf_activation_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['csrf_activation_nonce'])), 'plugin_activation_tab_action')) {
    $user_info_cols = array('name', 'company_name', 'email', 'phone', 'country');
    $user_info = array();
    foreach ($user_info_cols as $col) {
        if ($col == 'email') {
            $user_info[$col] = isset($_POST[$col]) ? sanitize_email(wp_unslash($_POST[$col])) : '';
        } else {
            $user_info[$col] = isset($_POST[$col]) ? sanitize_text_field(wp_unslash($_POST[$col])) : '';
        }
    }

    $user_info['website_url'] = site_url();

    krfsapp_set_active_tab('initial-tab');
    krfsapp_addMeta('_is_plugin_active', 'true');
    krfsapp_addMeta('_user_info', wp_json_encode($user_info));

    $is_plugin_active = krfsapp_getMeta('_is_plugin_active') == 'true';

    krfsapp_set_active_tab('help-tab');

    krfsapp_set_completed_tab('pricing-tab', true);
} else if (isset($_POST['advance_filter_action']) && !isset($_POST['delete_action'])) {

    $engagementRingTrigger = isset($_POST['engagement_ring_trigger']) ? sanitize_text_field(wp_unslash($_POST['engagement_ring_trigger'])) : '';

    // Retrieve current attribute data
    $shapeAttributes = json_decode(krfsapp_getMeta('shape_attr_advance_filters'), true) ?? [];
    $metalAttributes = json_decode(krfsapp_getMeta('metal_attr_advance_filters'), true) ?? [];
    $styleAttributes = json_decode(krfsapp_getMeta('style_attr_advance_filters'), true) ?? [];
    $wedMenAttributes = json_decode(krfsapp_getMeta('wed_men_attr_advance_filters'), true) ?? [];
    $SideStoneAttributes = json_decode(krfsapp_getMeta('side_stone_attr_advance_filters'), true) ?? [];
    $wedWomenAttributes = json_decode(krfsapp_getMeta('wed_women_attr_advance_filters'), true) ?? [];
    $sectionSettings = json_decode(krfsapp_getMeta('_setting_section_controls'), true) ?? [];

    // Process attributes
    if (empty($engagementRingTrigger)) {
        // Define attributes and their corresponding meta keys
        $attributesMapping = [
            'style_attr' => ['originalAttributes' => $styleAttributes, 'metaKey' => 'style_attr_advance_filters'],
            'side_stone_attr' => ['originalAttributes' => $SideStoneAttributes, 'metaKey' => 'side_stone_attr_advance_filters'],
            'wed_men_attr' => ['originalAttributes' => $wedMenAttributes, 'metaKey' => 'wed_men_attr_advance_filters'],
            'wed_women_attr' => ['originalAttributes' => $wedWomenAttributes, 'metaKey' => 'wed_women_attr_advance_filters'],
            'metal_attr' => ['originalAttributes' => $metalAttributes, 'metaKey' => 'metal_attr_advance_filters'],
            'shape_attr' => ['originalAttributes' => $shapeAttributes, 'metaKey' => 'shape_attr_advance_filters'],
        ];

        // Process all attributes
        foreach ($attributesMapping as $postKey => $config) {
            $enabledAttributes = isset($_POST[$postKey]) ? array_map('sanitize_text_field', (array) wp_unslash($_POST[$postKey])) : [];
            krfsapp_processAndUpdateFilterAttributes(
                $config['originalAttributes'],  // Original attributes
                $enabledAttributes,             // Enabled attributes from POST
                'krfsapp_update_advance_filters',  // Callback for updating
                $config['metaKey']              // Meta key for storing the updated attributes
            );
        }
        $enabledSections = isset($_POST['section_controls']) ? map_deep((array) wp_unslash($_POST['section_controls']), 'sanitize_text_field') : [];
        krfsapp_updateFilterSettingsControl($sectionSettings, $enabledSections);
        $toast_msg = "Advance Filters Updated successfully!";

    }

    if ($engagementRingTrigger === 'add-collection' || $engagementRingTrigger === 'edit-collection') {
        // Define a mapping for engagement ring triggers
        $engagementRingMapping = [
            'style_attr' => [
                'attributes' => $styleAttributes,
                'metaKey' => 'style_attr_advance_filters',
                'prefix' => 'style_',
            ],
            'wed_men_attr' => [
                'attributes' => $wedMenAttributes,
                'metaKey' => 'wed_men_attr_advance_filters',
                'prefix' => 'wedmen_',
            ],
            'wed_women_attr' => [
                'attributes' => $wedWomenAttributes,
                'metaKey' => 'wed_women_attr_advance_filters',
                'prefix' => 'wedwomen_',
            ],
        ];


        $newValue = isset($_POST['new_style_label']) ? sanitize_text_field(wp_unslash($_POST['new_style_label'])) : '';
        $oldValue = isset($_POST['old_style_label']) ? sanitize_text_field(wp_unslash($_POST['old_style_label'])) : '';
        $categoryName = isset($_POST['category_name']) ? sanitize_text_field(wp_unslash($_POST['category_name'])) : '';

        // Adds a new item to the category collection
        if ($engagementRingTrigger === 'add-collection') {
            $config = $engagementRingMapping[$categoryName];
            // Ensure the field is not empty
            if (!empty($newValue)) {
                $response = krfsapp_handleAddCollectionFilters(
                    $newValue,            // POST key
                    $config['attributes'],         // Attribute array (passed by reference)
                    $config['metaKey'],            // Meta key
                    $config['prefix'],
                    $categoryName           // Prefix for slug
                );
                $toast_msg = "Filter name added successfully!";
                if (!$response) {
                    $toast_msg = "Slug name already exists!";
                    $error = true;
                }
            } else {
                $toast_msg = "Filter name can't be empty!";
                $error = true;
            }
        }

        // Edit an item in the collection
        if ($engagementRingTrigger === 'edit-collection') {
            $response = krfsapp_handleEditCollectionFilters($newValue, $oldValue, $categoryName, $engagementRingMapping);
            $toast_msg = "Filter name edited successfully!";
            if (!$response) {
                $toast_msg = "Slug name already exists!";
                $error = true;
            }
        }
    }
    krfsapp_set_active_tab($active_tab);


} else if (isset($_POST['delete_action'])) {
    // Handle delete action
    $categoryToDeleteFrom = isset($_POST['category_name']) ? sanitize_text_field(wp_unslash($_POST['category_name'])) : ''; // Category to delete from
    $elementToDelete = isset($_POST['old_style_label']) ? sanitize_text_field(wp_unslash($_POST['old_style_label'])) : ''; // Name of the element to delete

    // Retrieve the current filter data
    $filterData = krfsapp_getMeta($categoryToDeleteFrom . '_advance_filters');

    $existingData = json_decode($filterData, true);

    // Check if the category exists and contains elements

    // Filter the array
    $updatedData = array_filter($existingData, function ($item) use ($elementToDelete) {
        return $item['name'] !== $elementToDelete;
    });

    // Reindex the array to ensure it starts from 0
    $updatedData = array_values($updatedData);
    $json_data = wp_json_encode($updatedData);
    $active_tab = 'advance-filter-tab';
    $toast_msg = "Item Deleted Successfully";
    krfsapp_set_active_tab($active_tab);
    krfsapp_addMeta($categoryToDeleteFrom . '_advance_filters', $json_data);
} else if (isset($_POST['krfs_activation']) && isset($_POST['krfs_email_permission_nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_POST['krfs_email_permission_nonce']));
    if ( wp_verify_nonce($nonce, 'krfs_email_permission') ) {
        $permission = isset($_POST['email_permission_action']) ? sanitize_text_field(wp_unslash($_POST['email_permission_action'])) : '';
        $permission = $permission === 'accept';
        krfsapp_init_activation($permission);
    }
}

/* phpcs:enable */
