<?php
namespace EasyChat\Controller;

use EasyChat\Library\PresenceService;
use EasyChat\Library\ResponseTimeMetrics;
use EasyChat\Library\Messenger\ChannelCatalog;

class Analytics extends Base {

    protected $layouts = 'layout';

    public function index() {
        if (!isset(\EasyChat\Library\RequestContext::session()['manager_id'])) {
            header('Location: index.php?route=auth/login');
            exit;
        }

        $this->vars['title'] = 'Аналитика | EasyChat';

        $db = $this->registry->get('db');
        $prefix = easychat_db_prefix();
        $response_metrics = new ResponseTimeMetrics($this->registry);

         
        $total_chats_q = $db->query("SELECT COUNT(*) AS total FROM `{$prefix}sessions`");
        $total_chats = (int)$total_chats_q->row['total'];

        $msg_stats_q = $db->query("
            SELECT 
                SUM(CASE WHEN author = 1 THEN 1 ELSE 0 END) AS client_msg,
                SUM(CASE WHEN author = 2 THEN 1 ELSE 0 END) AS operator_msg,
                SUM(CASE WHEN author = 3 THEN 1 ELSE 0 END) AS ai_msg
            FROM `{$prefix}messages`
        ");
        
        $client_msg = (int)($msg_stats_q->row['client_msg'] ?? 0);
        $operator_msg = (int)($msg_stats_q->row['operator_msg'] ?? 0);
        $ai_msg = (int)($msg_stats_q->row['ai_msg'] ?? 0);

         
         
        $avg_frt = (float)$response_metrics->getGlobalAverageSeconds(0);

         
        if ($avg_frt <= 0) {
            $formatted_frt = '—';
        } elseif ($avg_frt < 60) {
            $formatted_frt = round($avg_frt) . ' сек';
        } else {
            $min = floor($avg_frt / 60);
            $sec = round($avg_frt % 60);
            $formatted_frt = $min . ' мин ' . $sec . ' сек';
        }

         
        $daily_data_map = [];
        for ($i = 29; $i >= 0; $i--) {
            $date_key = date('Y-m-d', strtotime("-$i days"));
            $daily_data_map[$date_key] = 0;
        }

        $daily_chats_q = $db->query("
            SELECT DATE(date_added) AS date, COUNT(*) AS count 
            FROM `{$prefix}sessions` 
            WHERE date_added >= DATE(DATE_SUB(NOW(), INTERVAL 29 DAY)) 
            GROUP BY DATE(date_added) 
            ORDER BY DATE(date_added) ASC
        ");
        
        foreach ($daily_chats_q->rows as $row) {
            $date_key = date('Y-m-d', strtotime($row['date']));
            if (isset($daily_data_map[$date_key])) {
                $daily_data_map[$date_key] = (int)$row['count'];
            }
        }

        $daily_chats_labels = [];
        $daily_chats_data = [];
        foreach ($daily_data_map as $date_key => $count) {
            $daily_chats_labels[] = date('d.m', strtotime($date_key));
            $daily_chats_data[] = $count;
        }

         
        $hourly_chats_q = $db->query("
            SELECT HOUR(date_added) AS hour, COUNT(*) AS count 
            FROM `{$prefix}sessions` 
            GROUP BY HOUR(date_added) 
            ORDER BY hour ASC
        ");
        
        $hourly_chats_labels = [];
        $hourly_chats_data = array_fill(0, 24, 0);  
        foreach ($hourly_chats_q->rows as $row) {
            $hour = (int)$row['hour'];
            $hourly_chats_data[$hour] = (int)$row['count'];
        }
        for ($i = 0; $i < 24; $i++) {
            $hourly_chats_labels[] = sprintf('%02d:00', $i);
        }

         
        $operator_stats_q = $db->query("
            SELECT m.id, m.name, COUNT(msg.message_id) AS count 
            FROM `{$prefix}managers` m 
            LEFT JOIN `{$prefix}messages` msg ON msg.manager_id = m.id AND msg.author = 2 
            GROUP BY m.id 
            ORDER BY count DESC
        ");
        
        $operator_labels = [];
        $operator_data = [];
        foreach ($operator_stats_q->rows as $row) {
            $operator_labels[] = $row['name'];
            $operator_data[] = (int)$row['count'];
        }

         
        $manager_frt_map = $response_metrics->getManagerHumanAverageMap();
        $leaderboard_q = $db->query("
            SELECT 
                m.id, 
                m.name, 
                m.image,
                m.status,
                m.last_active,
                (SELECT COUNT(DISTINCT msg.chat_id) FROM `{$prefix}messages` msg WHERE msg.manager_id = m.id AND msg.author = 2) AS active_chats,
                (SELECT COUNT(*) FROM `{$prefix}messages` msg WHERE msg.manager_id = m.id AND msg.author = 2) AS total_messages
            FROM `{$prefix}managers` m
            ORDER BY total_messages DESC
        ");

        $leaderboard = [];
        $presence = new PresenceService($this->registry);
        foreach ($leaderboard_q->rows as $row) {
            $manager_id = (int)$row['id'];
            $op_frt = isset($manager_frt_map[$manager_id]) ? (float)$manager_frt_map[$manager_id] : 0.0;
            if ($op_frt <= 0) {
                $op_formatted_frt = '—';
            } elseif ($op_frt < 60) {
                $op_formatted_frt = round($op_frt) . ' сек';
            } else {
                $op_formatted_frt = floor($op_frt / 60) . 'м ' . round($op_frt % 60) . 'с';
            }

            $is_online = ((int)$row['status'] === 1 && $presence->isLastActiveOnline($row['last_active'] ?? '')) ? 1 : 0;

             
            $avatar_url = '';
            if (!empty($row['image']) && is_file(DIR_AVATARS . $row['image'])) {
                $avatar_url = HTTP_AVATARS . $row['image'];
            }

            $leaderboard[] = [
                'name'           => $row['name'],
                'avatar'         => $avatar_url,
                'status'         => $is_online,
                'active_chats'   => (int)$row['active_chats'],
                'total_messages' => (int)$row['total_messages'],
                'formatted_frt'  => $op_formatted_frt
            ];
        }

         
        $sources_q = $db->query("
            SELECT source_provider, COUNT(*) AS count 
            FROM `{$prefix}sessions` 
            GROUP BY source_provider
            ORDER BY count DESC
        ");
        
        $source_labels = [];
        $source_data = [];
        foreach ($sources_q->rows as $row) {
            $prov = strtolower(trim((string)($row['source_provider'] ?? '')));
            $label = ChannelCatalog::label($prov === '' ? 'widget' : $prov, true);
            
            $idx = array_search($label, $source_labels);
            if ($idx !== false) {
                $source_data[$idx] += (int)$row['count'];
            } else {
                $source_labels[] = $label;
                $source_data[] = (int)$row['count'];
            }
        }

         
        $this->vars['stats'] = [
            'total_chats'   => $total_chats,
            'client_msg'    => $client_msg,
            'operator_msg'  => $operator_msg,
            'ai_msg'        => $ai_msg,
            'formatted_frt' => $formatted_frt
        ];

        $this->vars['charts'] = [
            'daily_labels'    => json_encode($daily_chats_labels),
            'daily_data'      => json_encode($daily_chats_data),
            'hourly_labels'   => json_encode($hourly_chats_labels),
            'hourly_data'     => json_encode($hourly_chats_data),
            'operator_labels' => json_encode($operator_labels),
            'operator_data'   => json_encode($operator_data),
            'source_labels'   => json_encode($source_labels),
            'source_data'     => json_encode($source_data)
        ];

        $this->vars['leaderboard'] = $leaderboard;

        $this->template->view('analytics');
    }
}
