<?php

// Exit if accessed directly to ensure security.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handles saving settings for the plugin.
 */
function iafwzc_settings()
{

    // Verify nonce for security
    if (
        ! isset($_POST['iafwzc_settings_data_action_nonce']) ||
        ! wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['iafwzc_settings_data_action_nonce'])),
            'iafwzc_settings_data_action'
        )
    ) {
        wp_die(esc_html__('Security check failed.', 'integrate-any-form-with-zoho-crm'));
    }

    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrate-any-form-with-zoho-crm'));
    }

    // Sanitize and save the checkbox values and other inputs
    $delete_data_on_uninstall = (
        isset($_POST['iafwzc_delete_data_on_uninstall']) &&
        'yes' === sanitize_text_field(wp_unslash($_POST['iafwzc_delete_data_on_uninstall']))
    ) ? 'yes' : 'no';

    $error_notification = (
        isset($_POST['iafwzc_error_notification']) &&
        'yes' === sanitize_text_field(wp_unslash($_POST['iafwzc_error_notification']))
    ) ? 'yes' : 'no';

    $error_notification_email   = isset($_POST['iafwzc_error_notification_email'])
        ? sanitize_text_field(wp_unslash($_POST['iafwzc_error_notification_email']))
        : '';

    $error_notification_subject = isset($_POST['iafwzc_error_notification_subject'])
        ? sanitize_text_field(wp_unslash($_POST['iafwzc_error_notification_subject']))
        : '';

    // NEW: Deactivation notification checkbox
    $deactivate_notification = (
        isset($_POST['iafwzc_deactivate_notification']) &&
        'yes' === sanitize_text_field(wp_unslash($_POST['iafwzc_deactivate_notification']))
    ) ? 'yes' : 'no';

    // NEW: Deactivation notification email(s)
    $deactivate_notification_email = isset($_POST['iafwzc_deactivate_notification_email'])
        ? sanitize_text_field(wp_unslash($_POST['iafwzc_deactivate_notification_email']))
        : '';

    // Update options
    update_option('iafwzc_delete_data_on_uninstall', $delete_data_on_uninstall);
    update_option('iafwzc_error_notification', $error_notification);
    update_option('iafwzc_error_notification_email', $error_notification_email);
    update_option('iafwzc_error_notification_subject', $error_notification_subject);

    // NEW: update deactivate notification options
    update_option('iafwzc_deactivate_notification', $deactivate_notification);
    update_option('iafwzc_deactivate_notification_email', $deactivate_notification_email);

    // Set transient for success message
    set_transient('iafwzc_settings_saved', true, 30); // Transient expires after 30 seconds

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

    wp_safe_redirect($redirect_url);
    exit;
}
add_action('admin_post_iafwzc_delete_data_confirm', 'iafwzc_settings');

/**
 * Send email alert when plugin is deactivated.
 */
function iafwzc_send_deactivation_alert()
{

    // Check if deactivation alert is enabled in settings.
    $enabled = get_option('iafwzc_deactivate_notification', 'no');
    if ('yes' !== $enabled) {
        return;
    }

    // Get configured email addresses.
    $emails = get_option('iafwzc_deactivate_notification_email', '');
    if (empty($emails)) {
        return;
    }

    $email_list = array_filter(array_map('trim', explode(',', $emails)));
    if (empty($email_list)) {
        return;
    }

    $site_url = home_url();

    // Simple common subject (no site name).
    $subject = __('Plugin Deactivated – Action Required', 'integrate-any-form-with-zoho-crm');

    // HTML email body.
    $message  = '<html><body style="font-family: Arial, sans-serif; font-size:14px; color:#333;">';

    $message .= '<p style="margin:0 0 15px 0;">Hello,</p>';

    $message .= '<p style="margin:0 0 15px 0;">';
    $message .= 'The plugin <strong>Integration for Zoho CRM and Zoho Bigin</strong> has been deactivated on your website ';
    $message .= '<a href="' . esc_url($site_url) . '" target="_blank" style="color:#2271b1;text-decoration:none;">' . esc_html($site_url) . '</a>.';
    $message .= '</p>';

    $message .= '<p style="margin:0 0 8px 0;"><strong>What this means:</strong></p>';
    $message .= '<ul style="margin:0 0 15px 20px; padding:0;">';
    $message .= '<li style="margin-bottom:4px;">All form integrations with Zoho CRM and Zoho Bigin will stop working.</li>';
    $message .= '<li style="margin-bottom:4px;">Even if visitors submit forms, data will no longer be sent to Zoho CRM or Zoho Bigin.</li>';
    $message .= '<li style="margin-bottom:4px;">If you are using the licensed (premium) version, the license will not be used until the plugin is activated again.</li>';
    $message .= '</ul>';

    $message .= '<p style="margin:0 0 8px 0;"><strong>What you should do next:</strong></p>';
    $message .= '<ol style="margin:0 0 15px 20px; padding:0;">';
    $message .= '<li style="margin-bottom:4px;">Activate the plugin again from the Plugins page.</li>';
    $message .= '<li style="margin-bottom:4px;">Open the <strong>Setup</strong> page in the plugin.</li>';
    $message .= '<li style="margin-bottom:4px;">Re-activate or confirm that your license key is active.</li>';
    $message .= '<li style="margin-bottom:4px;">Manually enable all required integrations again so data starts syncing to Zoho CRM and Zoho Bigin.</li>';
    $message .= '</ol>';

    $message .= '<p style="margin:0 0 15px 0;">';
    $message .= 'If this deactivation was not expected, please review who has access to your WordPress admin and your plugins.';
    $message .= '</p>';

    // End with "Thank you" only.
    $message .= '<p style="margin:0;">Thank you.</p>';

    $message .= '</body></html>';

    // Headers for HTML email.
    $headers = array( 'Content-Type: text/html; charset=UTF-8' );

    foreach ($email_list as $email) {
        wp_mail($email, $subject, $message, $headers);
    }
}

function iafwzc_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 . '/integrate-any-form-with-zoho-crm/integrate-any-form-with-zoho-crm.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' => "9015035429093",
            '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('iafwzc_license_fail', "A network error occurred. Please check your connection and try again.", 300);
            wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&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('iafwzc_session_key', sanitize_text_field($response_data['result']['session_key']));
                update_option('iafwzc_session_plan', sanitize_text_field($response_data['result']['plan']));
                // Save the request key in WordPress options
                update_option('iafwzc_request_key', sanitize_text_field($key));

                // Set a transient to indicate success
                set_transient('iafwzc_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('iafwzc_license_fail', sanitize_text_field($error_message), 300);
            }
        } else {
            set_transient('iafwzc_license_fail', 'Key verification unsuccessful. Please recheck and try again.', 300);
        }
    } catch (Throwable $e) {
        set_transient('iafwzc_license_fail', "Something went wrong. Please try again later.", 300);
    } finally {
        // Redirect to the settings page
        wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&tab=settings&menu=license'));
        exit;
    }
}

function iafwzc_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 . '/integrate-any-form-with-zoho-crm/integrate-any-form-with-zoho-crm.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' => "9015035429093",
            '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('iafwzc_license_fail', "A network error occurred. Please check your connection and try again.", 300);
            wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&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('iafwzc_session_key');
                delete_option('iafwzc_session_plan');
                // Save the request key in WordPress options
                delete_option('iafwzc_request_key');

                // Set a transient to indicate success
                set_transient('iafwzc_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('iafwzc_license_fail', sanitize_text_field($error_message), 300);
            }
        } else {
            set_transient('iafwzc_license_fail', 'Key verification unsuccessful. Please recheck and try again.', 300);
        }
    } catch (Throwable $e) {
        set_transient('iafwzc_license_fail', "Something went wrong. Please try again later.", 300);
    } finally {
        // Redirect to the settings page
        wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&tab=settings&menu=license'));
        exit;
    }
}

function iafwzc_uninstall()
{
    try {
        // Validate the session key
        $session = iafwzc_is_valid_key();
        if ($session) {
            // Retrieve and sanitize the session key
            $key = get_option('iafwzc_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 . '/integrate-any-form-with-zoho-crm/integrate-any-form-with-zoho-crm.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' => "9015035429093",
                    '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('iafwzc_session_key');
                delete_option('iafwzc_session_plan');
                delete_option('iafwzc_request_key');
            }
        }
    } catch (Throwable $e) {
        // Silently catch exceptions without logging
    }
}


function iafwzc_is_valid_key()
{
    // Retrieve session data from options
    $session = get_option('iafwzc_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)) {
                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 iafwzc_send_error_log_details_email_by_log_id($log_id)
{
    try {
        $send_mail_status = get_option('iafwzc_error_notification', '');
        if ($send_mail_status === "yes") {
            $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();

            // Fetch error log details using the log ID
            $error_log_details = $IAFWZC_Error_LogDBInstance->get_error_log($log_id);

            // Extract relevant details
            $integration_name = $IAFWZC_Field_MappingDBInstance->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();
            $crm_data = $error_log_details->crm_data ?? array();
            $api_response = $error_log_details->api_response ?? array();

            // Fetch recipient email and subject from options
            $recipient_email = get_option('iafwzc_error_notification_email', '');
            $email_subject = get_option('iafwzc_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;">Retry Count</th><td style="padding: 8px;">' . esc_html($retry_count) . '</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 .= '<h4>API Response</h4>';
            $content .= '<pre style="background: #f4f4f4; padding: 8px; border: 1px solid #ddd; overflow-x: auto;">';
            $content .= esc_html(wp_json_encode($api_response, JSON_PRETTY_PRINT));
            $content .= '</pre>';


            // 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
    }
}
