<?php
/**
 * Admin: "Settings > Stripe" business logic
 *
 *
 */
if (! defined('ABSPATH')) {
    exit;
}
if (! current_user_can('manage_options')) {
    return;
}
try {
    // Create nonce for future use in URLs/forms
    $stripe_nonce = wp_create_nonce('chama_stripe_nonce');

    // Determine if the request is authorized via nonce
    $valid_nonce = isset($_GET['chama_nonce']) && is_string($_GET['chama_nonce']) && wp_verify_nonce(sanitize_key($_GET['chama_nonce']), 'chama_stripe_nonce');

    $mode = chama_is_live_mode() ? 'live' : 'test';

    $account_id          = get_option('chama_stripe_' . $mode . '_account_id');
    $account_country     = get_option('chama_stripe_' . $mode . '_account_country');
    $publishable_key     = get_option('chama_stripe_' . $mode . '_publishable_key');
    $secret_key          = get_option('chama_stripe_' . $mode . '_secret_key');
    $webhook_initialized = get_option('chama_stripe_' . $mode . '_webhook_initialized');
    $is_complete         = get_option('chama_stripe_' . $mode . '_account_completed_onboarding');

    // Handle authorized GET overrides
    if ($valid_nonce) {
        if (isset($_GET['id'])) {
            $account_id = sanitize_text_field(wp_unslash($_GET['id']));
        }
        if (isset($_GET['country'])) {
            $account_country = sanitize_text_field(wp_unslash($_GET['country']));
        }
        if (isset($_GET['pk'], $_GET['sk'])) {
            $publishable_key = sanitize_text_field(wp_unslash($_GET['pk']));
            $secret_key      = sanitize_text_field(wp_unslash($_GET['sk']));
        }
    }

    $connected          = $publishable_key && $secret_key;
    $show_account_error = false;

    $redirect_url         = admin_url('admin.php?page=chama-settings&tab=stripe');
    $stripe_dashboard_url = esc_url(CHAMA_STRIPE_DASHBOARD_URL . (chama_is_live_mode() ? '' : '/test'));

    // Generate URLs with nonce embedded
    $nonce_arg = ['chama_nonce' => $stripe_nonce];

    // Create account connect URL
    $connect_url = esc_url(add_query_arg(
        [
            'live_mode' => chama_is_live_mode(),
            'state'     => str_pad(wp_rand(wp_rand(), PHP_INT_MAX), 100, wp_rand(), STR_PAD_BOTH),
            'acct_url'  => urlencode(add_query_arg($nonce_arg, $redirect_url)),
        ],
        CHAMA_CONNECT_URL . '/?gateway_init=connect'
    ));

    // Create account verification URL
    $verify_url = esc_url(add_query_arg(
        [
            'live_mode' => chama_is_live_mode(),
            'id'        => $account_id,
            'acct_url'  => urlencode(add_query_arg($nonce_arg, $redirect_url)),
        ],
        CHAMA_CONNECT_URL . '/?gateway_init=verify'
    ));

    // Create account disconnect URL
    $disconnect_url = esc_url(add_query_arg(
        [
            'live_mode' => chama_is_live_mode(),
            'id'        => $account_id,
            'acct_url'  => urlencode(add_query_arg($nonce_arg, $redirect_url)),
        ],
        CHAMA_CONNECT_URL . '/?gateway_init=disconnect'
    ));

    // Handle resolution of onboarding process
    if ($valid_nonce && (isset($_GET['complete']) || isset($_GET['incomplete']))) {

        if (! $account_id && ! $secret_key && ! $publishable_key) {

            $show_account_error = true;
        }
    }

} catch (Exception $e) {

    wp_die(esc_html($e->getMessage()));
}
