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

namespace UltraguardPro\modules\antivirus\db;

use UltraguardPro\db\BaseTable;

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

// QuarantineTable
class QuarantineTable extends BaseTable {

    protected $table_name  = 'ultraguard_quarantine';
    protected $cache_group = 'ultraguard_quarantine';

    /**
     * @return array<string,mixed>
     */
    public function get_defaults(): array {
        return [
            'id'               => 0,
            'original_path'    => '',
            'quarantine_path'  => '',
            'file_hash'        => null,
            'file_size'        => 0,
            'threat_type'      => null,
            'threat_level'     => 'medium',
            'status'           => 'active',
            // Schema columns present in ultraguard_quarantine but missing from prior defaults:
            'clean_method'     => null,   // varchar(30) — e.g. 'core', 'plugin', 'injection_strip'
            'cleaned_at'       => null,   // datetime — when the clean operation ran
            'clean_backup_path'=> null,   // text — path to backup made before cleaning
            'restored_by'      => null,
            'restore_reason'   => null,
            'notes'            => null,
            'created_at'       => '',
            'updated_at'       => '',
        ];
    }

    /**
     * @param  array<string,mixed>|false $data
     * @return array<string,mixed>|false
     */
    protected function validate_data( $data ) {
        if ( empty( $data['original_path'] ) || empty( $data['quarantine_path'] ) ) {
            return false;
        }
        return $data;
    }

    /**
     * @param  array<string,mixed> $data
     * @return array<string,mixed>
     */
    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            $out[ $k ] = match ( $k ) {
                'original_path', 'quarantine_path',
                'clean_backup_path',
                'restore_reason', 'notes' => sanitize_textarea_field( (string) $v ),
                'file_size'               => absint( $v ),
                'restored_by'             => $v === null ? null : absint( $v ),
                // clean_method is a short enum-like varchar — plain sanitize_text_field is correct.
                // cleaned_at is a datetime string — pass through as-is (validated upstream).
                'clean_method'            => $v === null ? null : sanitize_text_field( (string) $v ),
                'cleaned_at'              => $v === null ? null : sanitize_text_field( (string) $v ),
                default                   => is_string( $v ) ? sanitize_text_field( $v ) : $v,
            };
        }
        return $out;
    }

    // ── Domain methods ─────────────────────────────────────────────────────────

    /**
     * Retrieve all actively quarantined files.
     *
     * @param  int $limit
     * @return array<int,array<string,mixed>>
     */
    public function get_active( int $limit = 100 ): array {
        return $this->get_by( [ 'status' => 'active' ], $limit, 'created_at', 'DESC' );
    }

    /**
     * Mark a quarantine record as restored.
     *
     * @param  int    $id      Record ID.
     * @param  string $reason  Admin-supplied restore reason.
     * @return bool
     */
    public function restore_file( int $id, string $reason = '' ): bool {
        return $this->update( $id, [
            'status'         => 'restored',
            'restored_by'    => get_current_user_id() ?: null,
            'restore_reason' => sanitize_text_field( $reason ),
        ] );
    }

    /**
     * Permanently delete a quarantined file from disk and mark record.
     *
     * @param  int $id  Record ID.
     * @return bool
     */
    public function permanently_delete( int $id ): bool {
        $item = $this->get( $id );
        if ( empty( $item['quarantine_path'] ) ) { return false; }

        if ( file_exists( $item['quarantine_path'] ) ) {
            wp_delete_file( $item['quarantine_path'] );
        }

        return $this->update( $id, [ 'status' => 'deleted' ] );
    }

    /**
     * Aggregate quarantine stats by status.
     *
     * @return array{active: int, restored: int, deleted: int, total: int}
     */
    public function get_quarantine_stats(): array {
        return [
            'active'   => $this->count( [ 'status' => 'active' ] ),
            'restored' => $this->count( [ 'status' => 'restored' ] ),
            'deleted'  => $this->count( [ 'status' => 'deleted' ] ),
            'total'    => $this->count(),
        ];
    }

    /**
     * @return string[]
     */
    protected function get_searchable_fields(): array {
        return [ 'original_path', 'quarantine_path', 'threat_type' ];
    }
}

// MalwareSignaturesTable
// =============================================================================
