<?php

namespace Mtc\Plugins\MembersMessaging\Http\Controllers;

use Throwable;
use Mtc\Plugins\MembersMessaging\Models\Thread;
use Mtc\Plugins\MembersMessaging\Models\Message;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;

class ResponseTimes extends Controller {

    public static $response_times = [
        15 * \Util::SECONDS_IN_A_MINUTE => '< 15 min',
        1 * \Util::SECONDS_IN_A_HOUR => '15-60 min',
        2 * \Util::SECONDS_IN_A_HOUR => '1-2 hours',
        3 * \Util::SECONDS_IN_A_HOUR => '2-3 hours',
        6 * \Util::SECONDS_IN_A_HOUR => '3-6 hours',
        12 * \Util::SECONDS_IN_A_HOUR => '6-12 hours',
        1 * \Util::SECONDS_IN_A_DAY => '12-24 hours',
        2 * \Util::SECONDS_IN_A_DAY => '1-2 days',
        100 * \Util::SECONDS_IN_A_YEAR => '2+ days',
    ];

    private function getResponseTimeLabel($seconds) {
        foreach (self::$response_times as $max => $label) {
            if ($seconds <= $max) {
                return $label;
            }
        }

        return 'Unknown';
    }

    public function __invoke() {
        $threads = Thread::withTrashed()->get();

        $responses = $threads->map(function ($thread) {
            try {
                $seconds = $thread->calculateResponseTime();
                return $this->getResponseTimeLabel($seconds);
            } catch (Throwable) {
                return null;
            }
        })->filter();

        $grouped = $responses->countBy();

        $total = $grouped->sum();

        $data = $grouped->map(function ($count, $label) use ($total) {
            return [
                'label' => $label,
                'count' => $count,
                'percentage' => round(($count / $total) * 100, 1),
            ];
        })->values()->all();

        return app('twig')->render('membersmessaging/admin/response_times.twig', [
            // 'can_edit_templates' => Permissions::can(Permissions::EDIT_MESSAGE_TEMPLATES),
            'message_count' => $total,
            'response_data' => $data,
        ]);
    }
}
