<?php

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


// Register the action hook
add_action('admin_init', 'integrazo_wz_errorlog_resync_action');

function integrazo_wz_errorlog_resync_action()
{
    if (
        isset($_GET['action'], $_GET['page'], $_GET['log_id'], $_GET['_wpnonce']) &&
        $_GET['action'] === 'integrazo_wz_resync' &&
        $_GET['page'] === 'integrazo-integration-for-zoho-apps'
    ) {
        $log_id = absint($_GET['log_id']);

        // Verify the nonce
        if (
            ! isset($_GET['_wpnonce']) ||
            ! wp_verify_nonce(
                sanitize_text_field(wp_unslash($_GET['_wpnonce'])),
                'resync_error_log_' . $log_id
            )
        ) {
            wp_die(esc_html__('Security check failed.', 'integrazo-integration-for-zoho-apps'));
        }

        // Retrieve error log details
        $logs_model = new INTEGRAZO_WZ_Logs_Model();
        $log_details = $logs_model->get_error_log($log_id);

        // Retrieve field mapping details
        $integration_model = new INTEGRAZO_WZ_Integration_Model();
        $integration_model->block_field_mapping();
        $integration_details = $integration_model->get_integration_by_id($log_details->integration_id);
        // Perform resync
        $status = INTEGRAZO_WZ_Form_Hooks::resync_process_submission($integration_details, $log_details);
        if (is_array($status)) {
            if ($status['success']) {
                set_transient('integrazo_wz_success', $status['message'], 30); // 30 seconds expiry
            } else {
                set_transient('integrazo_wz_fail', $status['message'], 30);
            }
        }

        // Redirect to remove sensitive query args
        wp_safe_redirect(remove_query_arg(['log_id', '_wpnonce', 'action']));
        exit;
    }
}

function integrazo_wz_bulk_resync(array $log_ids)
{
    $success_count = 0;
    $total_count = count($log_ids);

    $logs_model = new INTEGRAZO_WZ_Logs_Model();
    $integration_model = new INTEGRAZO_WZ_Integration_Model();
    $integration_model->block_field_mapping();

    foreach ($log_ids as $log_id) {
        // Get log details
        $log_details = $logs_model->get_error_log($log_id);
        // Get integration details for this log
        $integration_details = $integration_model->get_integration_by_id($log_details->integration_id);

        // Perform resync
        $status = INTEGRAZO_WZ_Form_Hooks::resync_process_submission($integration_details, $log_details);

        if (is_array($status) && !empty($status['success'])) {
            $success_count++;
        }
    }

    // Set appropriate transient messages based on the result
    if ($success_count === $total_count) {
        set_transient('integrazo_wz_success', 'Selected logs resynced successfully.', 300);
    } elseif ($success_count > 0) {
        $failed_count = $total_count - $success_count;
        set_transient(
            'integrazo_wz_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 {
        set_transient('integrazo_wz_fail', 'Failed to resync all selected logs. Please check the detailed log for more information.', 300);
    }
}



function INTEGRAZO_WZ_Error_Log_show_action()
{
    // Check the nonce for security
    if (
        !isset($_POST['security']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'integrazo_wz_error_log_nonce')
    ) {
        wp_send_json_error(['message' => __('Invalid security token.', 'integrazo-integration-for-zoho-apps')]);
    }
    if (! current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Insufficient permissions.', 'integrazo-integration-for-zoho-apps')]);
    }
    // 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.', 'integrazo-integration-for-zoho-apps')]);
    }

    // Fetch error log details
    $logs_model = new INTEGRAZO_WZ_Logs_Model();
    $integration_model = new INTEGRAZO_WZ_Integration_Model();

    $log_details = $logs_model->get_error_log($log_id);
    if (!$log_details) {
        wp_send_json_error(['message' => __('Log not found.', 'integrazo-integration-for-zoho-apps')]);
    }

    // Unserialize and enrich the log
    $log_details->submitted_data = maybe_unserialize($log_details->submitted_data);
    $log_details->response_data  = maybe_unserialize($log_details->response_data);
    $log_details->integration_name = $integration_model->get_integration_name($log_details->integration_id);

    // ✅ Return the response
    wp_send_json_success(['details' => $log_details]);
}
add_action('wp_ajax_INTEGRAZO_WZ_Error_Log_show_action', 'INTEGRAZO_WZ_Error_Log_show_action');
