<?php

/**
 * Class for handling scanner files data in the database. Only for reading operations.
 * For set, update, delete operations use ScanStorage class.
 */

namespace CleantalkSP\SpbctWP\Scanner;

class ScanRepository
{
    /**
     * Get approved hashes
     */
    public static function getApprovedRealFullHashes()
    {
        global $wpdb;

        return $wpdb->get_results(
            'SELECT real_full_hash FROM ' . SPBC_TBL_SCAN_FILES . ' WHERE status="APPROVED_BY_USER"',
            ARRAY_A
        );
    }

    /**
     * Get queued to send to Cleantalk Cloud files
     */
    public static function getPendingQueueFiles()
    {
        global $wpdb;

        return $wpdb->get_results(
            'SELECT fast_hash, status FROM ' . SPBC_TBL_SCAN_FILES . ' WHERE pscan_pending_queue = 1',
            ARRAY_A
        );
    }

    /**
     * Get fast hashes of the files known to the cloud analysis
     * @return array
     */
    public static function getCloudAnalysisFilesFastHashes()
    {
        global $wpdb;

        return (array) $wpdb->get_col(
            'SELECT DISTINCT fast_hash FROM ' . SPBC_TBL_SCAN_FILES
            . ' WHERE pscan_file_id IS NOT NULL AND fast_hash IS NOT NULL AND fast_hash <> ""'
        );
    }

    /**
     * Get file info by fast_hash
     * @return array|null
     */
    public static function getFileInfoByFastHash($fast_hash)
    {
        global $wpdb;

        $sql = $wpdb->prepare(
            'SELECT fast_hash, path, source_type, source, source_status, version, mtime, weak_spots, 
                full_hash, real_full_hash, status, checked_signatures, checked_heuristic, of_plugin_dir_success, of_plugin_dir_scan_info 
            FROM ' . SPBC_TBL_SCAN_FILES . ' WHERE fast_hash = %s LIMIT 1',
            $fast_hash
        );

        $sql_result = $wpdb->get_results($sql, ARRAY_A);

        return is_array($sql_result) && isset($sql_result[0]) ? $sql_result[0] : null;
    }
}
