<?php

namespace CleantalkSP\SpbctWP\Scanner\ScannerActions;

use CleantalkSP\SpbctWP\Helpers\HTTP;
use CleantalkSP\SpbctWP\Scanner\FrontendScan;
use CleantalkSP\SpbctWP\Helpers\CSV;
use CleantalkSP\Variables\Post;

class FrontendPagesActions
{
    /**
     * tested
     * Handler to approve or disapprove a page.
     * @param string $action Could be 'approve' or 'disapprove'
     * @return void
     * @throws \Exception
     */
    public static function pageApprove($action)
    {
        global $wpdb;

        if (!in_array($action, array('approve', 'disapprove'))) {
            throw new \Exception('APPROVE_PROCESS_MISTYPE');
        }

        $action = $action === 'approve' ? '1' : '0';

        $page_url = Post::get('page_url', null, 'url');
        $page_id = Post::getInt('page_id');

        if (empty($page_url) || $page_id === 0 ) {
            throw new \Exception('PAGE_ID_OR_PAGE_URL_IS_EMPTY');
        }

        if (filter_var($page_url, FILTER_VALIDATE_URL)) {
            // Getting file info.
            $sql = 'UPDATE ' . SPBC_TBL_SCAN_FRONTEND . ' SET approved = ' . $action . ' WHERE url = %s';
            $sql = $wpdb->prepare($sql, $page_url);
            $sql_result = $wpdb->query($sql);
            if ($sql_result === false) {
                throw new \Exception('COULDNT_UPDATE_DB');
            }
            $update_meta_result = update_post_meta($page_id, '_spbc_frontend__approved', (int)$action);
            if (false === $update_meta_result) {
                throw new \Exception('COULDNT_UPDATE_POST_META');
            }
        }
    }

    /**
     * frozen
     * Approve pages in bulk
     * @param string $action
     * @return array
     */
    public static function pageApproveBulk($action)
    {
        global $wpdb;

        $action = $action === 'approve' ? '1' : '0';

        $out = array();

        $sql = 'UPDATE ' . SPBC_TBL_SCAN_FRONTEND . ' SET approved = %s';
        $sql = $wpdb->prepare($sql, $action);
        $sql_result = $wpdb->query($sql);
        if ($sql_result === false) {
            $out['error'] = 'COULDNT_UPDATE_DB';
        }

        $ids = $wpdb->get_col("SELECT page_id FROM " . SPBC_TBL_SCAN_FRONTEND);
        foreach ($ids as $id) {
            $update_meta_result = update_post_meta($id, '_spbc_frontend__approved', (int)$action);
            if ($update_meta_result === false) {
                $out['error'] = 'COULDNT_UPDATE_POST_META';
            }
        }

        return $out;
    }

    /**
     * View page
     * @param string $page_url
     * @return array
     */
    public static function viewPage($page_url)
    {
        global $spbc, $wpdb;

        $time_start = microtime(true);

        $page_content = HTTP::getContentFromURL($page_url);

        if (empty($page_content) || (is_array($page_content) && isset($page_content['error']))) {
            return array('error' => 'FILE_TEXT_EMPTY');
        }

        // Getting signatures
        $check_list = array('redirects', 'dbd', 'signatures_js', 'signatures_html');
        if ($spbc->settings['scanner__frontend_analysis__csrf']) {
            $check_list[] = 'csrf';
        }
        $fe_scanner = new FrontendScan($check_list);
        $recheck_res = $fe_scanner->setHomeUrl(get_option('home'))
                                    ->setExceptUrls(CSV::parseNSV($spbc->settings['scanner__frontend_analysis__domains_exclusions']))
                                    ->setSignatures($wpdb->get_results('SELECT * FROM ' . SPBC_TBL_SCAN_SIGNATURES, ARRAY_A))
                                    ->setContent($page_content)
                                    ->check()
                                    ->getResult();

        // If the malware not more present
        if (count($recheck_res) === 0) {
            $page_id = $wpdb->get_var(
                $wpdb->prepare(
                    'SELECT page_id'
                    . ' FROM ' . SPBC_TBL_SCAN_FRONTEND
                    . ' WHERE url = %s',
                    $page_url
                )
            );
            delete_post_meta($page_id, '_spbc_frontend__last_checked');
            delete_post_meta($page_id, 'spbc_frontend__last_checked');
            $wpdb->query(
                $wpdb->prepare(
                    'DELETE'
                    . ' FROM ' . SPBC_TBL_SCAN_FRONTEND
                    . ' WHERE url = %s',
                    $page_url
                )
            );

            return [
                'success' => false,
                'content' => esc_html__('The malware found earlier no longer present. The notice about the malware will be replaced from the results list.', 'security-malware-firewall'), // Content of the modal
                'file_path' => esc_html__('The malware no longer found', 'security-malware-firewall') // Title of the modal
            ];
        }

        $page_text = array();
        $page_url_sql = str_replace('.', '%', $page_url);

        // Getting file info.
        $sql_result = $wpdb->get_results(
            $wpdb->prepare(
                'SELECT weak_spots'
                . ' FROM ' . SPBC_TBL_SCAN_FRONTEND
                . ' WHERE url LIKE %s'
                . ' LIMIT 1',
                $page_url_sql
            ),
            ARRAY_A
        );
        $result = isset($sql_result[0]) ? $sql_result[0] : null;

        foreach (preg_split("/((\r?\n)|(\r\n?))/", $page_content) as $line) {
            $page_text[] = htmlspecialchars($line);
        }

        $output = array(
            'success'    => true,
            'file'       => $page_text,
            'file_path'  => $page_url,
            'difference' => null,
            'weak_spots' => isset($result['weak_spots']) ? $result['weak_spots'] : null
        );

        $exec_time           = round(microtime(true) - $time_start);
        $output['exec_time'] = $exec_time;

        $red_line             = '<span style=\"background: rgb(200,80,80);\">';
        $red_line_end         = '</span>';
        $output['weak_spots'] = str_replace('__SPBCT_RED__', $red_line, $output['weak_spots']);
        $output['weak_spots'] = str_replace('__SPBCT_RED_END__', $red_line_end, $output['weak_spots']);

        return $output;
    }
}
