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

function integrazo_fwcrm_form_errorlog_delete_action()
{
    $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
    // Check if the delete log ID parameter is provided
    if (isset($_GET['de_log_id']) && isset($_GET['page']) && $_GET['page'] === 'crm-integration-freshworks-any-form') {

        $log_id = intval($_GET['de_log_id']);
        $nonce  = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';

        // Verify nonce for delete action
        if (!wp_verify_nonce($nonce, 'delete_error_log_' . $log_id)) {
            wp_die(esc_html__('Security check failed.', 'crm-integration-freshworks-any-form'));
        }

        // Call the delete function
        $result = $integrazo_fwcrm_form_errorLogDBInstance->delete_error_log($log_id);

        set_transient('integrazo_fwcrm_form_error_log_success', "Log deleted successfully!", 300);

        // Redirect to the current page after deletion, with 'de_log_id' and '_wpnonce' removed
        wp_safe_redirect(remove_query_arg(['de_log_id', '_wpnonce']));
        exit;
    }
}
add_action('admin_init', 'integrazo_fwcrm_form_errorlog_delete_action');


function integrazo_fwcrm_form_errorlog_delete_all_action()
{
    $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
    // Check if the "Delete All" button action is triggered.
    if (isset($_POST['bulk_delete_all']) && $_POST['bulk_delete_all'] === 'delete_all' && isset($_GET['page']) && $_GET['page'] === 'crm-integration-freshworks-any-form') {
        // Verify the nonce.
        if (
            !isset($_POST['integrazo_fwcrm_form_error_log_form_action_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_fwcrm_form_error_log_form_action_nonce'])), 'integrazo_fwcrm_form_error_log_form_action')
        ) {
            wp_die(esc_html__('Security check failed.', 'crm-integration-freshworks-any-form'));
        }

        // Call the function to delete all error logs.
        $result = $integrazo_fwcrm_form_errorLogDBInstance->delete_all_error_logs();

        if ($result) {
            set_transient('integrazo_fwcrm_form_error_log_success', 'All error logs deleted successfully!', 300);
        }
        // Redirect to the current page after deletion.
        wp_safe_redirect(remove_query_arg(['bulk_delete_all', 'integrazo_fwcrm_form_error_log_form_action_nonce']));
        exit;
    }
}

add_action('admin_init', 'integrazo_fwcrm_form_errorlog_delete_all_action');




// Reusable function for resync logic
function integrazo_fwcrm_form_process_resync($log_id)
{
    $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
    $integrazo_fwcrm_form_formSubmit = new integrazo_fwcrm_form_FormSubmit();
    $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
    $integrazo_fwcrm_form_api_Instance = new integrazo_fwcrm_form_API();
    $log_id = intval($log_id);

    // Retrieve error log details
    $error_log_details = $integrazo_fwcrm_form_errorLogDBInstance->get_error_log($log_id);
    if (!$error_log_details) {
        return ['success' => "false", 'message' => 'Error log not found.'];
    }

    // Retrieve field mapping details
    $field_mapping_details = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping($error_log_details->integration_id);
    if (!$field_mapping_details) {
        return ['success' => "false", 'message' => 'Field mapping details not found.'];
    }

    // Perform form submission processing
    $response = $integrazo_fwcrm_form_formSubmit->process_form_submission(
        $error_log_details->form_data,
        $error_log_details->crm_data,
        $field_mapping_details
    );
    // Retrieve the module action
    $module_name = $field_mapping_details->module_name ?? '';
    $module_action = $integrazo_fwcrm_form_api_Instance->getModuleAction($module_name);
    // Handle failed resync
    if (!isset($response[$module_action]) || !isset($response[$module_action]['id'])) {
        $code = $response['code'] ?? 'API_RESPONSE_ISSUE';
        $crm_record_id = $response[$module_action]['id'] ?? '';

        // Update error log with retry count increment
        $integrazo_fwcrm_form_errorLogDBInstance->update_error_log(
            $log_id,
            $code,
            $error_log_details->form_data,
            $error_log_details->crm_data,
            $response,
            $crm_record_id,
            $error_log_details->retry_count
        );
        return ['success' => "false", 'message' => 'Resync failed. Please check the detailed log for more information.'];
    }
    $integrazo_fwcrm_form_errorLogDBInstance->delete_error_log($log_id);
    return ['success' => "true", 'message' => 'Log resynced successfully.'];
}

// Hook for single resync
function integrazo_fwcrm_form_errorlog_resync_action()
{
    if (isset($_GET['log_id'], $_GET['_wpnonce'], $_GET['action'], $_GET['page']) && $_GET['action'] === 'resync' && $_GET['page'] === 'crm-integration-freshworks-any-form') {
        $log_id = intval($_GET['log_id']);
        $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce']));

        // Verify nonce for resync action
        if (!wp_verify_nonce($nonce, 'resync_error_log_' . $log_id)) {
            wp_die(esc_html__('Security check failed.', 'crm-integration-freshworks-any-form'));
        }

        // Call the reusable function
        $result = integrazo_fwcrm_form_process_resync($log_id);
        // Set transient message

        if ($result['success'] === "true") {
            set_transient('integrazo_fwcrm_form_error_log_success', $result['message'], 300);
        } else {
            set_transient('integrazo_fwcrm_form_error_log_fail', $result['message'], 300);
        }


        // Redirect to the current page after resync, removing sensitive query parameters
        wp_safe_redirect(remove_query_arg(['log_id', '_wpnonce', 'action']));
        exit;
    }
}
add_action('admin_init', 'integrazo_fwcrm_form_errorlog_resync_action');

// Example usage for bulk resync
function integrazo_fwcrm_form_bulk_resync(array $log_ids)
{
    $success_count = 0;
    $total_count = count($log_ids);

    foreach ($log_ids as $log_id) {
        $result = integrazo_fwcrm_form_process_resync($log_id);
        if ($result['success'] === "true") {
            $success_count++;
        }
    }

    // Check the results and set appropriate transient messages.
    if ($success_count === $total_count) {
        // All logs resynced successfully.
        set_transient('integrazo_fwcrm_form_error_log_success', 'Selected logs resynced successfully.', 300);
    } elseif ($success_count > 0) {
        // Some logs resynced, others failed.
        $failed_count = $total_count - $success_count;
        set_transient(
            'integrazo_fwcrm_form_error_log_fail',
            "Out of $total_count selected logs, $success_count resynced successfully and $failed_count failed. Please check the detailed log for more information.",
            300
        );
    } else {
        // All logs failed to resync.
        set_transient('integrazo_fwcrm_form_error_log_fail', 'Failed to resync all selected logs. Please check the detailed log for more information.', 300);
    }
}




function integrazo_fwcrm_form_errorlog_show_action()
{
    // Check the nonce for security
    if (
        !isset($_POST['security']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'integrazo_fwcrm_form_error_log_nonce')
    ) {
        wp_send_json_error(['message' => esc_html__('Invalid security token.', 'crm-integration-freshworks-any-form')]);
    }

    // Validate and sanitize the log ID
    $log_id = isset($_POST['log_id']) ? intval($_POST['log_id']) : 0;
    if (!$log_id) {
        wp_send_json_error(['message' => __('Invalid log ID.', 'crm-integration-freshworks-any-form')]);
    }

    // Fetch error log details using the custom database handler
    $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
    $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
    if (!isset($integrazo_fwcrm_form_errorLogDBInstance) || !method_exists($integrazo_fwcrm_form_errorLogDBInstance, 'get_error_log')) {
        wp_send_json_error(['message' => __('Database handler is not available.', 'crm-integration-freshworks-any-form')]);
    }

    $error_log_details = $integrazo_fwcrm_form_errorLogDBInstance->get_error_log($log_id);
    $integration_name = $integrazo_fwcrm_form_fieldMappingDBInstance->get_integration_name($error_log_details->integration_id);

    // Add the integration_name property to the error_log_details object
    if ($error_log_details) {
        $error_log_details->integration_name = $integration_name;
    }

    if (!$error_log_details) {
        wp_send_json_error(['message' => __('Error log not found.', 'crm-integration-freshworks-any-form')]);
    }

    // Send the log details as a success response
    wp_send_json_success(['details' => $error_log_details]);
}
add_action('wp_ajax_integrazo_fwcrm_form_errorlog_show_action', 'integrazo_fwcrm_form_errorlog_show_action');
