<?php

function IAFWZCAI_Error_Log_delete_action()
{
    $IAFWZCAI_Error_LogDBInstance = new IAFWZCAI_Error_Log();

    // Check if the delete log ID parameter is provided
    if (isset($_GET['de_log_id']) && isset($_GET['page']) && $_GET['page'] === 'integrate-with-zoho-campaigns') {
        $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.', 'integrate-with-zoho-campaigns'));
        }
        // Call the delete function
        $result = $IAFWZCAI_Error_LogDBInstance->delete_error_log($log_id);

        set_transient('iafwzcai_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', 'IAFWZCAI_Error_Log_delete_action');


function IAFWZCAI_Error_Log_delete_all_action()
{
    $IAFWZCAI_Error_LogDBInstance = new IAFWZCAI_Error_Log();

    // Check if the delete action is triggered.
    if (
        isset($_POST['bulk_delete_all'], $_GET['page']) && $_POST['bulk_delete_all'] === 'delete_all' && $_GET['page'] === 'integrate-with-zoho-campaigns' ||
        isset($_POST['bulk_delete_all_success'], $_GET['page']) && $_POST['bulk_delete_all_success'] === 'delete_all_success' && $_GET['page'] === 'integrate-with-zoho-campaigns'
    ) {
        // Verify the nonce.
        if (
            !isset($_POST['iafwzcai_error_log_form_action_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['iafwzcai_error_log_form_action_nonce'])), 'iafwzcai_error_log_form_action')
        ) {
            wp_die(esc_html__('Security check failed.', 'integrate-with-zoho-campaigns'));
        }

        // Determine which type of logs to delete
        if (isset($_POST['bulk_delete_all']) && $_POST['bulk_delete_all'] === 'delete_all') {
            $result = $IAFWZCAI_Error_LogDBInstance->delete_all_error_logs();
            $message = 'All error logs deleted successfully!';
        } elseif (isset($_POST['bulk_delete_all_success']) && $_POST['bulk_delete_all_success'] === 'delete_all_success') {
            $result = $IAFWZCAI_Error_LogDBInstance->delete_all_success_logs(); // You need to implement this function in your class
            $message = 'All successfully added records deleted successfully!';
        }

        // Set a success message if deletion was successful.
        if ($result) {
            set_transient('iafwzcai_error_log_success', $message, 300);
        }

        // Redirect to the current page after deletion.
        wp_safe_redirect(remove_query_arg(['bulk_delete_all', 'bulk_delete_all_success', 'iafwzcai_error_log_form_action_nonce']));
        exit;
    }
}

add_action('admin_init', 'IAFWZCAI_Error_Log_delete_all_action');




function IAFWZCAI_Error_Log_show_action()
{
    // Check the nonce for security
    if (
        !isset($_POST['security']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'iafwzcai_error_log_nonce')
    ) {
        wp_send_json_error(['message' => __('Invalid security token.', 'integrate-with-zoho-campaigns')]);
    }

    // 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.', 'integrate-with-zoho-campaigns')]);
    }

    // Fetch error log details using the custom database handler
    $IAFWZCAI_Error_LogDBInstance = new IAFWZCAI_Error_Log();
    $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();
    if (!isset($IAFWZCAI_Error_LogDBInstance) || !method_exists($IAFWZCAI_Error_LogDBInstance, 'get_error_log')) {
        wp_send_json_error(['message' => __('Database handler is not available.', 'integrate-with-zoho-campaigns')]);
    }

    $error_log_details = $IAFWZCAI_Error_LogDBInstance->get_error_log($log_id);
    $integration_name = $IAFWZCAI_Field_MappingDBInstance->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.', 'integrate-with-zoho-campaigns')]);
    }

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


// Reusable function for resync logic
function iafwzcai_process_resync($log_id)
{
    $iafwzcai_errorLogDBInstance = new IAFWZCAI_Error_Log();
    $iafwzcai_formSubmit = new iafwzcai_FormSubmit();
    $iafwzcai_fieldMappingDBInstance = new IAFWZCAI_Field_Mapping();

    $log_id = intval($log_id);

    // Retrieve error log details
    $error_log_details = $iafwzcai_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 = $iafwzcai_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 = $iafwzcai_formSubmit->process_form_submission(
        $error_log_details->form_data,
        $error_log_details->crm_data,
        $field_mapping_details,
        'resync'
    );
    // Handle failed resync
    $error_details = $response['body'] ?? 'UNKNOWN_ERROR';
    $code = $response['category'] ?? 'UNKNOWN_ERROR';
    $crm_record_id = $response['id'] ?? null;
    // Update error log with retry count increment
    $iafwzcai_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
    );
    if ($code != "SUCCESS") {
        return ['success' => "false", 'message' => 'Resync failed. Please check the detailed log for more information.'];
    }

    //$iafwzcai_errorLogDBInstance->delete_error_log($log_id);
    return ['success' => "true", 'message' => 'Log resynced successfully.'];
}

// Hook for single resync
function iafwzcai_errorlog_resync_action()
{
    if (
        isset($_GET['log_id'], $_GET['_wpnonce'], $_GET['action'], $_GET['page']) &&
        $_GET['action'] === 'iafwzcai_resync' &&
        $_GET['page'] === 'integrate-with-zoho-campaigns'
    ) {
        $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.', 'integrate-with-zoho-campaigns'));
        }

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

        if ($result['success'] === "true") {
            set_transient('iafwzcai_error_log_success', $result['message'], 300);
        } else {
            set_transient('iafwzcai_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', 'iafwzcai_errorlog_resync_action');

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

    foreach ($log_ids as $log_id) {
        $result = iafwzcai_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('iafwzcai_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(
            'iafwzcai_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('iafwzcai_error_log_fail', 'Failed to resync all selected logs. Please check the detailed log for more information.', 300);
    }
}
