<?php

namespace RtmMail\Helpers;

use DateTime;

/**
 * DashboardHelper - Helper for getting all dashboard data
 */
class DashboardHelper
{
    public static function get()
    {
        // Get global database object
        global $wpdb;
        // Set default data
        $data = [];
        // Get the last logged email
        $latest_log = LogHelper::get(['post_per_page' => 1]);
        // Get the last sent email
        $latest_sent_log = LogHelper::get([
            'post_per_page' => 1,
            'orderby' => 'sent',
            'order' => 'DESC',
            'where' => [
                'status' => [
                    'type' => '=',
                    'value' => 'sent',
                ]
            ],
        ]);
        // Get latest edited log
        $latest_updated_log = LogHelper::get([
            'post_per_page' => 1,
            'orderby' => 'updated',
            'order' => 'DESC',
        ]);

        // Get the last event
        $latest_event = EventHelper::get(['post_per_page' => 1]);
        // Get the last error
        $latest_error_event = EventHelper::get([
            'post_per_page' => 1,
            'filter_level' => 'on',
            'level_type' => 'error',
        ]);

        // Set the block data
        $data['blocks'] = [
            'emails_logged' => [
                'total' => LogHelper::get(
                    [
                    'post_per_page' => null,
                    'date' => date("Y-m-d") . ' - ' . date("Y-m-d"),
                    ],
                    true
                ),
                'latest' => isset($latest_log[0]) ? (new DateTime($latest_log[0]['created']))->format('d-m-Y H:i') : 'no date yet',
            ],
            'emails_sent' => [
                'total' => LogHelper::get(
                    [
                    'post_per_page' => null,
                    'date' => date("Y-m-d") . ' - ' . date("Y-m-d"),
                    'date_type' => 'sent',
                    ],
                    true
                ),
                'latest' => isset($latest_sent_log[0]) ? (new DateTime($latest_sent_log[0]['sent']))->format('d-m-Y H:i') : null,
            ],
            'events_logged' => [
                'total' => count(EventHelper::get([
                    'post_per_page' => null,
                    'date' => date("Y-m-d") . ' - ' . date("Y-m-d"),
                ])),
                'latest' => isset($latest_event[0]) ? $latest_event[0]['date']->format('d-m-Y H:i') : null,
            ],
            'errors_logged' => [
                'total' => count(EventHelper::get([
                    'post_per_page' => null,
                    'date' => date("Y-m-d") . ' - ' . date("Y-m-d"),
                    'filter_level' => 'on',
                    'level_type' => 'error',
                ])),
                'latest' => isset($latest_error_event[0]) ? $latest_error_event[0]['date']->format('d-m-Y H:i') : null,
            ],
        ];

        // Get all row counts by status
        $logs_row_count = $wpdb->get_results("SELECT COUNT(*) AS total, 
                                                    COUNT(CASE WHEN status = 'caught' THEN 1 END) AS caught, 
                                                    COUNT(CASE WHEN status = 'sent' THEN 1 END) AS sent, 
                                                    COUNT(CASE WHEN status = 'failed' THEN 1 END) AS failed 
                                                    FROM " . RTM_MAIL_TABLE_PREFIX . "logs;");
        // Set the logs info
        $data['logs_info'] = [
            'total' => $logs_row_count[0]->total,
            'caught' => $logs_row_count[0]->caught,
            'sent' => $logs_row_count[0]->sent,
            'failed' => $logs_row_count[0]->failed,
            'deleted_logs' => count(EventHelper::get(['post_per_page' => null, 'search_filter' => ['message' => 'on'], 's' => 'deleted'])),
            'last_added' => [
                'id' => isset($latest_log[0]) ? $latest_log[0]['id'] : null,
                'subject' => isset($latest_log[0]) ? $latest_log[0]['subject'] : null,
            ],
            'last_edited' => [
                'id' => isset($latest_updated_log[0]) ? $latest_updated_log[0]['id'] : null,
                'subject' => isset($latest_updated_log[0]) ? $latest_updated_log[0]['subject'] : null,
            ],
            'last_sent' => [
                'id' => isset($latest_sent_log[0]) ? $latest_sent_log[0]['id'] : null,
                'subject' => isset($latest_sent_log[0]) ? $latest_sent_log[0]['subject'] : null,
            ],
        ];

        // Set the event info
        $data['event_info'] = [
            'total' => count(EventHelper::get(['post_per_page' => null])),
            'notice' => count(EventHelper::get(['post_per_page' => null, 'filter_level' => 'on', 'level_type' => 'info'])),
            'debug' => count(EventHelper::get(['post_per_page' => null, 'filter_level' => 'on', 'level_type' => 'debug'])),
            'error' => count(EventHelper::get(['post_per_page' => null, 'filter_level' => 'on', 'level_type' => 'error'])),
            'recent_log' => [
                'log_id' => isset($latest_event[0]) && isset($latest_event[0]['context']['log_id']) ? $latest_event[0]['context']['log_id'] : null,
                'message' => isset($latest_event[0]) ? $latest_event[0]['message'] : null,
            ],
            'last_errors' => EventHelper::get(['post_per_page' => 5, 'filter_level' => 'on', 'level_type' => 'error']),
        ];

        // queue array
        $queue = [];
        // Loop to the current crons
        foreach (_get_cron_array() as $timestamp => $cron) {
            if (key($cron) === 'rtm_mail_send_log') {
                foreach ($cron as $schedules) {
                    foreach ($schedules as $schedule_data) {
                        $queue[] = [
                            'timestamp' => $timestamp,
                            'log_id' => $schedule_data['args'][0]
                        ];
                    }
                }
            }
        }

        // Filter queue by timestamp
        usort($queue, function ($a, $b) {
            return ($a['timestamp'] < $b['timestamp']) ? -1 : 1;
        });

        $data['queue_info'] = [
            'total' => count($queue),
            'latest' => (!empty($queue)) ? $queue[0] : null,
        ];

        return $data;
    }
}
