<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}


function integrazo_fwcrm_form_handle_account_authenticate()
{
    $redirect_url = admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=accounts');
    $auth_data = [
        'status' => 'fail',
        'message' => __('An unexpected issue occurred during authentication. Please try again.', 'crm-integration-freshworks-any-form')
    ];

    // Verify nonce
    if (
        empty($_POST['integrazo_fwcrm_form_account_authenticate_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['integrazo_fwcrm_form_account_authenticate_nonce'])),
            'integrazo_fwcrm_form_account_authenticate'
        )
    ) {
        $auth_data['message'] = __('Security verification failed. Please try again.', 'crm-integration-freshworks-any-form');
        set_transient('integrazo_fwcrm_form_auth_data', $auth_data, 300);
        wp_safe_redirect($redirect_url);
        exit;
    }

    // Sanitize and validate input data
    $account_name = sanitize_text_field(wp_unslash($_POST['account_name'] ?? ''));
    $instance_url = rtrim(esc_url_raw(wp_unslash($_POST['instance_url'] ?? '')), '/');
    $api_key = sanitize_textarea_field(wp_unslash($_POST['api_key'] ?? ''));
    $account_id = sanitize_textarea_field(wp_unslash($_POST['account_id'] ?? ''));

    $auth_data = array_merge($auth_data, compact('account_name', 'instance_url', 'api_key'));

    if (empty($account_name) || empty($instance_url) || empty($api_key)) {
        $auth_data['message'] = __('All fields are required. Please fill in all the details.', 'crm-integration-freshworks-any-form');
        set_transient('integrazo_fwcrm_form_auth_data', $auth_data, 300);
        wp_safe_redirect($redirect_url);
        exit;
    }
    $api_instance = new integrazo_fwcrm_form_API($instance_url, $api_key);
    $response = $api_instance->check_authentication('contacts');

    if (!empty($response['fields'])) {
        $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();

        // if ($account_id) {
        //     $result = $integrazo_fwcrm_form_accountDBInstance->update_account($account_id, $account_name, $instance_url, $api_key);
        //     $message = $result ? __('Account updated successfully!', 'crm-integration-freshworks-any-form') : __('Failed to save account details. Please try again.', 'crm-integration-freshworks-any-form');
        // } else {
        //     $result = $integrazo_fwcrm_form_accountDBInstance->insert_account($account_name, $instance_url, $api_key);
        //     $message = $result ? __('Account added successfully!', 'crm-integration-freshworks-any-form') : __('Failed to save account details. Please try again.', 'crm-integration-freshworks-any-form');
        // }
        if ($account_id) {
            set_transient('integrazo_fwcrm_form_account_message', "Account updated successfully.", 300);
            $integrazo_fwcrm_form_accountDBInstance->update_account($account_id, $account_name, $instance_url, $api_key);
        } else {

            $current_count = $integrazo_fwcrm_form_accountDBInstance->get_total_accounts();

            // Insert new account
            $account_id = $integrazo_fwcrm_form_accountDBInstance->insert_account($account_name, $instance_url, $api_key);

            // If this is the first account (count was 0 before insert)
            if ( $current_count == 0 ) {
                set_transient(
                    'integrazo_fwcrm_form_account_message',
                    "Account added successfully. Next, go to the Setup tab and start your integration.",
                    300
                );
            } else {
                set_transient('integrazo_fwcrm_form_account_message', "Account added successfully.", 300);
            }
        }
        // if ($result) {
        //     set_transient('integrazo_fwcrm_form_account_message', $message, 300);
            delete_transient('integrazo_fwcrm_form_auth_data');
            wp_safe_redirect($redirect_url);
            exit;
       // }
    } else {
        if (isset($response['error']) && !empty($response['error'])) {
            $auth_data['message'] = esc_html($response['error']);
        } else {
            $auth_data['message'] = esc_html__('Authentication failed. Please verify your credentials and try again.', 'crm-integration-freshworks-any-form');
        }

        if ($account_id) {
            $edit_url = add_query_arg([
                'page'      => 'crm-integration-freshworks-any-form',
                'tab'       => 'accounts',
                'ac_action' => 'edit',
                'ac_id'     => $account_id,
                '_wpnonce'  => wp_create_nonce('integrazo_fwcrm_form_edit_account_nonce')
            ], admin_url('admin.php'));

            set_transient('integrazo_fwcrm_form_auth_data', $auth_data, 300);
            wp_safe_redirect($edit_url);
            exit;
        }
    }

    set_transient('integrazo_fwcrm_form_auth_data', $auth_data, 300);
    wp_safe_redirect($redirect_url);
    exit;
}

add_action('admin_post_integrazo_fwcrm_form_account_authenticate', 'integrazo_fwcrm_form_handle_account_authenticate');


function integrazo_fwcrm_form_handle_delete_action()
{
    $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();

    // Check if the delete account ID parameter is provided
    if (
        isset($_GET['page'], $_GET['tab'], $_GET['ac_action'], $_GET['ac_id']) &&
        $_GET['page'] === 'crm-integration-freshworks-any-form' &&
        $_GET['tab'] === 'accounts' &&
        $_GET['ac_action'] === 'delete'
    ) {
        $account_id = intval($_GET['ac_id']);
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';

        // Verify nonce for delete action
        if (!wp_verify_nonce($nonce, 'integrazo_fwcrm_form_delete_account_' . $account_id)) {
            wp_die(esc_html__('Security check failed.', 'crm-integration-freshworks-any-form'));
        }

        // Call the delete function
        $deleted = $integrazo_fwcrm_form_accountDBInstance->delete_account($account_id);

        if ($deleted) {
            set_transient('integrazo_fwcrm_form_account_message', __('Account deleted successfully.', 'crm-integration-freshworks-any-form'), 300);
        } else {
            set_transient('integrazo_fwcrm_form_account_message', __('Failed to delete the account. Please try again.', 'crm-integration-freshworks-any-form'), 300);
        }

        // Redirect to the accounts tab page without 'de_ac_id' and '_wpnonce' in the URL
        $redirect_url = remove_query_arg(['ac_id', '_wpnonce', 'ac_action'], admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=accounts'));
        wp_safe_redirect($redirect_url);
        exit;
    }
}
add_action('admin_init', 'integrazo_fwcrm_form_handle_delete_action');
