<?php
/**
 * DbScanResultsTable — BaseTable subclass for ultraguard_db_scan_results.
 *
 * @package UltraguardPro\modules\database_scanner\db
 */

namespace UltraguardPro\modules\database_scanner\db;

use UltraguardPro\db\BaseTable;

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

class DbScanResultsTable extends BaseTable {

    protected $table_name  = 'ultraguard_db_scan_results';
    protected $cache_group = 'ultraguard_db_scan_results';

    public function get_defaults(): array {
        return [
            'id'              => 0,
            'scan_id'         => '',
            'db_table'        => '',
            'column_name'     => '',
            'row_id'          => 0,
            'threat_type'     => '',
            'threat_level'    => 'medium',
            'matched_pattern' => null,
            'content_excerpt' => null,
            'status'          => 'pending',
            'cleaned_at'      => null,
            'created_at'      => '',
            'updated_at'      => '',
        ];
    }

    protected function validate_data( $data ) {
        if ( empty( $data['scan_id'] ) || empty( $data['db_table'] ) ) {
            return false;
        }
        $valid_levels   = [ 'low', 'medium', 'high', 'critical' ];
        $valid_statuses = [ 'pending', 'cleaned', 'ignored', 'false_positive' ];

        if ( isset( $data['threat_level'] ) && ! in_array( $data['threat_level'], $valid_levels, true ) ) {
            $data['threat_level'] = 'medium';
        }
        if ( isset( $data['status'] ) && ! in_array( $data['status'], $valid_statuses, true ) ) {
            $data['status'] = 'pending';
        }
        return $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            $out[ $k ] = match ( $k ) {
                'matched_pattern', 'content_excerpt' => $v === null ? null : sanitize_textarea_field( (string) $v ),
                'row_id'                              => (int) $v,
                default                               => is_string( $v ) ? sanitize_text_field( $v ) : $v,
            };
        }
        return $out;
    }

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

    /**
     * Get pending results for a scan, grouped by threat type.
     *
     * @param  string $scan_id
     * @return array
     */
    public function get_pending_by_scan( string $scan_id ): array {
        return $this->get_by( [ 'scan_id' => $scan_id, 'status' => 'pending' ], 5000, 'threat_level', 'DESC' );
    }

    /**
     * Summary counts across all scans.
     *
     * @return array{total:int,pending:int,cleaned:int,ignored:int,critical:int,high:int}
     */
    public function get_summary(): array {
        return [
            'total'    => $this->count(),
            'pending'  => $this->count( [ 'status' => 'pending' ] ),
            'cleaned'  => $this->count( [ 'status' => 'cleaned' ] ),
            'ignored'  => $this->count( [ 'status' => 'ignored' ] ),
            'critical' => $this->count( [ 'threat_level' => 'critical', 'status' => 'pending' ] ),
            'high'     => $this->count( [ 'threat_level' => 'high',     'status' => 'pending' ] ),
        ];
    }

    /** @return string[] */
    protected function get_searchable_fields(): array {
        return [ 'scan_id', 'db_table', 'threat_type', '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(); }
}
