<?php

namespace CleantalkSP\SpbctWP\Scanner\OSCron\View;

use CleantalkSP\SpbctWP\Scanner\OSCron\Storages\OsCronTasksStorage;

class OSCronView
{
    /**
     * Returns the count of tasks scanned.
     *
     * @return int The number of tasks scanned.
     */
    public static function getCountOfTasksScanned()
    {
        return count(OsCronTasksStorage::get());
    }

    /**
     * Prepares the table data for display.
     *
     * @param object $table The table object containing rows of data.
     * @return object The modified table object with prepared data.
     */
    public static function prepareTableData($table)
    {
        foreach ($table->rows as $key => $row) {
            $actions = $row['actions'];
            // drop inverted actions
            if ($row['status'] === 'enabled' || ($row['verdict'] !== 'checked' && $row['status'] !== 'disabled')) {
                unset($actions['enable_oscron_task']);
            }
            if ($row['status'] === 'disabled') {
                unset($actions['disable_oscron_task']);
            }
            // prepare
            $table->items[$key] = array(
                'uid' => $row['id'],
                'cb' => $row['id'],
                'id' => $row['id'],
                // do not convert to human-readable if status is 'disabled'
                'repeats' => $row['status'] !== 'disabled' ? static::timePatternToHumanReadable($row['repeats']) : '-',
                'command' => $row['command'],
                'verdict' => static::decorateVerdict($row['verdict']),
                'detected' => static::decorateDetected($row['signature_matches']),
                'status' => static::decorateStatus($row['status']),
                'line_number' => $row['line_number'],
                'actions' => $actions,
            );
        }
        return $table;
    }

    /**
     * Decorates the status with appropriate HTML and CSS classes.
     *
     * @param string $status The status of the task.
     * @return string The decorated status with HTML and CSS classes.
     */
    private static function decorateStatus($status)
    {
        $class = '';
        if ($status === 'critical') {
            $status = OSCronLocale::getInstance()->task__status_critical;
            $class = 'spbc-icon-attention-alt spbc---red';
        }
        if ($status === 'enabled') {
            $status = OSCronLocale::getInstance()->task__status_enabled;
            $class = 'spbc-icon-ok spbc---green';
        }
        //disabled
        if ($status === 'disabled') {
            $status = OSCronLocale::getInstance()->task__status_disabled;
            $class = 'spbc-icon-cancel spbc---gray';
        }
        return '<b class="' . esc_html($class) . '">' . $status . '</b>';
    }

    /**
     * Decorates the analysis status with appropriate HTML and CSS classes.
     *
     * @param string $status The status of the task.
     * @return string The decorated status with HTML and CSS classes.
     */
    private static function decorateVerdict($status)
    {
        if ( ! $status ) {
            return '';
        }
        $class = 'spbc---gray';
        if ( $status === 'critical' ) {
            $status = OSCronLocale::getInstance()->task__verdict_critical;
        }
        if ( $status === 'checked' ) {
            $status = OSCronLocale::getInstance()->task__verdict_checked;
        }

        return '<span class="' . esc_html($class) . '">' . strtoupper($status) . '</span>';
    }

    private static function decorateDetected($signature_matches)
    {
        $detected = '';
        if ( ! $signature_matches ) {
            return '<span class="spbc---gray">'
                   . esc_html(OSCronLocale::getInstance()->task__nothing_detected)
                   . '</span>';
        }
        foreach ($signature_matches as $match) {
            if (isset($match['attack_type'])) {
                $detected .= '<span class="spbc---red">' . esc_html($match['attack_type']) . ': </span>';
            }
            if (isset($match['name'])) {
                $detected .= '<span>' . esc_html($match['name']) . ' </span>';
            }
        }
        return $detected;
    }

    /**
     * Converts a cron time pattern to a human-readable string.
     *
     * @param string $time The cron time pattern.
     * @return string The human-readable string representation of the cron time pattern.
     */
    private static function timePatternToHumanReadable($time)
    {
        $cronParts = explode(' ', $time);

        if (count($cronParts) !== 5) {
            return OSCronLocale::getInstance()->error__invalid_cron_expression;
        }

        list($minute, $hour, $dayOfMonth, $month, $dayOfWeek) = $cronParts;

        $humanReadable = __('At ', 'security-malware-firewall');

        // Handle minutes
        if ($minute === '*') {
            $humanReadable .= __('every minute', 'security-malware-firewall');
        } else {
            $humanReadable .= __('minute', 'security-malware-firewall') . ' ' . $minute;
        }

        // Handle hours
        if ($hour !== '*') {
            $humanReadable .= __(' past hour ', 'security-malware-firewall') . $hour;
        }

        // Handle days of the month
        if ($dayOfMonth !== '*') {
            $humanReadable .= __(' on day ', 'security-malware-firewall') . $dayOfMonth;
        }

        // Handle months
        if ($month !== '*') {
            $humanReadable .= __(' of month ', 'security-malware-firewall') . $month;
        }

        // Handle days of the week
        if ($dayOfWeek !== '*') {
            $humanReadable .= __(' on day of the week ', 'security-malware-firewall') . $dayOfWeek;
        }

        return $humanReadable;
    }
}
