<?php

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

// Action to handle Zoho Campaigns authentication
add_action('admin_post_iafwzcai_authenticate', 'iafwzcai_handle_authenticate');

function iafwzcai_handle_authenticate()
{
    // Check if nonce exists and is valid
    if (
        !isset($_POST['iafwzcai_auth_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['iafwzcai_auth_nonce'])), 'iafwzcai_authenticate')
    ) {
        wp_die(esc_html__('Nonce verification failed. Please try again.', 'integrate-with-zoho-campaigns'));
    }

    // Validate and sanitize input data
    $account_name = isset($_POST['accountName']) ? sanitize_text_field(wp_unslash($_POST['accountName'])) : '';
    $data_center  = isset($_POST['dataCenter']) ? sanitize_text_field(wp_unslash($_POST['dataCenter'])) : '';

    // Define Zoho API credentials
    $client_id = '1000.R6NADONBVTIS0VZSZ0DE5MNO3DEV7T';
    $redirect_uri = 'https://integrazo.com/zoho_callback';

    // Define required OAuth scopes
    $scope = "ZohoCampaigns.contact.CREATE,ZohoCampaigns.contact.READ,ZohoCampaigns.contact.UPDATE";

    // Generate a unique nonce
    $nonce = wp_create_nonce('iafwzcai_code');

    // Get account ID if re-authenticating
    $account_id = isset($_POST['account_id']) ? intval($_POST['account_id']) : null;

    // Prepare the state parameter with necessary details
    $query_args = [
        'page'  => 'integrate-with-zoho-campaigns',
        'tab'   => 'accounts',
        'nonce' => $nonce,
    ];
    if (!empty($account_id)) {
        $query_args['ac_id'] = $account_id;
    }

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

    // Prepare authentication data and store it in a transient
    $auth_data = [
        'account_name' => $account_name,
        'data_center'  => $data_center,
        'account_id'   => $account_id,
    ];
    update_option('iafwzcai_account_data', $auth_data);

    // Construct the Zoho OAuth URL
    $zoho_auth_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",
        esc_attr($data_center),
        urlencode($scope),
        esc_attr($client_id),
        urlencode($redirect_uri),
        $state
    );

    // Redirect user to Zoho Campaigns OAuth login
    wp_redirect($zoho_auth_url);
    exit;
}


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


function iafwzcai_check_for_code()
{
    $iafwzcai_accountDBInstance = new IAFWZCAI_Account_Table();
    if (isset($_GET['page'], $_GET['nonce']) && $_GET['page'] === 'integrate-with-zoho-campaigns') {
        // Retrieve and sanitize transient values
        $auth_data = get_option('iafwzcai_account_data') ?: [];

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

        // Verify nonce for security
        if (
            !isset($_GET['nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'iafwzcai_code')
        ) {
            return iafwzcai_handle_error(esc_html__('Security check failed. Please try again.', 'integrate-with-zoho-campaigns'));
        }

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

        // Proceed with Zoho token request if 'code' is available
        $token_response = iafwzcai_request_token($auth_data);
        if ($token_response['error']) {
            return iafwzcai_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('iafwzcai_account_message', "Account updated successfully.", 300);
            $iafwzcai_accountDBInstance->update_account($account_id, $auth_data['account_name'], $auth_data['data_center'], $refresh_token, $access_token);
        } else {

            $current_count = $iafwzcai_accountDBInstance->get_total_accounts();

            // Insert new account
            $account_id = $iafwzcai_accountDBInstance->insert_account($auth_data['account_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(
                    'iafwzcai_account_message',
                    "Account added successfully. Next, go to the Setup tab and start your integration.",
                    300
                );
            } else {
                set_transient('iafwzcai_account_message', "Account added successfully.", 300);
            }
        }
        // Delete auth data transient and redirect
        delete_option('iafwzcai_account_data');
        wp_redirect($redirect_url);
        exit;
    }
}

function iafwzcai_handle_error($message)
{
    // Retrieve the existing auth data and merge the new error message
    $auth_data = get_option('iafwzcai_account_data') ?: [];
    $auth_data['error_message'] = $message; // Add error message to existing data

    // Set the transient with the full auth data, including error message
    update_option('iafwzcai_account_data', $auth_data);
    // Redirect with error status
    wp_redirect(remove_query_arg(['code', 'nonce']));
    exit;
}


function iafwzcai_request_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." . esc_attr($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_key = $response_data['error'] ?? '';

    if ($error_key === 'invalid_code') {
        $error_message = "Session expired. Please authenticate again.";
    } elseif ($error_key === 'invalid_client') {
        $error_message = "Oops! Incorrect Data Center selected. Please choose the correct one.";
    } else {
        $error_message = "Oops! There was an error. Please try again.";
    }

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




function iafwzcai_handle_delete_action()
{
    $iafwzcaiai_accountDBInstance = new IAFWZCAI_Account_Table();

    if (isset($_GET['de_ac_id'], $_GET['page']) && $_GET['page'] === 'integrate-with-zoho-campaigns') {
        $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.', 'integrate-with-zoho-campaigns'));
        }

        $iafwzcaiai_accountDBInstance->delete_account($account_id);
        set_transient('iafwzcai_account_message', __('Account deleted successfully.', 'integrate-with-zoho-campaigns'), 300);

        wp_redirect(remove_query_arg(['de_ac_id', '_wpnonce']));
        exit;
    }
}
add_action('admin_init', 'iafwzcai_handle_delete_action');
