<?php declare( strict_types=1 );

namespace FernleafSystems\Wordpress\Plugin\Shield\Controller\Database;

use FernleafSystems\Wordpress\Plugin\Shield\Modules\PluginControllerConsumer;
use FernleafSystems\Wordpress\Services\Services;

class CleanMalwareDB {

	use PluginControllerConsumer;

	public function run() :void {
		$this->deleteRecordsWhereFileRemoved();
	}

	private function deleteRecordsWhereFileRemoved() :void {
		$records = self::con()->db_con->malware
			->getQuerySelector()
			->setResultsAsVo( false )
			->setSelectResultsFormat( ARRAY_A )
			->setColumnsToSelect( [ 'id', 'file_path' ] )
			->queryWithResult();

		if ( \is_array( $records ) ) {
			$idsToDelete = [];
			foreach ( $records as $record ) {
				if ( !Services::WpFs()->isAccessibleFile( path_join( ABSPATH, $record[ 'file_path' ] ) ) ) {
					$idsToDelete[] = (int)$record[ 'id' ];
				}
			}

			if ( !empty( $idsToDelete ) ) {
				self::con()->db_con->malware
					->getQueryDeleter()
					->addWhereIn( 'id', $idsToDelete )
					->query();
			}
		}
	}
}
