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

function IAFWZDESK_Error_Log_delete_action()
{
    $IAFWZDESK_Error_LogDBInstance = new IAFWZDESK_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-desk') {
        $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-desk'));
        }
        // Call the delete function
        $result = $IAFWZDESK_Error_LogDBInstance->delete_error_log($log_id);

        set_transient('iafwzdesk_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', 'IAFWZDESK_Error_Log_delete_action');


function IAFWZDESK_Error_Log_delete_all_action()
{
    $IAFWZDESK_Error_LogDBInstance = new IAFWZDESK_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-desk' ||
        isset($_POST['bulk_delete_all_success'], $_GET['page']) && $_POST['bulk_delete_all_success'] === 'delete_all_success' && $_GET['page'] === 'integrate-with-zoho-desk'
    ) {
        // Verify the nonce.
        if (
            !isset($_POST['iafwzdesk_error_log_form_action_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['iafwzdesk_error_log_form_action_nonce'])), 'iafwzdesk_error_log_form_action')
        ) {
            wp_die(esc_html__('Security check failed.', 'integrate-with-zoho-desk'));
        }

        // Determine which type of logs to delete
        if (isset($_POST['bulk_delete_all']) && $_POST['bulk_delete_all'] === 'delete_all') {
            $result = $IAFWZDESK_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 = $IAFWZDESK_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('iafwzdesk_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', 'iafwzdesk_error_log_form_action_nonce']));
        exit;
    }
}

add_action('admin_init', 'IAFWZDESK_Error_Log_delete_all_action');




function IAFWZDESK_Error_Log_show_action()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Unauthorized.', 'integrate-with-zoho-desk')]);
        wp_die();
    }

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

    // 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-desk')]);
    }

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

    $error_log_details = $IAFWZDESK_Error_LogDBInstance->get_error_log($log_id);
    $integration_name = $IAFWZDESK_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-desk')]);
    }

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


// Reusable function for resync logic
function iafwzdesk_process_resync($log_id)
{
    $iafwzdesk_errorLogDBInstance = new IAFWZDESK_Error_Log();
    $iafwzdesk_formSubmit = new IAFWZDESK_FormSubmit();
    $iafwzdesk_fieldMappingDBInstance = new IAFWZDESK_Field_Mapping();

    $log_id = intval($log_id);

    // Retrieve error log details
    $error_log_details = $iafwzdesk_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 = $iafwzdesk_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 = $iafwzdesk_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
    $iafwzdesk_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.'];
    }

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

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

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

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

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

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