<?php

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


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

function integrazo_wczo_errorlog_resync_action()
{
    if (
        isset($_GET['action'], $_GET['page'], $_GET['log_id'], $_GET['_wpnonce']) &&
        $_GET['action'] === 'integrazo_wczo_resync' &&
        $_GET['page'] === 'integrazo-wc-zoho-integration'
    ) {
        $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-wc-zoho-integration'));
        }

        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
        }

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

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

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

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

    $logs_model = new INTEGRAZO_WCZO_Logs_Model();
    $integration_model = new INTEGRAZO_WCZO_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_WCZO_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_wczo_success', 'Selected logs resynced successfully.', 300);
    } elseif ($success_count > 0) {
        $failed_count = $total_count - $success_count;
        set_transient(
            'integrazo_wczo_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_wczo_fail', 'Failed to resync all selected logs. Please check the detailed log for more information.', 300);
    }
}



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

    // Fetch error log details
    $logs_model = new INTEGRAZO_WCZO_Logs_Model();
    $integration_model = new INTEGRAZO_WCZO_Integration_Model();

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

    // 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_WCZO_Error_Log_show_action', 'INTEGRAZO_WCZO_Error_Log_show_action');
