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

function IAFWZC_Error_Log_delete_action()
{
    if (!current_user_can('manage_options')) {
        return;
    }

    $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();

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

        set_transient('iafwzc_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', 'IAFWZC_Error_Log_delete_action');


function IAFWZC_Error_Log_delete_all_action()
{
    if (!current_user_can('manage_options')) {
        return;
    }

    $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();
    // Check if the "Delete All" button action is triggered.
    if (isset($_POST['bulk_delete_all'], $_GET['page']) && $_POST['bulk_delete_all'] === 'delete_all' && $_GET['page'] === 'integrate-any-form-with-zoho-crm') {
        // Verify the nonce.
        if (
            !isset($_POST['iafwzc_error_log_form_action_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['iafwzc_error_log_form_action_nonce'])), 'iafwzc_error_log_form_action')
        ) {
            wp_die(esc_html__('Security check failed.', 'integrate-any-form-with-zoho-crm'));
        }

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

        if ($result) {
            set_transient('iafwzc_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', 'iafwzc_error_log_form_action_nonce']));
        exit;
    }
}

add_action('admin_init', 'IAFWZC_Error_Log_delete_all_action');



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

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Insufficient permissions.', 'integrate-any-form-with-zoho-crm')]);
    }

    // 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-any-form-with-zoho-crm')]);
    }

    // Fetch error log details using the custom database handler
    $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();
    $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
    if (!isset($IAFWZC_Error_LogDBInstance) || !method_exists($IAFWZC_Error_LogDBInstance, 'get_error_log')) {
        wp_send_json_error(['message' => __('Database handler is not available.', 'integrate-any-form-with-zoho-crm')]);
    }

    $error_log_details = $IAFWZC_Error_LogDBInstance->get_error_log($log_id);
    $integration_name = $IAFWZC_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-any-form-with-zoho-crm')]);
    }

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


// Reusable function for resync logic
function iafwzc_process_resync($log_id)
{
    $iafwzc_errorLogDBInstance = new IAFWZC_Error_Log();
    $iafwzc_formSubmit = new iafwzc_FormSubmit();
    $iafwzc_fieldMappingDBInstance = new IAFWZC_Field_Mapping();

    $log_id = intval($log_id);

    // Retrieve error log details
    $error_log_details = $iafwzc_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 = $iafwzc_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 = $iafwzc_formSubmit->process_form_submission(
        $error_log_details->form_data,
        $error_log_details->crm_data,
        $field_mapping_details
    );

    // Handle failed resync
    if (isset($response['data'][0]['status']) && $response['data'][0]['status'] === 'error') {
        $error_details = $response['data'][0];
        $code = $error_details['code'] ?? '';
        $crm_record_id = $error_details['details']['id'] ?? null;

        // Update error log with retry count increment
        $iafwzc_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.'];
    }
    $iafwzc_errorLogDBInstance->delete_error_log($log_id);
    return ['success' => "true", 'message' => 'Log resynced successfully.'];
}

// Hook for single resync
function iafwzc_errorlog_resync_action()
{
    if (!current_user_can('manage_options')) {
        return;
    }

    if (isset($_GET['log_id'], $_GET['_wpnonce'], $_GET['action']) && $_GET['action'] === 'resync') {
        $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-any-form-with-zoho-crm'));
        }

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

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

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

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