<?php
defined( 'ABSPATH' ) || exit;

/**
 * Orchestrates all individual scanners and stores a unified result.
 */
class SITECL_Scanner {

    /**
     * Run a full site scan.
     *
     * @return array  Unified issues list: [ ['type'=>..., 'severity'=>..., 'title'=>..., 'detail'=>...], ... ]
     */
    public static function run_full_scan(): array {
        $issues = [];

        $issues = array_merge( $issues, SITECL_Error_Reader::scan() );
        $issues = array_merge( $issues, SITECL_Health_Score::scan() );
        $issues = array_merge( $issues, SITECL_Plugin_CVE::scan() );
        $issues = array_merge( $issues, SITECL_Plugin_Bloat::scan() );
        $issues = array_merge( $issues, SITECL_Update_Risk::scan() );
        $issues = array_merge( $issues, SITECL_Image_Audit::scan() );
        $issues = array_merge( $issues, SITECL_Alt_Scanner::scan() );
        $issues = array_merge( $issues, SITECL_SEO_Checker::scan() );
        $issues = array_merge( $issues, SITECL_Broken_Links::scan() );

        $result = [
            'scanned_at' => current_time( 'mysql' ),
            'issues'     => $issues,
            'summary'    => self::summarise( $issues ),
        ];

        update_option( 'sitecl_last_scan', $result, false );

        // Sync PHP errors into the persistent error log.
        SITECL_Error_Log::sync_from_scan( $issues );

        // Persist to scan_results table.
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert(
            $wpdb->prefix . 'sitecl_scan_results',
            [
                'scan_type'  => 'full',
                'result'     => wp_json_encode( $result ),
                'scanned_at' => current_time( 'mysql' ),
            ],
            [ '%s', '%s', '%s' ]
        );

        return $result;
    }

    private static function summarise( array $issues ): array {
        $counts = [ 'critical' => 0, 'warning' => 0, 'info' => 0 ];
        foreach ( $issues as $issue ) {
            $sev = $issue['severity'] ?? 'info';
            if ( isset( $counts[ $sev ] ) ) {
                $counts[ $sev ]++;
            }
        }
        return $counts;
    }
}
