<?php
/**
 * DevDome Tools — suite-wide account connection state + disconnect handler.
 *
 * The account exists for one user-facing purpose: the optional DevDome Monitoring service
 * (email alerts + the account dashboard). This file holds the server-verified
 * connection-state helper and the hub Disconnect handler. Nothing here gates any feature.
 */

defined('ABSPATH') || exit;

/**
 * Suite-wide, server-VERIFIED account connection state: {ok, account_id, email}.
 * "Connected" means the suite's site token (option devdcorev1_site_token, provisioned by the
 * one-click connect in any DevDome plugin) is linked to a DevDome account RIGHT NOW — the
 * alert service resolves token -> account -> email. Local option presence alone (stale or
 * test leftovers) never renders a connected UI. Cached: a transient marker skips the remote
 * call on normal page loads and a persistent last-known state survives transient outages.
 * function_exists-guarded so plugins can ship helpers of the same name safely.
 */
if (!function_exists('devdcorev1_connection_state')) {
    function devdcorev1_connection_state($force = false)
    {
        $state = get_option('devdcorev1_conn_state', array('ok' => 0, 'account_id' => '', 'email' => ''));
        if (!is_array($state)) {
            $state = array('ok' => 0, 'account_id' => '', 'email' => '');
        }
        if (!$force && get_transient('devdcorev1_conn_checked')) {
            return $state;
        }
        $token = (string) get_option('devdcorev1_site_token', '');
        if ('' === $token) {
            // No token = never connected anywhere in the suite. Definitive, no remote call.
            $state = array('ok' => 0, 'account_id' => '', 'email' => '');
            update_option('devdcorev1_conn_state', $state, false);
            set_transient('devdcorev1_conn_checked', 1, 12 * HOUR_IN_SECONDS);
            return $state;
        }
        $site = (string) get_option('devdcorev1_site_id', '');
        if ('' === $site) {
            $site = (string) wp_parse_url(home_url(), PHP_URL_HOST);
        }
        $resp = wp_remote_get(
            add_query_arg(array('site' => $site, 'token' => $token), 'https://api.devdome.com/plugin/account'),
            array('timeout' => 8)
        );
        if (is_wp_error($resp)) {
            set_transient('devdcorev1_conn_checked', 1, 10 * MINUTE_IN_SECONDS); // outage: keep last known
            return $state;
        }
        $code = (int) wp_remote_retrieve_response_code($resp);
        $data = json_decode(wp_remote_retrieve_body($resp), true);
        if (200 === $code && is_array($data) && !empty($data['email']) && is_email($data['email'])) {
            $acct = isset($data['account_id']) ? strtoupper(sanitize_text_field($data['account_id'])) : '';
            $state = array(
                'ok'         => 1,
                'account_id' => preg_match('/^DD\d{8}$/', $acct) ? $acct : '',
                'email'      => sanitize_email($data['email']),
            );
            update_option('devdcorev1_conn_state', $state, false);
            set_transient('devdcorev1_conn_checked', 1, 12 * HOUR_IN_SECONDS);
        } elseif (in_array($code, array(400, 401, 403, 404), true)) {
            // Definitive: the token is not linked to an account (or was unlinked server-side).
            $state = array('ok' => 0, 'account_id' => '', 'email' => '');
            update_option('devdcorev1_conn_state', $state, false);
            set_transient('devdcorev1_conn_checked', 1, HOUR_IN_SECONDS);
        } else {
            set_transient('devdcorev1_conn_checked', 1, 10 * MINUTE_IN_SECONDS); // 5xx: keep last known
        }
        return $state;
    }
}

/** Convenience: is the site connected to a DevDome account (server-verified, cached)? */
if (!function_exists('devdcorev1_account_is_connected')) {
    function devdcorev1_account_is_connected()
    {
        $state = devdcorev1_connection_state();
        return !empty($state['ok']);
    }
}

/**
 * Handle the hub Disconnect: unlink the site from the account server-side (token-authenticated;
 * the site token never leaves WordPress), then clear every local connect artifact so the
 * verified state flips to disconnected everywhere.
 */
function devdcorev1_hub_handle_account()
{
    if (empty($_POST['devdcorev1_disconnect']) || !current_user_can('manage_options')) {
        return;
    }
    check_admin_referer('devdcorev1_account', '_ddacct');
    update_option('devdcorev1_account_connected', 0);
    $site  = (string) get_option('devdcorev1_site_id', '');
    $token = (string) get_option('devdcorev1_site_token', '');
    if ($site !== '' && $token !== '') {
        wp_remote_post('https://api.devdome.com/plugin/disconnect', array(
            'timeout' => 10,
            'headers' => array('Content-Type' => 'application/json'),
            'body'    => wp_json_encode(array('site' => $site, 'token' => $token)),
        ));
    }
    delete_option('devdcorev1_conn_state');
    delete_transient('devdcorev1_conn_checked');
    delete_option('devdcorev1_connected_at');
    delete_option('devdcorev1_account_email');
    delete_option('devdcorev1_hub_connect_dismissed'); // the connect card should reappear
    devdcorev1_connection_state(true); // re-verify now so the UI flips immediately
    wp_safe_redirect(add_query_arg(
        array('page' => DEVDCOREV1_TOOLS_MENU_SLUG, 'ddacct' => 'disconnected'),
        admin_url('admin.php')
    ));
    exit;
}
add_action('admin_init', 'devdcorev1_hub_handle_account');
