<?php

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

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

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

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

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

        if ($deleted) {
            set_transient('integrazo_wz_success', __('Integration deleted successfully.', 'integrazo-integration-for-zoho-apps'), 60);
        } else {
            set_transient('integrazo_wz_fail', __('Failed to delete integration. Please try again.', 'integrazo-integration-for-zoho-apps'), 60);
        }

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


function INTEGRAZO_WZ_Error_Log_delete_all_action()
{
    $INTEGRAZO_WZ_Error_LogDBInstance = new INTEGRAZO_WZ_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-integration-for-zoho-apps' ||
        isset($_POST['bulk_delete_all_success'], $_GET['page']) && $_POST['bulk_delete_all_success'] === 'delete_all_success' && $_GET['page'] === 'integrazo-integration-for-zoho-apps'
    ) {
        // Verify the nonce.
        if (
            !isset($_POST['integrazo_wz_error_log_form_action_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['integrazo_wz_error_log_form_action_nonce'])), 'integrazo_wz_error_log_form_action')
        ) {
            wp_die(esc_html__('Security check failed.', 'integrazo-integration-for-zoho-apps'));
        }
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('permissions.', 'integrazo-integration-for-zoho-apps'));
        }
        // Determine which type of logs to delete
        if (isset($_POST['bulk_delete_all']) && $_POST['bulk_delete_all'] === 'delete_all') {
            $result = $INTEGRAZO_WZ_Error_LogDBInstance->delete_all_error_logs();
            $message = __('All logs have been deleted successfully!', 'integrazo-integration-for-zoho-apps');
        } elseif (isset($_POST['bulk_delete_all_success']) && $_POST['bulk_delete_all_success'] === 'delete_all_success') {
            $result = $INTEGRAZO_WZ_Error_LogDBInstance->delete_all_success_logs(); // You need to implement this function in your class
            $message = __('All successfully added records have been deleted!', 'integrazo-integration-for-zoho-apps');
        }

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

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

add_action('admin_init', 'INTEGRAZO_WZ_Error_Log_delete_all_action');


function INTEGRAZO_WZ_Error_Log_delete_action()
{
    $INTEGRAZO_WZ_Error_LogDBInstance = new INTEGRAZO_WZ_Logs_Model();

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

        set_transient('integrazo_wz_success', __('Log deleted successfully!', 'integrazo-integration-for-zoho-apps'), 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_WZ_Error_Log_delete_action');


// Hook delete action
add_action('admin_action_integrazo_wz_delete_account', 'integrazo_wz_account_delete_action');

function integrazo_wz_account_delete_action()
{
    $account_instance = new INTEGRAZO_WZ_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-integration-for-zoho-apps'));
        }
        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'integrazo-integration-for-zoho-apps'));
        }
        $account_instance->delete_error_log($account_id);

        set_transient('integrazo_wz_success', esc_html__('Account deleted successfully!', 'integrazo-integration-for-zoho-apps'), 300);

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

        wp_safe_redirect($redirect_url);
        exit;
    }
}
