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

function kirb_color_filter_creator($hex) {
    $rgb = kirbHexToRgb($hex);
    $color = new KIRBColor($rgb[0], $rgb[1], $rgb[2]);
    $solver = new KIRBColorSolver($color);
    $result = $solver->solve();
    return $result['filter'];
}

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['text_primary_color'] = sanitize_hex_color(kirb_readable_text_color($settings['primary_color']));
        $settings['text_accent_color'] = sanitize_hex_color(kirb_readable_text_color($settings['accent_color']));

        $settings['products_per_page'] = isset($_POST['products_per_page']) ? absint(sanitize_text_field(wp_unslash($_POST['products_per_page']))) : 0;
        $settings['cache_enabled'] = isset($_POST['cache_enabled']) ? 'true' : 'false';
        $settings['ring_setting_catg'] = isset($_POST['ring_setting_catg']) ? sanitize_text_field(wp_unslash($_POST['ring_setting_catg'])) : '';
        if (isset($_POST['ring_wedding_catg']) && is_array($_POST['ring_wedding_catg'])) {
            $ring_wedding_catg = array_map('sanitize_text_field', wp_unslash($_POST['ring_wedding_catg']));
            $settings['ring_wedding_catg'] = wp_json_encode($ring_wedding_catg);
        } else {
            $settings['ring_wedding_catg'] = '[]';
        }
        if (isset($_POST['engraving_catg']) && is_array($_POST['engraving_catg'])) {
            $engraving_catg = array_map('sanitize_text_field', wp_unslash($_POST['engraving_catg']));
            $settings['engraving_catg'] = wp_json_encode($engraving_catg);
        } else {
            $settings['engraving_catg'] = '[]';
        }

        $catg_control = array();

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

        $settings['catg_control'] = wp_json_encode($catg_control);

        if (!in_array(true, $catg_control)) {
            $toast_msg = "At least one category must be enabled!";
        } else {
            // Generate primary color filter
            $settings['primary_color_filter'] = kirb_color_filter_creator($settings['primary_color']);
            $settings['text_primary_color_filter'] = kirb_color_filter_creator($settings['text_primary_color']);
            $settings['text_accent_color_filter'] = kirb_color_filter_creator($settings['text_accent_color']);

            foreach ($settings as $key => $value) {
                kirbAddMeta('_setting_' . $key, $value);
            }
            $toast_msg = "Settings saved successfully!";
        }

        if (isset($_POST['initial_sub_tab'])) {
            kirb_set_initial_active_tab(sanitize_text_field(wp_unslash($_POST['initial_sub_tab'])));
        }

        kirb_set_completed_tab('initial-tab', true);
        kirb_set_active_tab('initial-tab');
    } else if (sanitize_text_field(wp_unslash($_POST['settings_action'])) == 'clear_cache') {
        global $wpdb;
        $table_name = $wpdb->prefix . 'kirb_cache';

        // Use $wpdb->prepare for safety
        $wpdb->query($wpdb->prepare("TRUNCATE TABLE %i", $table_name));

        $toast_msg = "Cache cleared successfully!";
        kirb_set_active_tab('initial-tab');
    } else if (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['message'])) : '';

        $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(KIRB_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 $kirb_hide_support_form;
        $kirb_hide_support_form = true;
        kirb_set_active_tab('help-tab');
    }
}else if(isset($_POST['language_action']) && isset($_POST['csrf_language_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['csrf_language_nonce'])), 'language_tab_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(kirbGetMeta('_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'];
        }
        kirbAddMeta('_regional_data', wp_json_encode($regional_data));
    }

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

    global $kirb_active_lang_tab_config;
    if(isset($_POST['current_tab']) && isset($kirb_active_lang_tab_config[sanitize_text_field(wp_unslash($_POST['current_tab']))])) {
        foreach($kirb_active_lang_tab_config as $key => $value) {
            $kirb_active_lang_tab_config[$key] = false;
        }
        $kirb_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);

        kirb_file_put_contents(wp_get_upload_dir()['basedir'] . DIRECTORY_SEPARATOR .'kirb-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 = kirb_file_get_contents(KIRB_PLUGIN_DIR.'/languages/'.$lang.'.json');
            $curr_lang_data = json_decode($curr_lang_data, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                kirb_file_put_contents(KIRB_BASE_DIR . 'languages'. DIRECTORY_SEPARATOR . $lang . '.json', wp_json_encode($curr_lang_data, JSON_PRETTY_PRINT));
            }
        }

        // Other lang update
        $other_lang_data = isset($_POST['other_lang_data']) ? sanitize_textarea_field(wp_unslash($_POST['other_lang_data'])) : '';
        $other_lang_data = json_decode(stripslashes($other_lang_data), true);
        $kirb_upload_dir = wp_get_upload_dir();
        kirb_file_put_contents($kirb_upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'kirb-other-lang.json', wp_json_encode($other_lang_data, JSON_PRETTY_PRINT));

        // Clear lang cache
        kirb_delete_cache_db('kirb-locale-cache-other');
        kirb_delete_cache_db('kirb-ud-local-cache'); 
        
        $toast_msg = "Localization Updated successfully!";
    }else{
        $toast_msg = "Something Went Wrong!";
    }
    kirb_set_active_tab('lang-tab');
    kirb_set_completed_tab('lang-tab', true);
    kirb_set_completed_tab('feed-control', true);
}else if(isset($_POST['kirb_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();
    
    kirbAddMeta('_user_info', wp_json_encode($user_info));
    
    $is_plugin_active = kirbGetMeta('_is_plugin_active') == 'true';

    if($is_plugin_active) {
        kirb_set_active_tab('help-tab');
    }else{
        kirb_set_active_tab('initial-tab');
    }

    kirb_set_completed_tab('pricing-tab', true);

    include_once("plugin_activation_hook.php");
} else if (isset($_POST['kirb_activation']) && isset($_POST['kirb_email_permission_nonce'])) {
    $nonce = sanitize_text_field(wp_unslash($_POST['kirb_email_permission_nonce']));
    if ( wp_verify_nonce($nonce, 'kirb_email_permission') ) {
        $permission = isset($_POST['email_permission_action']) ? sanitize_text_field(wp_unslash($_POST['email_permission_action'])) : '';
        $permission = $permission === 'accept';
        kirb_register_plugin($permission);
    }
}
