<?php

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

// Handle integration delete action securely on setup tab
add_action('admin_init', 'integrazo_wczo_handle_delete_request');

function integrazo_wczo_handle_delete_request()
{
    if (
        isset($_GET['action'], $_GET['integration_id'], $_GET['page'], $_GET['tab']) &&
        $_GET['action'] === 'delete' &&
        $_GET['page'] === 'integrazo-wc-zoho-integration' &&
        $_GET['tab'] === 'setup'
    ) {
        $integration_id = intval($_GET['integration_id']);

        // ✅ Now this function is safely available
        check_admin_referer('integrazo_wczo_delete_integration_' . $integration_id);

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

        $model = new INTEGRAZO_WCZO_Integration_Model();
        $deleted = $model->delete_integration_by_id($integration_id);

        if ($deleted) {
            set_transient('integrazo_wczo_success', __('Integration deleted successfully.', 'integrazo-wc-zoho-integration'), 60);
        } else {
            set_transient('integrazo_wczo_fail', __('Failed to delete integration. Please try again.', 'integrazo-wc-zoho-integration'), 60);
        }

        wp_safe_redirect(admin_url('admin.php?page=integrazo-wc-zoho-integration&tab=setup'));
        exit;
    }
}


function INTEGRAZO_WCZO_Error_Log_delete_all_action()
{
    $INTEGRAZO_WCZO_Error_LogDBInstance = new INTEGRAZO_WCZO_Logs_Model();

    // Check if the delete action is triggered.
    if (
        isset($_POST['bulk_delete_all'], $_GET['page']) && $_POST['bulk_delete_all'] === 'delete_all' && $_GET['page'] === 'integrazo-wc-zoho-integration' ||
        isset($_POST['bulk_delete_all_success'], $_GET['page']) && $_POST['bulk_delete_all_success'] === 'delete_all_success' && $_GET['page'] === 'integrazo-wc-zoho-integration'
    ) {
        // Verify the nonce.
        if (
            !isset($_POST['integrazo_wczo_error_log_form_action_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wczo_error_log_form_action_nonce'])), 'integrazo_wczo_error_log_form_action')
        ) {
            wp_die(esc_html__('Security check failed.', 'integrazo-wc-zoho-integration'));
        }
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('permissions.', 'integrazo-wc-zoho-integration'));
        }
        // Determine which type of logs to delete
        if (isset($_POST['bulk_delete_all']) && $_POST['bulk_delete_all'] === 'delete_all') {
            $result = $INTEGRAZO_WCZO_Error_LogDBInstance->delete_all_error_logs();
            $message = __('All logs have been deleted successfully!', 'integrazo-wc-zoho-integration');
        } elseif (isset($_POST['bulk_delete_all_success']) && $_POST['bulk_delete_all_success'] === 'delete_all_success') {
            $result = $INTEGRAZO_WCZO_Error_LogDBInstance->delete_all_success_logs(); // You need to implement this function in your class
            $message = __('All successfully added records have been deleted!', 'integrazo-wc-zoho-integration');
        }

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

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

add_action('admin_init', 'INTEGRAZO_WCZO_Error_Log_delete_all_action');


function INTEGRAZO_WCZO_Error_Log_delete_action()
{
    $INTEGRAZO_WCZO_Error_LogDBInstance = new INTEGRAZO_WCZO_Logs_Model();

    // Check if the delete log ID parameter is provided
    if (isset($_GET['de_log_id']) && isset($_GET['page']) && $_GET['page'] === 'integrazo-wc-zoho-integration') {
        $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.', 'integrazo-wc-zoho-integration'));
        }
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'integrazo-wc-zoho-integration'));
        }
        // Call the delete function
        $result = $INTEGRAZO_WCZO_Error_LogDBInstance->delete_error_log($log_id);

        set_transient('integrazo_wczo_success', __('Log deleted successfully!', 'integrazo-wc-zoho-integration'), 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', 'INTEGRAZO_WCZO_Error_Log_delete_action');


// Hook delete action
add_action('admin_action_integrazo_wczo_delete_account', 'integrazo_wczo_account_delete_action');

function integrazo_wczo_account_delete_action()
{
    $account_instance = new INTEGRAZO_WCZO_Account_Model();

    if (isset($_GET['de_ac_id'])) {
        $account_id = intval($_GET['de_ac_id']);
        $nonce      = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';

        if (!wp_verify_nonce($nonce, 'delete_account_' . $account_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'));
        }
        $account_instance->delete_error_log($account_id);

        set_transient('integrazo_wczo_success', esc_html__('Account deleted successfully!', 'integrazo-wc-zoho-integration'), 300);

        // Redirect back to accounts tab
        $redirect_url = add_query_arg([
            'page'    => 'integrazo-wc-zoho-integration',
            'tab'     => 'settings',
            'subtab'  => 'accounts'
        ], admin_url('admin.php'));

        wp_safe_redirect($redirect_url);
        exit;
    }
}
