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


/**
 * Handles saving settings for the plugin.
 */
function integrazo_fwcrm_form_settings()
{
    // Verify nonce for security
    if (
        !isset($_POST['integrazo_fwcrm_form_settings_data_action_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['integrazo_fwcrm_form_settings_data_action_nonce'])),
            'integrazo_fwcrm_form_settings_data_action'
        )
    ) {
        wp_die(esc_html__('Security check failed.', 'crm-integration-freshworks-any-form'));
    }
    // Sanitize and save the checkbox values and other inputs
    $delete_data_on_uninstall = isset($_POST['integrazo_fwcrm_form_delete_data_on_uninstall']) && 'yes' === $_POST['integrazo_fwcrm_form_delete_data_on_uninstall'] ? 'yes' : 'no';
    $error_notification = isset($_POST['integrazo_fwcrm_form_error_notification']) && 'yes' === $_POST['integrazo_fwcrm_form_error_notification'] ? 'yes' : 'no';
    $error_notification_email = isset($_POST['integrazo_fwcrm_form_error_notification_email']) ? sanitize_text_field(wp_unslash($_POST['integrazo_fwcrm_form_error_notification_email'])) : '';
    $error_notification_subject = isset($_POST['integrazo_fwcrm_form_error_notification_subject']) ? sanitize_text_field(wp_unslash($_POST['integrazo_fwcrm_form_error_notification_subject'])) : '';

    // Update options
    update_option('integrazo_fwcrm_form_delete_data_on_uninstall', $delete_data_on_uninstall);
    update_option('integrazo_fwcrm_form_error_notification', $error_notification);
    update_option('integrazo_fwcrm_form_error_notification_email', $error_notification_email);
    update_option('integrazo_fwcrm_form_error_notification_subject', $error_notification_subject);
    // Set transient for success message
    set_transient('integrazo_fwcrm_form_settings_saved', true, 30); // Transient expires after 30 seconds

    // Redirect with success notice
    $redirect_url = add_query_arg(
        array(
            'page' => 'crm-integration-freshworks-any-form',
            'tab'  => 'settings',
        ),
        admin_url('admin.php')
    );

    wp_safe_redirect($redirect_url);
    exit;
}
add_action('admin_post_integrazo_fwcrm_form_delete_data_confirm', 'integrazo_fwcrm_form_settings');

function integrazo_fwcrm_form_process_request_key($key)
{
    try {
        // Validate and sanitize the input key
        $key = sanitize_text_field($key);

        // API endpoint for request processing
        $api_endpoint = 'https://www.zohoapis.in/creator/custom/plugcrux/request_key?publickey=j8eF7tDbf5VMNveC4yjzE5uDR';

        // Gather other details dynamically
        $current_site_url = esc_url(home_url()) ?: 'unknown';

        $plugin_file = WP_PLUGIN_DIR . '/crm-integration-freshworks-any-form/crm-integration-freshworks-any-form.php';

        // Check if the plugin file exists
        if (file_exists($plugin_file)) {
            $plugin_data = get_plugin_data($plugin_file);
            $plugin_version = isset($plugin_data['Version']) ? sanitize_text_field($plugin_data['Version']) : 'unknown';
            $plugin_name = isset($plugin_data['Name']) ? sanitize_text_field($plugin_data['Name']) : 'unknown';
        } else {
            // Set default values if the plugin file does not exist
            $plugin_version = 'unknown';
            $plugin_name = 'unknown';
        }

        // Safely fetch plugin details
        $php_version = phpversion() ?: 'unknown';
        $wp_version = get_bloginfo('version') ?: 'unknown';

        // Prepare the request body
        $body = [
            'request_key' => $key,
            'code' => "9019077656805",
            'otherDetails' => [
                'site_url' => $current_site_url,
                'plugin_version' => $plugin_version,
                'plugin_name' => $plugin_name,
                'php_version' => $php_version,
                'wp_version' => $wp_version
            ],
        ];

        // Convert body to JSON
        $body_json = wp_json_encode($body);

        // Make the API request
        $response = wp_remote_post($api_endpoint, [
            'body' => $body_json,
            'timeout' => 60,
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);

        // Check for errors
        if (is_wp_error($response)) {
            set_transient('integrazo_fwcrm_form_license_fail', "A network error occurred. Please check your connection and try again.", 300);
            wp_redirect(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=settings&menu=license'));
            exit;
        }

        // Decode the JSON response
        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);
        // Validate and handle the response
        if (is_array($response_data) && isset($response_data['code']) && $response_data['code'] === 3000) {
            if (!empty($response_data['result']['session_key'])) {
                // Save the session key in WordPress options
                update_option('integrazo_fwcrm_form_session_key', sanitize_text_field($response_data['result']['session_key']));
                update_option('integrazo_fwcrm_form_session_plan', sanitize_text_field($response_data['result']['plan']));
                // Save the request key in WordPress options
                update_option('integrazo_fwcrm_form_request_key', sanitize_text_field($key));

                // Set a transient to indicate success
                set_transient('integrazo_fwcrm_form_license_success', sanitize_text_field($response_data['result']['message']), 300);
            } else {
                // Set a transient to indicate failure
                $error_message = isset($response_data['result']['message']) ? $response_data['result']['message'] : 'Invalid license key.';
                set_transient('integrazo_fwcrm_form_license_fail', sanitize_text_field($error_message), 300);
            }
        } else {
            set_transient('integrazo_fwcrm_form_license_fail', 'Key verification unsuccessful. Please recheck and try again.', 300);
        }
    } catch (Throwable $e) {
        set_transient('integrazo_fwcrm_form_license_fail', "Something went wrong. Please try again later.", 300);
    } finally {
        // Redirect to the settings page
        wp_redirect(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=settings&menu=license'));
        exit;
    }
}

function integrazo_fwcrm_form_revoke_request_key($key)
{
    try {
        // Validate and sanitize the input key
        $key = sanitize_text_field($key);

        // API endpoint for request processing
        $api_endpoint = 'https://www.zohoapis.in/creator/custom/plugcrux/revoke_key?publickey=O7ykQPzAhHX4tdZ25MSqn8kZJ';

        // Gather other details dynamically
        $current_site_url = esc_url(home_url()) ?: 'unknown';

        $plugin_file = WP_PLUGIN_DIR . '/crm-integration-freshworks-any-form/crm-integration-freshworks-any-form.php';

        // Check if the plugin file exists
        if (file_exists($plugin_file)) {
            $plugin_data = get_plugin_data($plugin_file);
            $plugin_version = isset($plugin_data['Version']) ? sanitize_text_field($plugin_data['Version']) : 'unknown';
            $plugin_name = isset($plugin_data['Name']) ? sanitize_text_field($plugin_data['Name']) : 'unknown';
        } else {
            // Set default values if the plugin file does not exist
            $plugin_version = 'unknown';
            $plugin_name = 'unknown';
        }

        // Safely fetch plugin details
        $php_version = phpversion() ?: 'unknown';
        $wp_version = get_bloginfo('version') ?: 'unknown';

        // Prepare the request body
        $body = [
            'request_key' => $key,
            'code' => "9019077656805",
            'otherDetails' => [
                'site_url' => $current_site_url,
                'plugin_version' => $plugin_version,
                'plugin_name' => $plugin_name,
                'php_version' => $php_version,
                'wp_version' => $wp_version
            ],
        ];

        // Convert body to JSON
        $body_json = wp_json_encode($body);

        // Make the API request
        $response = wp_remote_post($api_endpoint, [
            'body' => $body_json,
            'timeout' => 60,
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);

        // Check for errors
        if (is_wp_error($response)) {
            set_transient('integrazo_fwcrm_form_license_fail', "A network error occurred. Please check your connection and try again.", 300);
            wp_redirect(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=settings&menu=license'));
            exit;
        }

        // Decode the JSON response
        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);
        // Validate and handle the response
        if (is_array($response_data) && isset($response_data['code']) && $response_data['code'] === 3000) {
            if (!empty($response_data['result']['session_key'])) {
                // Save the session key in WordPress options
                delete_option('integrazo_fwcrm_form_session_key');
                delete_option('integrazo_fwcrm_form_session_plan');
                // Save the request key in WordPress options
                delete_option('integrazo_fwcrm_form_request_key');

                // Set a transient to indicate success
                set_transient('integrazo_fwcrm_form_license_success', sanitize_text_field($response_data['result']['message']), 300);
            } else {
                // Set a transient to indicate failure
                $error_message = isset($response_data['result']['message']) ? $response_data['result']['message'] : 'Invalid license key.';
                set_transient('integrazo_fwcrm_form_license_fail', sanitize_text_field($error_message), 300);
            }
        } else {
            set_transient('integrazo_fwcrm_form_license_fail', 'Key verification unsuccessful. Please recheck and try again.', 300);
        }
    } catch (Throwable $e) {
        set_transient('integrazo_fwcrm_form_license_fail', "Something went wrong. Please try again later.", 300);
    } finally {
        // Redirect to the settings page
        wp_redirect(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=settings&menu=license'));
        exit;
    }
}

function integrazo_fwcrm_form_uninstall()
{
    try {
        // Validate the session key
        $session = integrazo_fwcrm_form_is_valid_key();
        if ($session) {
            // Retrieve and sanitize the session key
            $key = get_option('integrazo_fwcrm_form_request_key', '');
            $key = sanitize_text_field($key);

            if (!empty($key)) {
                // API endpoint for uninstall request
                $api_endpoint = 'https://www.zohoapis.in/creator/custom/plugcrux/uninstall?publickey=CvvaFnSr4y1664E1hxGBFhYKC';

                // Gather dynamic details
                $current_site_url = esc_url(home_url());
                $plugin_file = WP_PLUGIN_DIR . '/crm-integration-freshworks-any-form/crm-integration-freshworks-any-form.php';

                // Initialize default values
                $plugin_version = 'unknown';
                $plugin_name = 'unknown';

                // Check if the plugin file exists and fetch plugin details
                if (file_exists($plugin_file)) {
                    // Use `get_plugin_data` to retrieve plugin details
                    $plugin_data = get_plugin_data($plugin_file, false, false);

                    $plugin_version = isset($plugin_data['Version']) ? sanitize_text_field($plugin_data['Version']) : 'unknown';
                    $plugin_name = isset($plugin_data['Name']) ? sanitize_text_field($plugin_data['Name']) : 'unknown';
                }

                // Fetch server and WordPress details safely
                $php_version = sanitize_text_field(phpversion() ?: 'unknown');
                $wp_version = sanitize_text_field(get_bloginfo('version') ?: 'unknown');

                // Prepare request body
                $body = [
                    'request_key' => $key,
                    'code' => "9019077656805",
                    'otherDetails' => [
                        'site_url' => $current_site_url,
                        'plugin_version' => $plugin_version,
                        'plugin_name' => $plugin_name,
                        'php_version' => $php_version,
                        'wp_version' => $wp_version,
                    ],
                ];

                // Convert request body to JSON
                $body_json = wp_json_encode($body);

                // Make the API request
                wp_remote_post($api_endpoint, [
                    'body' => $body_json,
                    'timeout' => 60,
                    'headers' => [
                        'Content-Type' => 'application/json',
                    ],
                ]);

                // Clean up options after uninstall
                delete_option('integrazo_fwcrm_form_session_key');
                delete_option('integrazo_fwcrm_form_session_plan');
                delete_option('integrazo_fwcrm_form_request_key');
            }
        }
    } catch (Throwable $e) {
        // Silently catch exceptions without logging
    }
}


function integrazo_fwcrm_form_is_valid_key()
{
    // Retrieve session data from options
    $session = get_option('integrazo_fwcrm_form_session_key', null);
    if (!empty($session)) {
        // Decode the session key
        $decoded_session = base64_decode($session, true);

        // Ensure the session key was successfully decoded and is numeric
        if ($decoded_session !== false && is_numeric($decoded_session)) {
            $current_time = round(microtime(true) * 1000); // Current time in milliseconds

            // Check if the decoded session key is greater than the current time
            if ((is_numeric($decoded_session) && (int)$decoded_session > $current_time) || ($session === "MTExMTExMTExMTExMQ==")) {
                return true; // License is valid
            }
        }
    }

    // If the session is not valid, return false
    return false;
}


/**
 * Sends an email with error log details fetched by log ID.
 *
 * @param int $log_id The ID of the error log to fetch and send.
 */
function integrazo_fwcrm_send_error_log_details_email_by_log_id($log_id)
{
    try {
        $send_mail_status = get_option('integrazo_fwcrm_form_error_notification', '');
        if ($send_mail_status === "yes") {
            $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            // Fetch error log details using the log ID
            $error_log_details = $integrazo_fwcrm_form_errorLogDBInstance->get_error_log($log_id);

            // Extract relevant details
            $integration_name = $integrazo_fwcrm_form_fieldMappingDBInstance->get_integration_name($error_log_details->integration_id ?? '');
            $error_type = $error_log_details->error_type ?? 'N/A';
            $retry_count = $error_log_details->retry_count ?? 'N/A';
            $created_at = $error_log_details->created_at ?? 'N/A';
            $form_data = $error_log_details->form_data ?? array();

            // Fetch recipient email and subject from options
            $recipient_email = get_option('integrazo_fwcrm_form_error_notification_email', '');
            $email_subject = get_option('integrazo_fwcrm_form_error_notification_subject', 'Error Log Details');

            if (empty($recipient_email)) {
                return; // Skip if recipient email is not set
            }

            // Prepare the email content
            $content = '<html><body>';
            $content .= '<h3>Error Log Details</h3>';
            $content .= '<table style="border-collapse: collapse; width: 100%; border: 1px solid #ddd;">';
            $content .= '<tr><th style="padding: 8px; text-align: left; background: #f4f4f4;">Integration Name</th><td style="padding: 8px;">' . esc_html($integration_name) . '</td></tr>';
            $content .= '<tr><th style="padding: 8px; text-align: left; background: #f4f4f4;">Error Type</th><td style="padding: 8px;">' . esc_html($error_type) . '</td></tr>';
            $content .= '<tr><th style="padding: 8px; text-align: left; background: #f4f4f4;">Created At</th><td style="padding: 8px;">' . esc_html($created_at) . '</td></tr>';
            $content .= '</table>';

            $content .= '<h4>Form Data</h4>';
            $content .= '<table style="border-collapse: collapse; width: 100%; border: 1px solid #ddd;">';
            if (!empty($form_data)) {
                foreach ($form_data as $key => $value) {
                    $content .= '<tr>';
                    $content .= '<th style="padding: 8px; text-align: left; background: #f4f4f4;">' . esc_html($key) . '</th>';
                    $content .= '<td style="padding: 8px;">' . esc_html($value) . '</td>';
                    $content .= '</tr>';
                }
            } else {
                $content .= '<tr><td colspan="2" style="padding: 8px; text-align: center;">No form data available</td></tr>';
            }
            $content .= '</table>';

            $content .= '<p>Thank you,<br><strong>Integrazo Plugin Team</strong></p>';
            $content .= '</body></html>';

            // Set email headers
            $headers = array(
                'Content-Type: text/html; charset=UTF-8'
            );

            // Send the email
            wp_mail($recipient_email, $email_subject, $content, $headers);
        }
    } catch (Throwable $e) {
        // Log the exception for debugging
    }
}
