<?php

namespace App\Services\Commands;

use Exception;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SendCallStatsReportService
{
    private string $url;
    private string $channelName;
    private string $provinceId;
    private string $provinceName;
    public function __construct()
    {
        $this->url = config('ProvinceInfo.center_ip');
        $this->channelName = 'send_call_stats_report';
        $this->provinceId = config('ProvinceInfo.id');
        $this->provinceName = config('ProvinceInfo.name');
    }

    /**
     * @throws ConnectionException
     * @throws RequestException
     */
    public function execute(): void
    {
        try
        {
            $data = $this->prepare();
            Http::post($this->url, $data)->throw();
            Log::channel($this->channelName)->info(SendCallStatsReportService::class, [$this->provinceName, array_sum($data), 'successful']);
        }
        catch (Exception $e)
        {
            Log::channel($this->channelName)->error(SendCallStatsReportService::class, [$e->getMessage()]);
            throw $e;
        }
    }

    private function prepare(): array
    {
        $query = "SELECT
            {$this->provinceId} AS province_id,
            '{$this->provinceName}' AS province_name,
            date,
            total,
            route_to_teh4,
            route_to_teh5,
            route_to_os4,
            route_to_os5,
            answered,
            missed,
            answered_over10,
            dnd,
            transferred,
            talked_to_operator,
            c_agency,
            c_agency_driver,
            average_calls_time,
            (talked_to_operator - (answered + missed) + c_agency + c_agency_driver) AS fails
        FROM (
            SELECT
                DATE(calldate) AS date,
                COUNT(CASE WHEN recordingfile = '' OR recordingfile LIKE 'q-%' THEN 1 END) AS total,
                COUNT(CASE WHEN lastdata = 'IAX2/serverpeer/100' THEN 1 END) AS route_to_teh4,
                COUNT(CASE WHEN lastdata = 'IAX2/serverpeer/200' THEN 1 END) AS route_to_teh5,
                COUNT(CASE WHEN dst = '500' THEN 1 END) AS route_to_os4,
                COUNT(CASE WHEN dst = '600' THEN 1 END) AS route_to_os5,
                COUNT(CASE WHEN dcontext = 'from-internal' AND disposition = 'ANSWERED' AND dst BETWEEN 101 AND 104 THEN 1 END) AS answered,
                COUNT(CASE WHEN dcontext = 'from-internal' AND disposition = 'NO ANSWER' AND dst BETWEEN 101 AND 104 AND duration > 14 THEN 1 END) AS missed,
                COUNT(CASE WHEN dcontext = 'from-internal' AND disposition = 'ANSWERED' AND dst BETWEEN 101 AND 104 AND billsec > 9 THEN 1 END) AS answered_over10,
                COUNT(CASE WHEN lastapp = 'Busy' THEN 1 END) AS dnd,
                COUNT(CASE WHEN dst BETWEEN 502 AND 599 THEN 1 END) AS transferred,
                COUNT(CASE WHEN disposition <> 'BUSY' AND dst BETWEEN 101 AND 105 THEN 1 END) AS talked_to_operator,
                COUNT(CASE WHEN lastdata LIKE '%custom/agency%' THEN 1 END) AS c_agency,
                COUNT(CASE WHEN lastdata LIKE '%custom/agency-driver%' THEN 1 END) AS c_agency_driver,
                AVG(CASE WHEN dcontext = 'from-internal' AND disposition = 'ANSWERED' THEN billsec END) AS average_calls_time
            FROM asteriskcdrdb.cdr
            WHERE calldate >= NOW() - INTERVAL 3 DAY
            GROUP BY date
        )
        WHERE date >= DATE(NOW() - INTERVAL 3 DAY)";

        return DB::select($query);
    }
}
