<?php 

add_action('rest_api_init', function () {

    register_rest_route('spacetree', '/connectivity', array(
        'methods' => 'POST',
        'callback' => 'spacetree_third_party_connectivty_api',
        'permission_callback' => [$this, 'spacetree_api_permissions_callback'],
    ));

    register_rest_route('spacetree', '/client', array(
        'methods' => 'GET',
        'callback' => 'spacetree_get_client_api',
        'permission_callback' => [$this, 'spacetree_api_permissions_callback'],
    ));
});


function spacetree_third_party_connectivty_api ( \WP_REST_Request $req ) {
    return wp_send_json((object) [ 
        "success" => (object) [
            "message" => "connected successfully",
            "domain"  => (object) get_site_details()    
        ]
    ]);
}


// site detail
function get_site_details() {
    // Get site URL
    $site_url = wp_parse_url(site_url(), PHP_URL_HOST);
    $site_url = preg_replace('#^www\.(.+\.)#i', '$1', $site_url); // Remove 'www.' prefix
    $site_url = rtrim($site_url, '/'); // Remove trailing slash if present

    // Get site title
    $site_title = get_bloginfo('name');

    // Get site description
    $site_description = get_bloginfo('description');

    // Get site logo URL
    $site_logo_id = get_theme_mod('custom_logo');
    $site_logo_url = wp_get_attachment_image_src($site_logo_id, 'full');
    $site_logo_url = $site_logo_url ? $site_logo_url[0] : '';

    // Get admin user data
    $admin_user = get_user_by('login', 'admin'); // Replace 'admin' with the admin username
    $admin_name = $admin_user ? $admin_user->display_name : '';
    $admin_email = $admin_user ? $admin_user->user_email : '';
    $admin_avatar_url = $admin_user ? get_avatar_url($admin_user->ID) : '';

    // Get site contact email address
    $site_contact_email = get_option('admin_email');

    // Return site details as an associative array
    return array(
        'site_url' => $site_url,
        'site_title' => $site_title,
        'site_description' => $site_description,
        'site_logo_url' => $site_logo_url,
        'admin_name' => $admin_name,
        'admin_email' => $admin_email,
        'admin_avatar_url' => $admin_avatar_url,
        'site_contact_email' => $site_contact_email
    );
}


