<?php
/**
 * SailWP Co-pilot — Dashboard stats panel.
 *
 * Renders a small grid of "your site at a glance" cards below the
 * onboarding hero on /wp-admin/index.php. Replaces the empty grey area
 * the theme used to occupy with default WP widgets we strip out.
 *
 * v1 cards: Content (pages/posts/media), Updates (core/plugin/theme
 * counts with link to update-core.php), Site Health (transient from
 * WP's Site Health tool). PageSpeed deferred — it needs an API key.
 */
if (!defined('ABSPATH')) exit;

if (class_exists('SailWP_Copilot_Dashboard_Stats')) return;

class SailWP_Copilot_Dashboard_Stats {

    public function __construct() {
        add_action('all_admin_notices', [$this, 'render'], 20); // after onboarding-hero (priority 10)
        add_action('admin_head-index.php', [$this, 'hide_chrome']);
    }

    /**
     * Hide WP's "Dashboard" h1 + empty widgets-wrap when this panel is
     * showing. Keeps the page single-focus: hero + stats, nothing else.
     */
    public function hide_chrome() {
        if (!current_user_can('edit_posts')) return;
        ?>
        <style id="swcp-stats-hide-chrome">
            body.index-php .wrap > h1,
            body.index-php #dashboard-widgets-wrap,
            body.index-php #welcome-panel { display: none !important; }
            body.index-php .wrap { margin-top: 0 !important; }
        </style>
        <?php
    }

    public function render() {
        if (!is_admin()) return;
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->id !== 'dashboard') return;
        if (!current_user_can('edit_posts')) return;

        $content   = $this->content_card();
        $updates   = $this->updates_card();
        $health    = $this->health_card();
        ?>
        <div class="swcp-stats" role="region" aria-label="Site at a glance">
            <div class="swcp-stats__eyebrow">Your site at a glance</div>
            <div class="swcp-stats__grid">
                <?php echo $this->render_card($content); ?>
                <?php echo $this->render_card($updates); ?>
                <?php echo $this->render_card($health); ?>
            </div>
        </div>
        <style>
            .swcp-stats {
                margin: 0 20px 24px 2px;
                font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif;
            }
            .swcp-stats__eyebrow {
                font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase;
                font-weight: 600; color: rgba(26, 26, 46, 0.5);
                margin: 0 4px 12px;
            }
            .swcp-stats__grid {
                display: grid;
                grid-template-columns: repeat(3, minmax(0, 1fr));
                gap: 14px;
            }
            .swcp-stat {
                position: relative;
                display: block;
                padding: 18px 20px;
                background: #ffffff;
                border: 1px solid rgba(26, 26, 46, 0.08);
                border-radius: 12px;
                color: inherit; text-decoration: none;
                transition: transform 0.12s ease, box-shadow 0.18s ease, border-color 0.18s ease;
            }
            a.swcp-stat:hover, a.swcp-stat:focus-visible {
                transform: translateY(-2px);
                box-shadow: 0 10px 24px rgba(26, 26, 46, 0.08);
                border-color: rgba(232, 132, 92, 0.35);
                color: inherit;
                outline: none;
            }
            .swcp-stat__head {
                display: flex; align-items: center; gap: 10px;
                font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase;
                font-weight: 600; color: rgba(26, 26, 46, 0.55);
                margin-bottom: 12px;
            }
            .swcp-stat__icon {
                width: 18px; height: 18px; flex-shrink: 0;
                color: #e8845c;
            }
            .swcp-stat__primary {
                font-size: 22px; font-weight: 700; line-height: 1.15;
                color: #1a1a2e;
                display: flex; align-items: baseline; gap: 8px;
            }
            .swcp-stat__primary-meta {
                font-size: 12px; font-weight: 500;
                color: rgba(26, 26, 46, 0.5);
            }
            .swcp-stat__lines {
                margin: 10px 0 0; padding: 0; list-style: none;
                display: flex; flex-direction: column; gap: 4px;
            }
            .swcp-stat__lines li {
                font-size: 13px; line-height: 1.4;
                color: rgba(26, 26, 46, 0.7);
                display: flex; justify-content: space-between; gap: 12px;
            }
            .swcp-stat__lines li strong {
                color: #1a1a2e; font-weight: 600;
            }
            .swcp-stat__badge {
                display: inline-block; padding: 2px 8px;
                font-size: 10px; font-weight: 700; letter-spacing: 0.05em;
                text-transform: uppercase; border-radius: 999px;
                margin-left: 8px;
                vertical-align: middle;
            }
            .swcp-stat__badge--good     { background: rgba(31, 111, 62, 0.12); color: #1f6f3e; }
            .swcp-stat__badge--warn     { background: rgba(232, 132, 92, 0.18); color: #c4593a; }
            .swcp-stat__badge--critical { background: rgba(196, 89, 58, 0.2); color: #a04528; }

            @media (max-width: 900px) {
                .swcp-stats__grid { grid-template-columns: 1fr; }
            }
        </style>
        <?php
    }

    private function render_card($card) {
        $tag       = isset($card['href']) && $card['href'] ? 'a' : 'div';
        $href_attr = isset($card['href']) && $card['href'] ? ' href="' . esc_url($card['href']) . '"' : '';
        ob_start();
        ?>
        <<?php echo $tag; ?> class="swcp-stat"<?php echo $href_attr; ?>>
            <div class="swcp-stat__head">
                <span class="swcp-stat__icon" aria-hidden="true"><?php echo $card['icon']; // SVG: trusted ?></span>
                <span><?php echo esc_html($card['label']); ?></span>
            </div>
            <div class="swcp-stat__primary">
                <span><?php echo esc_html($card['primary']); ?></span>
                <?php if (!empty($card['primary_meta'])): ?>
                    <span class="swcp-stat__primary-meta"><?php echo esc_html($card['primary_meta']); ?></span>
                <?php endif; ?>
                <?php if (!empty($card['badge'])): ?>
                    <span class="swcp-stat__badge swcp-stat__badge--<?php echo esc_attr($card['badge']['kind']); ?>"><?php echo esc_html($card['badge']['text']); ?></span>
                <?php endif; ?>
            </div>
            <?php if (!empty($card['lines'])): ?>
            <ul class="swcp-stat__lines">
                <?php foreach ($card['lines'] as $line): ?>
                    <li>
                        <span><?php echo esc_html($line['label']); ?></span>
                        <strong><?php echo esc_html($line['value']); ?></strong>
                    </li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
        </<?php echo $tag; ?>>
        <?php
        return ob_get_clean();
    }

    private function content_card() {
        $pages    = wp_count_posts('page');
        $posts    = wp_count_posts('post');
        $media    = wp_count_attachments();
        $page_n   = $pages && isset($pages->publish) ? (int) $pages->publish : 0;
        $post_n   = $posts && isset($posts->publish) ? (int) $posts->publish : 0;
        $media_n  = 0;
        if (is_object($media)) {
            foreach ((array) $media as $k => $v) {
                if (strpos($k, 'image/') === 0 || strpos($k, 'video/') === 0 || strpos($k, 'audio/') === 0 || strpos($k, 'application/') === 0) {
                    $media_n += (int) $v;
                }
            }
        }
        $total = $page_n + $post_n;

        return [
            'label'        => 'Content',
            'icon'         => $this->icon_doc(),
            'primary'      => number_format_i18n($total),
            'primary_meta' => $total === 1 ? 'item published' : 'items published',
            'href'         => admin_url('edit.php?post_type=page'),
            'lines'        => [
                ['label' => 'Pages',         'value' => number_format_i18n($page_n)],
                ['label' => 'Posts',         'value' => number_format_i18n($post_n)],
                ['label' => 'Media',         'value' => number_format_i18n($media_n)],
            ],
        ];
    }

    private function updates_card() {
        $data = function_exists('wp_get_update_data') ? wp_get_update_data() : ['counts' => []];
        $counts = isset($data['counts']) ? $data['counts'] : [];
        $core    = isset($counts['wordpress']) ? (int) $counts['wordpress'] : 0;
        $plugins = isset($counts['plugins'])   ? (int) $counts['plugins']   : 0;
        $themes  = isset($counts['themes'])    ? (int) $counts['themes']    : 0;
        $total   = $core + $plugins + $themes;

        if ($total === 0) {
            $primary = 'Up to date';
            $badge   = ['kind' => 'good', 'text' => 'OK'];
            $lines   = [
                ['label' => 'WordPress', 'value' => get_bloginfo('version')],
                ['label' => 'Plugins',   'value' => 'Current'],
                ['label' => 'Themes',    'value' => 'Current'],
            ];
        } else {
            $primary = number_format_i18n($total);
            $badge   = ['kind' => $total > 3 ? 'critical' : 'warn', 'text' => 'Update'];
            $lines   = [
                ['label' => 'WordPress core', 'value' => $core ? $core . ' available' : 'Current'],
                ['label' => 'Plugins',        'value' => $plugins ? $plugins . ' available' : 'Current'],
                ['label' => 'Themes',         'value' => $themes ? $themes . ' available' : 'Current'],
            ];
        }

        return [
            'label'        => 'Software',
            'icon'         => $this->icon_refresh(),
            'primary'      => $primary,
            'primary_meta' => $total > 0 ? ($total === 1 ? 'update available' : 'updates available') : '',
            'badge'        => $badge,
            'href'         => admin_url('update-core.php'),
            'lines'        => $lines,
        ];
    }

    private function health_card() {
        $result = get_transient('health-check-site-status-result');
        $has_data = is_string($result) && $result !== '';
        $counts = [
            'good'        => 0,
            'recommended' => 0,
            'critical'    => 0,
        ];
        if ($has_data) {
            $decoded = json_decode($result, true);
            if (is_array($decoded)) $counts = array_merge($counts, array_map('intval', $decoded));
        }
        $total = $counts['good'] + $counts['recommended'] + $counts['critical'];

        if (!$has_data || $total === 0) {
            $primary = 'Unknown';
            $badge   = null;
            $lines   = [
                ['label' => 'Status', 'value' => 'Not yet checked'],
            ];
        } elseif ($counts['critical'] > 0) {
            $primary = 'Action needed';
            $badge   = ['kind' => 'critical', 'text' => $counts['critical'] . ' critical'];
            $lines   = [
                ['label' => 'Critical',     'value' => number_format_i18n($counts['critical'])],
                ['label' => 'Recommended',  'value' => number_format_i18n($counts['recommended'])],
                ['label' => 'Passing',      'value' => number_format_i18n($counts['good'])],
            ];
        } elseif ($counts['recommended'] > 0) {
            $primary = 'Should improve';
            $badge   = ['kind' => 'warn', 'text' => $counts['recommended'] . ' tips'];
            $lines   = [
                ['label' => 'Recommended',  'value' => number_format_i18n($counts['recommended'])],
                ['label' => 'Passing',      'value' => number_format_i18n($counts['good'])],
            ];
        } else {
            $primary = 'Good';
            $badge   = ['kind' => 'good', 'text' => 'Healthy'];
            $lines   = [
                ['label' => 'Passing', 'value' => number_format_i18n($counts['good'])],
            ];
        }

        return [
            'label'        => 'Site health',
            'icon'         => $this->icon_heart(),
            'primary'      => $primary,
            'badge'        => $badge,
            'href'         => admin_url('site-health.php'),
            'lines'        => $lines,
        ];
    }

    /* ---------- inline icons (coral stroke) ---------- */

    private function icon_doc() {
        return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="16" y2="17"/></svg>';
    }

    private function icon_refresh() {
        return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>';
    }

    private function icon_heart() {
        return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';
    }
}
