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

// Action to handle Zoho Desk authentication
add_action('admin_post_iafwzdesk_authenticate', 'iafwzdesk_handle_authenticate');

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

    // 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 = "Desk.settings.READ,Desk.basic.READ,Desk.tickets.ALL,Desk.search.READ,Desk.contacts.ALL";

    // Generate a unique nonce
    $nonce = wp_create_nonce('iafwzdesk_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-desk',
        '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('iafwzdesk_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 Desk OAuth login
    add_filter(
        'allowed_redirect_hosts',
        function ( $hosts ) use ( $data_center ) {
            $hosts[] = 'accounts.zoho.' . $data_center;
            return $hosts;
        }
    );
    wp_safe_redirect($zoho_auth_url);
    exit;
}


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


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

    $iafwzdesk_accountDBInstance = new IAFWZDESK_Account_Table();
    if (isset($_GET['page'], $_GET['nonce']) && $_GET['page'] === 'integrate-with-zoho-desk') {
        // Retrieve and sanitize transient values
        $auth_data = get_option('iafwzdesk_account_data') ?: [];

        // Handle session expiration or missing data
        if (empty($auth_data)) {
            return iafwzdesk_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'])), 'iafwzdesk_code')
        ) {
            return iafwzdesk_handle_error(esc_html__('Security check failed. Please try again.', 'integrate-with-zoho-desk'));
        }

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

        // Proceed with Zoho token request if 'code' is available
        $token_response = iafwzdesk_request_token($auth_data);
        if ($token_response['error']) {
            return iafwzdesk_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']);
        //
        $org_id = IAFWZDESK_PRODUCT::get_desk_org_id(
            sanitize_text_field($access_token),
            sanitize_text_field($auth_data['data_center'])
        );
        if ($org_id === -1) {
            return iafwzdesk_handle_error('Authentication failed. Your session may have expired or your token may be invalid. Please reauthenticate and try again.');
        }
        //
        if ($account_id) {
            set_transient('iafwzdesk_account_message', "Account updated successfully.", 300);
            $iafwzdesk_accountDBInstance->update_account($account_id, $auth_data['account_name'], $auth_data['data_center'], $refresh_token, $access_token, $org_id);
        } else {

            $current_count = $iafwzdesk_accountDBInstance->get_total_accounts();

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

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

        wp_safe_redirect($redirect_url);
        exit;
    }
}

function iafwzdesk_handle_error($message)
{
    // Retrieve the existing auth data and merge the new error message
    $auth_data = get_option('iafwzdesk_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('iafwzdesk_account_data', $auth_data);
    // Redirect with error status
    wp_safe_redirect(remove_query_arg(['code', 'nonce']));
    exit;
}


function iafwzdesk_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
    }

    // --- PHP 7 compatible fallback (replace the match block) ---
    $error_value = isset($response_data['error']) ? $response_data['error'] : '';

    if ($error_value === 'invalid_code') {
        $error_message = "Session expired. Please authenticate again.";
    } elseif ($error_value === '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 iafwzdesk_handle_delete_action()
{
    $iafwzdeskai_accountDBInstance = new IAFWZDESK_Account_Table();

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

        $iafwzdeskai_accountDBInstance->delete_account($account_id);
        set_transient('iafwzdesk_account_message', __('Account deleted successfully.', 'integrate-with-zoho-desk'), 300);

        wp_safe_redirect(remove_query_arg(['de_ac_id', '_wpnonce']));
        exit;
    }
}
add_action('admin_init', 'iafwzdesk_handle_delete_action');
