<?php

namespace App\Lib;

use App\Constants\Status;

class ResponseTime
{
    public static function getFirstResponseTime($supportTickets, $agentReply = true, $adminId = 0)
    {
        $data = [];

        foreach ($supportTickets as $supportTicket) {
            
            if ($agentReply) {
                if ($adminId) {
                    $reply = $supportTicket->replies->where('is_private', Status::NO)->where('auto_response', Status::NO)->where('admin_id', $adminId)->first();
                } else {
                    $reply = $supportTicket->replies->where('is_private', Status::NO)->where('auto_response', Status::NO)->where('admin_id', '!=', 0)->first();
                }

                $message = $reply ? $supportTicket->replies->where('is_private', Status::NO)->where('auto_response', Status::NO)->where('admin_id', 0)->where('id', '<', $reply->id)->first() : null;
            } else {
                $message = $supportTicket->replies->where('is_private', Status::NO)->where('auto_response', Status::NO)->where('admin_id', '!=', 0)->first();
                $reply   = $message ? $supportTicket->replies->where('is_private', Status::NO)->where('auto_response', Status::NO)->where('admin_id', 0)->where('id', '>', $message->id)->first() : null;
            }

            if ($reply && $message) {
                $dateFormat = showDateTime($message->created_at, 'd M');

                if (!array_key_exists($dateFormat, $data)) {
                    $data[$dateFormat]['first_reply_duration'] = 0;
                    $data[$dateFormat]['total_first_reply']    = 0;
                }

                $data[$dateFormat]['first_reply_duration'] += abs($message->created_at->diffInSeconds($reply->created_at, true));
                $data[$dateFormat]['total_first_reply']++;
            }
        }

        $result = [
            'keys'   => [],
            'values' => [],
        ];

        $totalDuration = 0;
        $totalReplies  = 0;

        foreach ($data as $date => $values) {
            $avg                = $values['total_first_reply'] ? ($values['first_reply_duration'] / $values['total_first_reply']) : 0;
            $result['keys'][]   = $date;
            $result['values'][] = round($avg, 2);

            $totalDuration += $values['first_reply_duration'];
            $totalReplies += $values['total_first_reply'];
        }

        $result['avg_first_response'] = $totalReplies ? $totalDuration / $totalReplies : 0;
        return $result;
    }

    public static function getAvgResponseTime($supportTickets, $agentReply = true, $adminId = 0)
    {
        $totalReply    = 0;
        $totalDuration = 0;

        foreach ($supportTickets as $supportTicket) {
            $replies = $supportTicket->replies->where('is_private', Status::NO)->where('auto_response', Status::NO);
            foreach ($replies as $reply) {
                if ($agentReply) {
                    if (($adminId == 0 && $reply->admin_id > 0) || ($adminId && $reply->admin_id == $adminId)) {
                        $message = $replies->where('admin_id', 0)->where('id', '<', $reply->id)->sortByDesc('id')->first();
                        if ($message) {
                            $totalReply++;
                            $totalDuration += abs($message->created_at->diffInSeconds($reply->created_at));
                        }
                    }
                } else {
                    if ($reply->admin_id == 0) {
                         $message = $replies->where('admin_id', '!=', 0)->where('id', '<', $reply->id)->sortByDesc('id')->first();
                         if ($message) {
                            $totalReply++;
                            $totalDuration += abs($message->created_at->diffInSeconds($reply->created_at));
                        }
                    }
                }
            }
        }

        $avgDuration = $totalReply ? $totalDuration / $totalReply : 0;
        return $avgDuration;
    }

    public static function getResolutionTime($supportTickets, $createdTime = true, $adminId = 0, $dateWise = false)
    {
        $supportTickets->load(['ticketLogs' => function ($log) use ($adminId) {
            $log->whereIn('remark', ['assigned', 'closed']);
        }]);

        if ($dateWise) {
            $data = [];
        } else {
            $totalSolved   = 0;
            $totalDuration = 0;
        }

        foreach ($supportTickets as $supportTicket) {
            if ($adminId) {
                $log = $supportTicket->ticketLogs->where('remark', 'assigned')->where('assign_staff_id', $adminId)->first();
            } elseif (!$createdTime) {
                $log = $supportTicket->ticketLogs->where('remark', 'assigned')->first();
            } else {
                $log = $supportTicket;
            }

            $solvedLogs = $supportTicket->ticketLogs->where('remark', 'closed');

            if ($adminId) {
                $solvedLogs = $solvedLogs->where('assign_staff_id', $adminId);
            }

            $solved = $solvedLogs->sortByDesc('id')->first();

            if ($solved && $log) {
                if ($dateWise) {
                    $date = $solved->created_at->format('d-M-Y');
                    if (!array_key_exists($date, $data)) {
                        $data[$date]['total_solved']   = 0;
                        $data[$date]['total_duration'] = 0;
                    }
                    $data[$date]['total_solved']++;
                    $data[$date]['total_duration'] += abs($log->created_at->diffInSeconds($solved->created_at));
                } else {
                    $totalSolved++;
                    $totalDuration += abs($log->created_at->diffInSeconds($solved->created_at));
                }
            }
        }

        if ($dateWise) {
            $result = [
                'keys'   => [],
                'values' => [],
            ];
            $totalDuration = 0;
            $totalSolved   = 0;

            uksort($data, function ($a, $b) {
                return \DateTime::createFromFormat('d-M-Y', $a) <=> \DateTime::createFromFormat('d-M-Y', $b);
            });

            foreach ($data as $date => $values) {
                $avg                = $values['total_solved'] ? ($values['total_duration'] / $values['total_solved']) : 0;
                $result['keys'][]   = now()->parse($date)->format('d M');
                $result['values'][] = round($avg, 2);

                $totalDuration += $values['total_duration'];
                $totalSolved += $values['total_solved'];
            }

            return [
                'avg_resolution' => $totalSolved ? $totalDuration / $totalSolved : 0,
                'keys'           => $result['keys'],
                'values'         => $result['values'],
            ];
        } else {
            $avgDuration = $totalSolved ? $totalDuration / $totalSolved : 0;
            return $avgDuration;
        }

    }

}
