<?php

namespace RtmBusiness\PostSync\Pages;

use Exception;
use JetBrains\PhpStorm\NoReturn;
use RtmBusiness\PostSync\Logger;
use RtmBusiness\PostSync\Model\Log;
use WordpressModels\Assets;

class LoggerPage extends NetworkPage
{

    public function __construct(Assets $assets)
    {
        parent::__construct('logger', 'postsync-logger', 'Logs', 'postsync-settings', 'administrator', 3, '', [], $assets, true, null, 'rtm-postsync');

        add_action('wp_ajax_postsync_logger_get', [$this, 'getLogs']);
    }

    /**
     * Gets log entities based on search string parameters
     * @return void
     * @throws Exception
     */
    #[NoReturn]
    public function getLogs(): void
    {
        check_ajax_referer('postsync_save_settings', 'nonce', false);
        if (wp_verify_nonce($_GET['nonce'], 'postsync_wp_ajax')) {
            $postPerPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $logs = Log::query();
            if (isset($_GET['sort'])) {
                $logs = $logs->sort(sanitize_text_field($_GET['sort']));
            }
            if (isset($_GET['order'])) {
                $logs = $logs->order(sanitize_text_field($_GET['order']));
            } else {
                $logs->order('DESC');
            }
            if (isset($_GET['severity']) && is_array($_GET['severity'])) {
                foreach ($_GET['severity'] as $severity) {
                    $logs = $logs->where('severity', sanitize_text_field($severity), 'OR');
                }
            }
            if (isset($_GET['category']) && is_array($_GET['category'])) {
                foreach ($_GET['category'] as $category) {
                    $logs = $logs->where('category', sanitize_text_field($category), 'OR');
                }
            }
            if (isset($_GET['source']) && is_array($_GET['source'])) {
                foreach ($_GET['source'] as $source) {
                    $logs = $logs->whereLike('source', sanitize_text_field($source), 'OR');
                }
            }
            if (isset($_GET['search'])) {
                $logs = $logs->search(sanitize_text_field($_GET['search']));
            }
            if (isset($_GET['filter_date'])) {
                if (isset($_GET['filter_date'][0]) && isset($_GET['filter_date'][1])) {
                    $logs = $logs->whereGreaterThanOrEqual("timestamp", sanitize_text_field($_GET['filter_date'][0]))
                        ->whereLessThanOrEqual("timestamp", sanitize_text_field($_GET['filter_date'][1]));
                }
            }
            $count = $logs->count();
            $logs = $logs->limit($postPerPage)->offset(($page - 1) * $postPerPage);
            wp_send_json_success(['logs' => array_map(function ($log) {
                return $log->format();
            }, $logs->execute()), 'count' => $count], 200);
        } else {
            Logger::error(
                'WP Nonce error',
                "Unable to verify plugin nonce, either the nonce was invalid or it does not exist",
                'LoggerPage::getLogs',
                'Plugin',
                [
                    "action" => "postsync_wp_ajax",
                    "nonce" => $_POST['_ajax_nonce'],
                    "post_data" => $_POST
                ]
            );
            wp_send_json_error([
                'message' => __('Nonce error', 'postsync')
            ]);
        }
        wp_die();
    }

    /**
     * @inheritDoc
     */
    public function buildContext(array $context = []): array
    {
        $page = 1;
        $postPerPage = 10;
        $logs = Log::query()->limit($postPerPage)->offset(($page - 1) * $postPerPage)->order('desc')->execute();
        $count = Log::query()->count();
        $pages = ceil($count / $postPerPage);

        $pageContext = [
            'logs' => $logs,
            'count' => $count,
            'pages' => $pages
        ];
        return array_merge($context, $pageContext);
    }


    /**
     * @inheritDoc
     */
    public function doEnqueue()
    {
        wp_localize_script('logger', 'WP_AJAX', [
            'url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('postsync_wp_ajax'),
        ]);
        wp_localize_script('logger', 'WP_REST', [
            'url' => get_rest_url(),
            'nonce' => wp_create_nonce('wp_rest'),
            'debug' => wp_get_environment_type() === 'development'
        ]);

        wp_localize_script('logger', 'WP_SETTINGS', [
            "locale" => get_locale()
        ]);
        wp_localize_script('logger', 'POSTSYNC_TRANSLATE', [
            'noLogsFound' => __('No logs have been found', 'postsync'),
        ]);
    }
}