<?php

/**
 * Get WordPress Meta Command
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Commands\WP;

use _121Digital\Connect\Commands\CommandBase;

/**
 * Command to get WordPress site metadata including version, updates, users, and pages.
 */
class GetMeta extends CommandBase
{
    /**
     * Retrieve the favicon URL for the site.
     *
     * This method first attempts to get the favicon ID from the WordPress Customizer.
     * If no custom favicon is set, it falls back to the default site icon URL.
     *
     * @return string The URL of the favicon image.
     */
    private function getFaviconUrl(): string
    {
        return get_site_icon_url() ?: '';
    }

    /**
     * Execute the WP metadata command.
     *
     * @return array An associative array of site metadata.
     */
    public function execute(): array
    {
        require_once ABSPATH . 'wp-admin/includes/update.php';

        $coreUpdates = get_core_updates();
        $updateAvailable = !empty($coreUpdates) && $coreUpdates[0]->response === 'upgrade';

        $info = [
            'wp_version' => get_bloginfo('version'),
            'update_needed' => $updateAvailable,
            'users_count' => count_users()['total_users'],
            'pages_count' => wp_count_posts('page')->publish,
            'connect_version' => SC_PLUGIN_VERSION,
            'favicon_url' => $this->getFaviconUrl(),
            'site_title' => get_bloginfo('name'),
            'site_subtitle' => get_bloginfo('description'),
        ];

        return $this->success('The command has executed.', $info);
    }
}
