<?php

if (!defined('ABSPATH')) {
    exit;
}

// Inject the background color CSS variable into the frontend
add_action('wp_head', 'sapmfly_dynamic_back_top_color');
function sapmfly_dynamic_back_top_color()
{
    $default = '#4CAF50';
    $colorBg = get_option('sapmfly_back_top_bg_color', $default);
    $colorhv = get_option('sapmfly_back_top_hv_color', $default);

    // Validate
    if (!preg_match('/^#[a-fA-F0-9]{3,6}$/', $colorBg)) {
        $colorBg = $default;
    }
    if (!preg_match('/^#[a-fA-F0-9]{3,6}$/', $colorhv)) {
        $colorhv = $default;
    }

    echo '<style>:root { 
    --sapmfly-back-top-bg-color: ' . esc_attr($colorBg) . '; 
    --sapmfly-back-top-hv-color: ' . esc_attr($colorhv) . '; 
    }</style>';
}

// Handle AJAX saving of hex color
add_action('wp_ajax_sapmfly_save_back_top_color', function () {

    if (! current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }

    // Verify nonce
    if (
        ! isset($_POST['_wpnonce']) ||
        ! wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'sapmfly_color_save'
        )
    ) {
        wp_send_json_error('Invalid nonce');
    }

    $bg = isset($_POST['hex_color'])
        ? sanitize_text_field(wp_unslash($_POST['hex_color']))
        : '';

    $hv = isset($_POST['hex_hover'])
        ? sanitize_text_field(wp_unslash($_POST['hex_hover']))
        : '';

    $hexPattern = '/^#[a-fA-F0-9]{3}$|^#[a-fA-F0-9]{6}$/';

    if (! preg_match($hexPattern, $bg)) {
        wp_send_json_error('Invalid background color');
    }

    if (! preg_match($hexPattern, $hv)) {
        wp_send_json_error('Invalid hover color');
    }

    update_option('sapmfly_back_top_bg_color', $bg);
    update_option('sapmfly_back_top_hv_color', $hv);

    wp_send_json_success('Colors saved');
});

add_action('wp_ajax_sapmfly_save_pb_customization', function () {

    check_ajax_referer('sapmfly_pb_save', 'nonce');

    // Get values
    $color = isset($_POST['color'])
        ? sanitize_hex_color(wp_unslash($_POST['color']))
        : '';

    $height = isset($_POST['height'])
        ? intval(wp_unslash($_POST['height']))
        : 0;

    // Set defaults if empty
    if (empty($color)) {
        $color = '#4CAF50'; // default color
    }

    if ($height <= 0) {
        $height = 5; // default height
    }

    // Save
    update_option('sapmfly_pb_color', $color);
    update_option('sapmfly_pb_height', $height);

    wp_send_json_success([
        'message' => __('Settings saved successfully!', 'minifly')
    ]);
});


// Insert progress bar dynamic background and height via AJAX
add_action('wp_head', function () {
    if (get_option('sapmfly_enable_progress_bar', 'no') !== 'yes') {
        return;
    }

    $color  = get_option('sapmfly_pb_color', '#ff0000');
    $height = intval(get_option('sapmfly_pb_height', 5));

?>
    <style>
        :root {
            --sapmfly-pb-color: <?php echo esc_attr($color); ?>;
            --sapmfly-pb-height: <?php echo esc_attr($height); ?>px;
        }
    </style>
<?php
});

/**
 * Handle multiple image uploads via AJAX
 *
 * @param string $sapmfly_file_input_name   Input field name
 * @param string $sapmfly_db_option_name    DB option to save URL
 * @param array  $sapmfly_allowed_types     Allowed mime types
 * @return string|false Uploaded URL or false
 */
function sapmfly_handle_image_upload(
    $file_input_name,
    $db_option_name,
    $nonce_action = 'sapmfly_click_talk_popup_ajax',
    $nonce_field = '_wpnonce',
    $allowed_types = ['image/jpeg', 'image/png', 'image/webp']
) {
    // 1. Verify nonce
    if (
        ! isset($_POST[$nonce_field]) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST[$nonce_field])), $nonce_action)
    ) {
        wp_send_json_error('Invalid nonce for image upload.');
    }

    // 2. Sanitize the array key
    $file_input_name_safe = sanitize_key($file_input_name);

    // 3. Check if file exists safely
    if (empty($_FILES) || ! isset($_FILES[$file_input_name_safe])) {
        return false; // Nothing to upload
    }

    // 4. Copy to a local variable
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $file = $_FILES[$file_input_name_safe];

    // 5. Sanitize only the file name
    $file['name'] = sanitize_file_name($file['name']);

    // 6. Mime type check using wp_check_filetype (more secure)
    $file_info = wp_check_filetype($file['name']);
    if (! in_array($file_info['type'], $allowed_types, true)) {
        wp_send_json_error('Invalid image type for ' . esc_html($file_input_name_safe));
    }

    // 7. File size check (max 2MB)
    if ($file['size'] > 2 * 1024 * 1024) {
        wp_send_json_error('File too large for ' . esc_html($file_input_name_safe));
    }

    // 8. Upload
    require_once ABSPATH . 'wp-admin/includes/file.php';
    $upload = wp_handle_upload($file, ['test_form' => false]);

    if (isset($upload['error'])) {
        wp_send_json_error($upload['error']);
    }

    // 9. Save URL to DB
    $url = esc_url_raw($upload['url']);
    update_option($db_option_name, $url);

    return $url;
}

// Handle Click to talk AJAX saving
add_action('wp_ajax_sapmfly_save_click_talk_heading', function () {

    // Nonce check
    if (
        ! isset($_POST['_wpnonce']) ||
        ! wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'sapmfly_click_talk_popup_ajax'
        )
    ) {
        wp_send_json_error('Invalid nonce');
    }

    // Input receive sanitize
    $heading = isset($_POST['sapmfly_click_talk_popup_heading'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_popup_heading']))
        : '';

    $subheading = isset($_POST['sapmfly_click_talk_popup_subheading'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_popup_subheading']))
        : '';

    $highlighText = isset($_POST['sapmfly_click_talk_highlight_text'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_highlight_text']))
        : '';

    $bgColor = isset($_POST['sapmfly_click_talk_color_bg'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_color_bg']))
        : '';

    $agentOneName = isset($_POST['sapmfly_click_talk_agent_1_name'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_1_name']))
        : '';

    $agentOneDesignation = isset($_POST['sapmfly_click_talk_agent_1_designation'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_1_designation']))
        : '';

    $agentOneNumber = isset($_POST['sapmfly_click_talk_agent_1_number'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_1_number']))
        : '';

    $agentTwoName = isset($_POST['sapmfly_click_talk_agent_2_name'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_2_name']))
        : '';

    $agentTwoDesignation = isset($_POST['sapmfly_click_talk_agent_2_designation'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_2_designation']))
        : '';

    $agentTwoNumber = isset($_POST['sapmfly_click_talk_agent_2_number'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_2_number']))
        : '';

    $agentThreeName = isset($_POST['sapmfly_click_talk_agent_3_name'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_3_name']))
        : '';

    $agentThreeDesignation = isset($_POST['sapmfly_click_talk_agent_3_designation'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_3_designation']))
        : '';

    $agentThreeNumber = isset($_POST['sapmfly_click_talk_agent_3_number'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_3_number']))
        : '';

    // Save text fields
    update_option('sapmfly_click_talk_popup_heading', $heading);
    update_option('sapmfly_click_talk_popup_subheading', $subheading);
    update_option('sapmfly_click_talk_highlight_text', $highlighText);
    update_option('sapmfly_click_talk_color_bg', $bgColor);

    // Handle all the images
    sapmfly_handle_image_upload('sapmfly_click_talk_qr_image', 'sapmfly_click_talk_qr_image');

    // Agent 1
    update_option('sapmfly_click_talk_agent_1_name', $agentOneName);
    update_option('sapmfly_click_talk_agent_1_designation', $agentOneDesignation);
    update_option('sapmfly_click_talk_agent_1_number', $agentOneNumber);
    sapmfly_handle_image_upload('sapmfly_click_talk_agent_1_image', 'sapmfly_click_talk_agent_1_image');

    // Agent 2
    update_option('sapmfly_click_talk_agent_2_name', $agentTwoName);
    update_option('sapmfly_click_talk_agent_2_designation', $agentTwoDesignation);
    update_option('sapmfly_click_talk_agent_2_number', $agentTwoNumber);
    sapmfly_handle_image_upload('sapmfly_click_talk_agent_2_image', 'sapmfly_click_talk_agent_2_image');

    // Agent 3
    update_option('sapmfly_click_talk_agent_3_name', $agentThreeName);
    update_option('sapmfly_click_talk_agent_3_designation', $agentThreeDesignation);
    update_option('sapmfly_click_talk_agent_3_number', $agentThreeNumber);
    sapmfly_handle_image_upload('sapmfly_click_talk_agent_3_image', 'sapmfly_click_talk_agent_3_image');

    // Send success response
    wp_send_json_success('Popup settings saved successfully');
});


// Handle Click to call AJAX saving
add_action('wp_ajax_sapmfly_save_click_call_heading', function () {

    // Nonce check
    if (
        ! isset($_POST['_wpnonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'sapmfly_click_call_popup_ajax')
    ) {
        wp_send_json_error('Invalid nonce');
    }

    // Input receive sanitize
    $heading = isset($_POST['sapmfly_click_call_popup_heading'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_call_popup_heading']))
        : '';

    $subheading = isset($_POST['sapmfly_click_call_popup_subheading'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_call_popup_subheading']))
        : '';

    $highlighText = isset($_POST['sapmfly_click_call_highlight_text'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_call_highlight_text']))
        : '';

    $bgColor = isset($_POST['sapmfly_click_call_color_bg'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_call_color_bg']))
        : '';

    $agentFourName = isset($_POST['sapmfly_click_talk_agent_4_name'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_4_name']))
        : '';

    $agentFourDesignation = isset($_POST['sapmfly_click_talk_agent_4_designation'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_4_designation']))
        : '';

    $agentFourNumber = isset($_POST['sapmfly_click_talk_agent_4_number'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_click_talk_agent_4_number']))
        : '';

    // Save text fields
    update_option('sapmfly_click_talk_popup_heading', $heading);
    update_option('sapmfly_click_talk_popup_subheading', $subheading);
    update_option('sapmfly_click_talk_highlight_text', $highlighText);
    update_option('sapmfly_click_talk_color_bg', $bgColor);

    // Handle images
    sapmfly_handle_image_upload(
        'sapmfly_click_call_qr_image',
        'sapmfly_click_call_qr_image',
        'sapmfly_click_call_popup_ajax'
    );

    // Agent 4
    update_option('sapmfly_click_talk_agent_4_name', $agentFourName);
    update_option('sapmfly_click_talk_agent_4_designation', $agentFourDesignation);
    update_option('sapmfly_click_talk_agent_4_number', $agentFourNumber);

    sapmfly_handle_image_upload(
        'sapmfly_click_talk_agent_4_image',
        'sapmfly_click_talk_agent_4_image',
        'sapmfly_click_call_popup_ajax'
    );

    wp_send_json_success('Popup settings saved successfully');
});

// handle add to cart change text
add_action('wp_ajax_sapmfly_save_cac_text', function () {

    // Nonce check
    if (
        ! isset($_POST['_wpnonce']) ||
        ! wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'sapmfly_cac_ajax_nonce'
        )
    ) {
        wp_send_json_error('Invalid nonce');
    }

    // Sanitize input
    $text = isset($_POST['sapmfly_cac_text'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_cac_text']))
        : '';

    // Save to DB
    update_option('sapmfly_cac_text', $text);

    wp_send_json_success('Saved successfully');
});

// Handle Floating Button AJAX saving
add_action('wp_ajax_sapmfly_floating_btn_handling', function () {

    // Nonce check
    if (
        ! isset($_POST['_wpnonce']) ||
        ! wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'sapmfly_floating_btn_popup_ajax'
        )
    ) {
        wp_send_json_error('Invalid nonce');
    }

    // Input sanitize
    $btnText = isset($_POST['sapmfly_floating_btn_text'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_text']))
        : '';

    $raw_url = isset($_POST['sapmfly_floating_btn_url'])
        ? esc_url_raw(wp_unslash($_POST['sapmfly_floating_btn_url']))
        : '';

    if ($raw_url === '' || $raw_url === '#') {
        $btnUrl = $raw_url;
    } else {
        $btnUrl = esc_url_raw($raw_url);

        if (empty($btnUrl)) {
            wp_send_json_error('Invalid URL provided');
        }
    }

    $btnColor = isset($_POST['sapmfly_floating_btn_color'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_color']))
        : '';

    $btnBg = isset($_POST['sapmfly_floating_btn_bg'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_bg']))
        : '';

    $btnHover = isset($_POST['sapmfly_floating_btn_hover'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_hover']))
        : '';

    $btnIcon = isset($_POST['sapmfly_floating_btn_icon'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_icon']))
        : '';

    $btnClose = isset($_POST['sapmfly_floating_btn_close_option'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_close_option']))
        : '';

    $btnLink = isset($_POST['sapmfly_floating_btn_open_link'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_open_link']))
        : '';

    $btnStyle = isset($_POST['sapmfly_floating_btn_style'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_style']))
        : '';

    $btnPosition = isset($_POST['sapmfly_floating_btn_position'])
        ? sanitize_text_field(wp_unslash($_POST['sapmfly_floating_btn_position']))
        : '';

    // Save options
    update_option('sapmfly_floating_btn_text', $btnText);
    update_option('sapmfly_floating_btn_url', $btnUrl);
    update_option('sapmfly_floating_btn_color', $btnColor);
    update_option('sapmfly_floating_btn_bg', $btnBg);
    update_option('sapmfly_floating_btn_hover', $btnHover);

    // If delete requested
    if (! empty($_POST['sapmfly_floating_btn_icon_delete'])) {
        delete_option('sapmfly_floating_btn_icon');
    }

    // If new image uploaded
    if (! empty($_FILES['sapmfly_floating_btn_icon'])) {
        sapmfly_handle_image_upload(
            'sapmfly_floating_btn_icon',
            'sapmfly_floating_btn_icon'
        );
    }

    update_option('sapmfly_floating_btn_close_option', $btnClose);
    update_option('sapmfly_floating_btn_open_link', $btnLink);
    update_option('sapmfly_floating_btn_style', $btnStyle);
    update_option('sapmfly_floating_btn_position', $btnPosition);

    wp_send_json_success('Popup settings saved successfully');
});
