<?php
/**
 * VulnerabilityResultsTable — standalone class file.
 *
 * @package UltraguardPro\modules\vulnerability\db
 */

namespace UltraguardPro\modules\vulnerability\db;

use UltraguardPro\db\BaseTable;

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

namespace UltraguardPro\modules\vulnerability\db;

use UltraguardPro\db\BaseTable;

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

// VulnerabilityResultsTable
class VulnerabilityResultsTable extends BaseTable {

    protected $table_name  = 'ultraguard_vulnerability_results';
    protected $cache_group = 'ultraguard_vulnerability_results';

    public function get_defaults(): array {
        return [
            'id'                   => 0,
            'component_type'       => 'plugin',
            'component_slug'       => '',
            'component_version'    => null,
            'cve_id'               => null,
            'cvss_score'           => null,
            'severity'             => 'medium',
            'title'                => '',
            'description'          => null,
            'references'           => null,
            'patched_in_version'   => null,
            'is_exploitable'       => 0,
            'virtual_patch_active' => 0,
            'status'               => 'open',
            'first_seen'           => '',
            'last_checked'         => '',
            'created_at'           => '',
            'updated_at'           => '',
        ];
    }

    protected function validate_data( $data ) {
        if ( empty( $data['component_slug'] ) || empty( $data['title'] ) ) {
            return false;
        }
        $valid_types = [ 'plugin', 'theme', 'core' ];
        $valid_sev   = [ 'low', 'medium', 'high', 'critical' ];
        $valid_stat  = [ 'open', 'patched', 'ignored', 'virtual_patched' ];

        if ( isset( $data['component_type'] ) && ! in_array( $data['component_type'], $valid_types, true ) ) {
            $data['component_type'] = 'plugin';
        }
        if ( isset( $data['severity'] ) && ! in_array( $data['severity'], $valid_sev, true ) ) {
            $data['severity'] = 'medium';
        }
        if ( isset( $data['status'] ) && ! in_array( $data['status'], $valid_stat, true ) ) {
            $data['status'] = 'open';
        }
        return $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            $out[ $k ] = match ( $k ) {
                'description', 'references' => $v === null ? null : sanitize_textarea_field( (string) $v ),
                'cvss_score'                => $v === null ? null : (float) $v,
                'is_exploitable',
                'virtual_patch_active'      => (int) (bool) $v,
                default                     => is_string( $v ) ? sanitize_text_field( $v ) : $v,
            };
        }
        return $out;
    }

    // ── Domain helpers ─────────────────────────────────────────────────────────

    /**
     * Summary counts for the dashboard.
     *
     * @return array{total:int,open:int,critical:int,high:int,medium:int,low:int,virtual_patched:int}
     */
    public function get_summary(): array {
        return [
            'total'           => $this->count(),
            'open'            => $this->count( [ 'status' => 'open' ] ),
            'critical'        => $this->count( [ 'severity' => 'critical', 'status' => 'open' ] ),
            'high'            => $this->count( [ 'severity' => 'high',     'status' => 'open' ] ),
            'medium'          => $this->count( [ 'severity' => 'medium',   'status' => 'open' ] ),
            'low'             => $this->count( [ 'severity' => 'low',      'status' => 'open' ] ),
            'virtual_patched' => $this->count( [ 'virtual_patch_active' => 1 ] ),
        ];
    }

    /**
     * Check whether a CVE already exists for this component+version.
     *
     * @param  string $slug    Component slug.
     * @param  string $cve_id  CVE identifier.
     * @return bool
     */
    public function cve_exists( string $slug, string $cve_id ): bool {
        return (bool) $this->count( [ 'component_slug' => $slug, 'cve_id' => $cve_id ] );
    }

    protected function get_searchable_fields(): array {
        return [ 'component_slug', 'cve_id', 'title', 'severity', 'status' ];
    }

    protected function invalidate_caches_after_insert()    { $this->clear_all_caches(); }
    protected function invalidate_caches_after_update( $id ) { $this->clear_all_caches(); }
    protected function invalidate_caches_after_bulk()      { $this->clear_all_caches(); }
}

// VirtualPatchesTable
// =============================================================================
