<?php

namespace UltraguardPro\modules\auto_updater\pages;

if ( ! defined( 'ABSPATH' ) ) { exit; }

use UltraguardPro\Plugin;
use UltraguardPro\modules\auto_updater\UpdateEngine;
use UltraguardPro\modules\core\BasePage;

class AutoUpdaterDashboard extends BasePage {

    private ?UpdateEngine $engine = null;

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $engine  = $this->engine();
        $pending = $engine->get_pending_updates();
        $stats   = $engine->get_update_stats();
        $table   = $this->plugin->modules->get_db_tables()->get_table( 'update_log' );
        $log     = $table && method_exists( $table, 'get_recent' ) ? $table->get_recent( 30 ) : [];
        $pie     = $table && method_exists( $table, 'get_monthly_type_breakdown' ) ? $table->get_monthly_type_breakdown() : [];

        return [
            'type'      => 'page',
            'id'        => 'auto-updater-dashboard',
            'page_slug' => 'auto-updater',
            'header'    => [
                'title'    => __( 'Auto Plugin & Theme Updater', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Keep WordPress core, plugins, and themes updated with safer automation and change tracking.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'auto-updater-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Apply All Updates', 'ultraguard-security-suite' ), 'ultraguard_updater_apply_all', [], 'primary', 'dashicons-update' ),
                    $this->create_ajax_button( __( 'Check for Updates Now', 'ultraguard-security-suite' ), 'ultraguard_updater_get_pending', [], 'secondary', 'dashicons-search' ),
                ],
            ],
            'data'      => [
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Pending Updates', 'ultraguard-security-suite' ), 'value' => count( $pending ), 'format' => 'number', 'icon' => 'dashicons-update', 'class' => count( $pending ) > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Applied This Month', 'ultraguard-security-suite' ), 'value' => (int) $stats['applied_month'], 'format' => 'number', 'icon' => 'dashicons-yes-alt', 'class' => 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Failed Updates', 'ultraguard-security-suite' ), 'value' => (int) $stats['failed'], 'format' => 'number', 'icon' => 'dashicons-warning', 'class' => (int) $stats['failed'] > 0 ? 'danger' : 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last Check', 'ultraguard-security-suite' ), 'value' => ! empty( $stats['last_check'] ) ? $this->format_date_time( (string) $stats['last_check'] ) : __( 'Never', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-clock', 'class' => 'info' ] ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Pending Updates', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-update',
                    'data'  => [
                        [
                            'type'       => 'data-table',
                            'id'         => 'auto-updater-pending',
                            'columns'    => [
                                'component'     => [ 'title' => __( 'Component', 'ultraguard-security-suite' ) ],
                                'type'          => [ 'title' => __( 'Type', 'ultraguard-security-suite' ) ],
                                'versions'      => [ 'title' => __( 'Current → New', 'ultraguard-security-suite' ) ],
                                'vulnerability' => [ 'title' => __( 'Vulnerability', 'ultraguard-security-suite' ) ],
                                'actions'       => [ 'title' => __( 'Actions', 'ultraguard-security-suite' ) ],
                            ],
                            'data'       => $this->build_pending_rows( $pending ),
                            'searchable' => true,
                            'pagination' => [ 'enabled' => true, 'page_size' => 20 ],
                        ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '18px',
                    'items'   => [
                        [
                            'span'      => 5,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Update Types This Month', 'ultraguard-security-suite' ),
                                'data'  => [
                                    [
                                        'type'       => 'chart',
                                        'chart_type' => 'pie',
                                        'height'     => '250px',
                                        'labels'     => array_map( static function ( $row ) { return (string) $row['component_type']; }, $pie ),
                                        'datasets'   => [
                                            [
                                                'data'            => array_map( static function ( $row ) { return (int) $row['total']; }, $pie ),
                                                'backgroundColor' => [ '#155eef', '#157347', '#f79009' ],
                                            ],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 7,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Applied Updates History', 'ultraguard-security-suite' ),
                                'data'  => [
                                    [
                                        'type'       => 'data-table',
                                        'id'         => 'auto-updater-history',
                                        'columns'    => [
                                            'status'     => [ 'title' => __( 'Status', 'ultraguard-security-suite' ) ],
                                            'component'  => [ 'title' => __( 'Component', 'ultraguard-security-suite' ) ],
                                            'versions'   => [ 'title' => __( 'Versions', 'ultraguard-security-suite' ) ],
                                            'trigger'    => [ 'title' => __( 'Trigger', 'ultraguard-security-suite' ) ],
                                            'date'       => [ 'title' => __( 'Date', 'ultraguard-security-suite' ) ],
                                        ],
                                        'data'       => $this->build_log_rows( $log ),
                                        'searchable' => true,
                                        'pagination' => [ 'enabled' => true, 'page_size' => 15 ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
            'form'      => [ 'enable' => false ],
        ];
    }

    private function build_pending_rows( array $pending ): array {
        $rows = [];

        foreach ( $pending as $index => $update ) {
            $rows[] = [
                'id'            => 'pending-update-' . $index,
                'component'     => esc_html( (string) $update['name'] ),
                'type'          => [ 'content' => esc_html( ucfirst( (string) $update['type'] ) ), 'class' => 'info' ],
                'versions'      => esc_html( (string) $update['old_version'] . ' → ' . (string) $update['new_version'] ),
                'vulnerability' => esc_html( apply_filters( 'ultraguard_pro/vulnerability/get_component_status', __( 'Unknown', 'ultraguard-security-suite' ), $update ) ),
                'actions'       => $this->row_actions( [
                    [
                        'type' => 'button',
                        'text' => __( 'Update', 'ultraguard-security-suite' ),
                        'button_style' => 'primary',
                        'ajax' => [
                            'action' => 'ultraguard_updater_apply_one',
                            'nonce'  => $this->create_nonce( 'ultraguard_admin_nonce' ),
                            'data'   => [
                                'component_type' => $update['type'],
                                'component_slug' => $update['slug'],
                            ],
                        ],
                    ],
                    [
                        'type' => 'button',
                        'text' => __( 'Skip', 'ultraguard-security-suite' ),
                        'button_style' => 'secondary',
                        'ajax' => [
                            'action' => 'ultraguard_updater_skip_update',
                            'nonce'  => $this->create_nonce( 'ultraguard_admin_nonce' ),
                            'data'   => [
                                'component_type' => $update['type'],
                                'component_slug' => $update['slug'],
                            ],
                        ],
                    ],
                ] ),
            ];
        }

        return $rows;
    }

    private function build_log_rows( array $log ): array {
        $rows = [];
        foreach ( $log as $index => $row ) {
            $rows[] = [
                'id'        => 'update-log-' . $index,
                'status'    => [ 'content' => esc_html( ucfirst( (string) $row['status'] ) ), 'class' => $this->status_class( (string) $row['status'] ) ],
                'component' => esc_html( (string) $row['component_name'] ),
                'versions'  => esc_html( (string) $row['old_version'] . ' → ' . (string) $row['new_version'] ),
                'trigger'   => esc_html( ucfirst( (string) $row['trigger_type'] ) ),
                'date'      => esc_html( $this->format_date_time( (string) $row['created_at'] ) ),
            ];
        }

        return $rows;
    }

    private function status_class( string $status ): string {
        switch ( $status ) {
            case 'success':
                return 'success';
            case 'failed':
                return 'danger';
            case 'rolled_back':
                return 'warning';
            default:
                return 'secondary';
        }
    }

    private function engine(): UpdateEngine {
        if ( null === $this->engine ) {
            $this->engine = new UpdateEngine( $this->plugin );
        }

        return $this->engine;
    }
}
