<?php

namespace RtmMail\Helpers;

use Devdot\Monolog\Reader\LogReader;
use RtmMail\Models\Entities\Log;

/**
 * EventHelper - Helper for loading log data to a table
 */
class EventHelper
{
    /**
     * DEFAULT_ARGS - default settings to use for getting all logs
     * @type array
     */
    const DEFAULT_ARGS = [
        'orderby'       => 'timestamp',
        'order'         => 'DESC',
        'post_per_page' => 10,
        'paged'         => 1,
        'date'          => null,
        's'             => null,
        'filter_severity' => null,
        'severity_type' => null,
    ];

    /**
     * get - Get all the logs from WP_PLUGIN_DIR/rtm-mail/logs
     *
     * @param array $args
     *
     * @return array|int
     */
    public static function get($args = [], $isCount = false)
    {
        // Merge defaults with given args
        $args = array_merge(self::DEFAULT_ARGS, $args);

        // Begin constructing the query
        $query = Log::query();

        // Handle severity filtering
        if (!empty($args['filter_severity']) && !empty($args['severity_type'])) {
            $query->where('severity', $args['severity_type'], 'AND');
        }

        $query->sort($args['orderby']);
        $query->order($args['order']);

        // Search by id
        if (!empty($args['id'])) {
            $searchTerm = esc_sql($args['id']);
            $query->where('id', (int)$searchTerm);
        }
        // Handle basic search functionality if 's' is provided
        if (!empty($args['s'])) {
            $searchTerm = esc_sql($args['s']);
            $query->whereLike('message', "%{$searchTerm}%");
        }

        // Manually apply pagination
        if (!$isCount) {
            if ($args['post_per_page'] !== -1) {
                $offset = ($args['paged'] - 1) * $args['post_per_page'];
                $query->offset($offset);
                $query->limit($args['post_per_page']);
            }
        }

        // Execute the query to fetch records before applying date filtering
        $items = $query->execute();

        if (!empty($args['date']) && !$isCount) {
            $dates = explode(' - ', sanitize_text_field(wp_unslash($args['date'])));
            if (count($dates) == 2) {
                $startDate = new \DateTime($dates[0]);
                $endDate = new \DateTime($dates[1]);
                $items = array_filter($items, function ($item) use ($startDate, $endDate) {
                    $itemDate = $item->getTimestamp();
                    return $itemDate >= $startDate && $itemDate <= $endDate;
                });
            }
        }

        // Return count for pagination if requested
        if ($isCount) {
            return count($items);
        }

        return $items;
    }


    /**
     * delete - delete all log files
     *
     * @param false $deleted_only - only delete lines from deleted mail logs
     */
    public static function delete($deleted_only = false)
    {
        $upload = wp_upload_dir();
        // Get all directories in logs path
        $log_directories = self::get_directories($upload['basedir'] . '/rtm-mail/logs');
        // Array to save every log file path
        $log_paths = [];
        foreach ($log_directories as $directory) {
            // Scan for files in each directory
            $directory_files = array_diff(scandir($directory), [ '.', '..' ]);
            foreach ($directory_files as $log_file) {
                // For every file check if it has a log extension
                $ext = explode('.', $log_file);
                if (! empty($log_file) && isset($ext[1]) && strtolower($ext[1]) === 'log') {
                    // Add to paths array
                    $log_paths[] = $directory . '/' . $log_file;
                }
            }
        }
        // Check if only to remove deleted mail logs
        if (! $deleted_only) {
            foreach ($log_paths as $file_path) {
                unlink($file_path);
            }
        } else {
            // Get all deleted mail logs
            $deleted_logs = self::get([
                'post_per_page' => null,
                'search_filter' => [ 'message' => 'on' ],
                's'             => 'deleted'
            ]);
            // Loop through all logs and paths
            foreach ($deleted_logs as $mail_log) {
                foreach ($log_paths as $file_path) {
                    // Get content of log file
                    $file = file_get_contents($file_path);
                    // Get every line
                    $lines     = explode("\n", str_replace("\\r\\n", "\n", $file));
                    $new_lines = [];
                    // Loop over every line
                    foreach ($lines as $line) {
                        // Check if the current log_id contains in this line
                        if (strpos($line, '"log_id":"' . $mail_log['context']['log_id'] . '"')) {
                            // Skip this line
                            continue;
                        }
                        // Add line to the new lines if its not empty
                        if (! empty($line)) {
                            $new_lines[] = $line;
                        }
                    }
                    // Create new file content
                    $new_file = implode("\n", $new_lines);
                    // Set new file content
                    file_put_contents($file_path, $new_file);
                }
            }
        }
    }

    /**
     * get_total_rows - Get total amount of rows
     * @return int|void
     */
    public static function get_total_rows($args = [])
    {
        $args = array_merge($args, [ 'post_per_page' => - 1 ]);

        return self::get($args, true);
    }
}
