<?php

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

// Action to handle Zoho CRM authentication
add_action('admin_post_iafwzc_authenticate_zoho_crm', 'iafwzc_handle_authenticate_zoho_crm');

function iafwzc_handle_authenticate_zoho_crm()
{
    if (
        !isset($_POST['iafwzc_auth_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['iafwzc_auth_nonce'])), 'iafwzc_authenticate_zoho_crm')
    ) {
        wp_die(esc_html__('Nonce verification failed. Please try again.', 'integrate-any-form-with-zoho-crm'));
    }

    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrate-any-form-with-zoho-crm'));
    }

    // Sanitize and prepare input data for authentication
    $auth_data = [
        'account_name' => sanitize_text_field(wp_unslash($_POST['accountName'] ?? '')),
        'service_name' => sanitize_text_field(wp_unslash($_POST['service'] ?? '')),
        'data_center'  => sanitize_text_field(wp_unslash($_POST['dataCenter'] ?? '')),
    ];


    // Define client ID and redirect URI
    $client_id = '1000.R6NADONBVTIS0VZSZ0DE5MNO3DEV7T';
    $redirect_uri = 'https://integrazo.com/zoho_callback';

    // Determine the scope based on the selected service
    $scope = ($auth_data['service_name'] === 'zoho_crm')
        ? 'ZohoCRM.modules.ALL,ZohoCRM.settings.ALL,ZohoCRM.users.ALL,ZohoCRM.org.ALL,ZohoCRM.coql.READ,ZohoCRM.files.CREATE'
        : 'ZohoBigin.modules.ALL,ZohoBigin.users.READ,ZohoBigin.settings.ALL,ZohoBigin.coql.READ';

    // Generate a nonce and construct the state with optional account_id
    $nonce = wp_create_nonce('iafwzc_code');
    $account_id = isset($_POST['account_id']) ? intval($_POST['account_id']) : null;

    // Build the base query parameters and conditionally add `ac_id`
    $query_args = [
        'page'  => 'integrate-any-form-with-zoho-crm',
        'tab'   => 'accounts',
        'nonce' => $nonce,
    ];
    if ($account_id !== null) {
        $query_args['ac_id'] = $account_id;
    }

    // Encode the state URL
    $state = urlencode(add_query_arg($query_args, admin_url('admin.php')));

    // Add `account_id` to `auth_data` for transient storage
    $auth_data['account_id'] = $account_id;

    update_option('iafwzc_account_data', $auth_data, false);

    // Construct the Zoho OAuth authorization URL
    $login_url = sprintf(
        "https://accounts.zoho.%s/oauth/v2/auth?scope=%s&client_id=%s&response_type=code&access_type=offline&redirect_uri=%s&state=%s",
        sanitize_text_field($auth_data['data_center']),
        urlencode($scope),
        esc_attr($client_id),
        urlencode($redirect_uri),
        $state
    );

    // Redirect to the Zoho OAuth login URL
    $zoho_host = 'accounts.zoho.' . sanitize_text_field($auth_data['data_center']);
    add_filter(
        'allowed_redirect_hosts',
        function ( $hosts ) use ( $zoho_host ) {
            $hosts[] = $zoho_host;
            return $hosts;
        }
    );
    wp_safe_redirect($login_url);
    exit;
}


// Action to check for Zoho code
add_action('admin_init', 'iafwzc_check_for_zoho_code');


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

    $iafwzc_accountDBInstance = new IAFWZC_Account_Table();
    if (isset($_GET['page'], $_GET['nonce']) && $_GET['page'] === 'integrate-any-form-with-zoho-crm') {
        // Verify nonce for security first, before any other processing
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'iafwzc_code')) {
            iafwzc_handle_error(
                esc_html__('Security check failed. Please try again.', 'integrate-any-form-with-zoho-crm')
            );
        }

        // Retrieve and sanitize transient values
        $auth_data = get_option('iafwzc_account_data', []);

        // Handle session expiration or missing data
        if (empty($auth_data)) {
            iafwzc_handle_error('Session expired. Please authenticate again.');
        }

        // If 'code' is not present, return error message for missing parameters
        if (!isset($_GET['code'])) {
            iafwzc_handle_error('Required parameters are missing or incorrect.');
        }

        // Proceed with Zoho token request if 'code' is available
        $token_response = iafwzc_request_zoho_token($auth_data);
        if ($token_response['error']) {
            iafwzc_handle_error($token_response['error_message']);
        }
        // Handle refresh token and account management
        $redirect_url = remove_query_arg(['code', 'nonce', 'ac_id']);
        $account_id = $auth_data['account_id'] ?? null;
        $refresh_token = sanitize_text_field($token_response['refresh_token']);
        $access_token = sanitize_text_field($token_response['access_token']);

        if ($account_id) {
            set_transient('iafwzc_account_message', "Account updated successfully.", 300);
            $iafwzc_accountDBInstance->update_account($account_id, $auth_data['account_name'], $auth_data['service_name'], $auth_data['data_center'], $refresh_token, $access_token);
        } else {

            $current_count = $iafwzc_accountDBInstance->get_total_accounts();

            // Insert new account
            $account_id = $iafwzc_accountDBInstance->insert_account(
                $auth_data['account_name'],
                $auth_data['service_name'],
                $auth_data['data_center'],
                $refresh_token,
                $access_token
            );

            // If this is the first account (count was 0 before insert)
            if ($current_count == 0) {
                set_transient(
                    'iafwzc_account_message',
                    "Account added successfully. Next, go to the Setup tab and start your integration.",
                    300
                );
            } else {
                set_transient('iafwzc_account_message', "Account added successfully.", 300);
            }
        }

        delete_option('iafwzc_account_data');

        wp_safe_redirect($redirect_url);
        exit;
    }
}

function iafwzc_handle_error($message)
{
    // Retrieve the existing auth data and merge the new error message
    $auth_data = get_option('iafwzc_account_data', []);

    $auth_data['error_message'] = $message; // Add error message to existing data

    update_option('iafwzc_account_data', $auth_data, false);

    // Redirect with error status
    wp_safe_redirect(remove_query_arg(['code', 'nonce']));
    exit;
}


function iafwzc_request_zoho_token($auth_data)
{
    // Define client credentials and redirect URI
    $client_id = '1000.R6NADONBVTIS0VZSZ0DE5MNO3DEV7T';
    $client_secret = '52f6c37069fd0db03ed6025766e968214d35bffbe5';
    $redirect_uri = 'https://integrazo.com/zoho_callback';

    // Prepare the token request data
    $token_request_data = [
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        'code' => isset($_GET['code']) ? sanitize_text_field(wp_unslash($_GET['code'])) : '',
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri' => $redirect_uri,
        'grant_type' => 'authorization_code',
    ];

    // Send the token request to Zoho
    $token_url = "https://accounts.zoho." . sanitize_text_field($auth_data['data_center']) . "/oauth/v2/token";
    $response = wp_remote_post($token_url, [
        'body' => $token_request_data,
        'timeout' => 30,
    ]);

    if (is_wp_error($response)) {
        return ['error' => true, 'error_message' => 'Failed to connect to Zoho. Please try again later.'];
    }

    // Decode the response data
    $response_data = json_decode(wp_remote_retrieve_body($response), true);

    // Check for refresh token or error in response
    if (!empty($response_data['refresh_token'])) {
        $response_data['error'] = false;
        return $response_data; // Return the modified response_data
    }


    $error_message = match ($response_data['error'] ?? '') {
        'invalid_code' => "Session expired. Please authenticate again.",
        'invalid_client' => "Oops! Incorrect Data Center selected. Please choose the correct one.",
        default => "Oops! There was an error. Please try again."
    };

    return ['error' => true, 'error_message' => $error_message];
}



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

    $iafwzc_accountDBInstance = new IAFWZC_Account_Table();
    // Check if the delete account ID parameter is provided
    if (isset($_GET['de_ac_id']) && isset($_GET['page']) && $_GET['page'] === 'integrate-any-form-with-zoho-crm') {
        $account_id = intval($_GET['de_ac_id']);
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';

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

        // Call the delete function
        $iafwzc_accountDBInstance->delete_account($account_id);
        set_transient('iafwzc_account_message', "Account deleted successfully.", 300);

        // Redirect to the current page after deletion, with 'status=0' and without 'de_ac_id' and '_wpnonce'
        wp_safe_redirect(remove_query_arg(['de_ac_id', '_wpnonce']));
        exit;
    }
}
add_action('admin_init', 'iafwzc_handle_delete_action');
