<?php

namespace App\Repositories;

use App\Interfaces\OverageRepositoryInterface;
use Illuminate\Support\Facades\Http;

class OverageRepository implements OverageRepositoryInterface
{


   public function getGraph(string $whmcs_brand, int $whmcs_client_id, int $whmcs_service_id, string $whmcs_service_string, int $start, int $finish, int $commit, float $price, string $currency, int $version = 2, string $method = 'global'): array
   {

        $payload = [
            'start'     => $start,
            'finish'    => $finish,
            'commit'    => $commit,
            'price'     => $price,
            'unit'      => $currency,
            'brand'     => $whmcs_brand,
            'client'    => $whmcs_client_id,
            'service'   => $whmcs_service_id,
            'service_extra' => $whmcs_service_string,
            'flags'     => []
        ];

        if($method === 'australian') {
            $payload['flags'][] = 'au-agg';
        }

        // Retrieve raw data
        $graph_response = Http::timeout(300)->get(env('ENDPOINT_OVERAGE_MICROSERVICE_URL') . ( $version === 1 ? '/graph' : "/v$version/graph"), $payload);

        if($graph_response->status() === 200) {

            $raw_graphs = $version === 1 ? [ $graph_response->json() ] : $graph_response->json();
            $processed_graphs = [];

            foreach($raw_graphs as $graph) {

                if($version === 2) {

                    if($graph['captioning']['circuit_id'] === 'GSL-0') {
                        continue;
                    }

                    if($price == 0) {
                        unset($graph['captioning']['cost']);

                        $graph['captioning'] = [
                            ...$graph['captioning'],
                            'commit' => round($commit / 1000, 3),
                            'overage' => $graph['captioning']['circuit_id'] !== 'AGGREGATE' 
                                ? null 
                                : round(max(0, (abs($graph['95th']) - ($commit / 1000))), 3)
                        ];
                    }

                    $trend = round($graph['95th'], 3);
                    unset($graph['95th']); // Remove it from the source data
                    
                    $processed_graphs[] = [
                        ...$graph,
                        'start' => $start,
                        'end' => $finish,
                        'now' => $finish,
                        'trend' => $trend,
                        'categories' => [
                            ['name' => 'in', 'colour' => '#FF0000'],
                            ['name' => 'out', 'colour' => '#0000FF']
                        ]
                    ];

                }
                else {
                    
                    if($price == 0) {
                        unset($graph['captioning']['cost']);
                        unset($graph['captioning']['cids']);

                        $graph['captioning'] = [
                            ...$graph['captioning'],
                            'circuit_id'    => 'AGGREGATE',
                            'commit'        => round($commit / 1000, 3),
                            'overage'       => round(max(0, (abs($graph['95th']) - ($commit / 1000))), 3)
                        ];
                    }
                    else {
                        $graph['captioning']['circuit_id'] = 'AGGREGATE';
                    }

                    $trend = round($graph['95th'], 3);
                    unset($graph['95th']); // Remove it from the source data
                    
                    $processed_graphs[] = [
                        ...$graph,
                        'start' => $start,
                        'end' => $finish,
                        'now' => $finish,
                        'trend' => $trend,
                        'categories' => [
                            ['name' => 'bw_in', 'colour' => '#FF0000'],
                            ['name' => 'bw_out', 'colour' => '#0000FF']
                        ]
                    ];

                }

            }

            return $processed_graphs;
        }
        return [
            'categories' => [],
            'data' => [],
            'now' => time(),
            'start' => time(),
            'end' => time()
        ];

    }

   public function getValidOverage(string $whmcs_brand, int $whmcs_client_id, int $whmcs_service_id, string $whmcs_service_string, int $start, int $finish, int $commit, float $price, string $currency, string $method = 'global'): bool 
   {

        $payload = [
            'start'             => $start,
            'finish'            => $finish,
            'commit'            => $commit,
            'price'             => $price,
            'unit'              => $currency,
            'brand'             => $whmcs_brand,
            'client'            => $whmcs_client_id,
            'service'           => $whmcs_service_id,
            'service_extra'     => $whmcs_service_string,
            'flags'             => []
        ];

        if($method === 'australian') {
            $payload['flags'][] = 'au-agg';
        }

        $valid_response = Http::get(env('ENDPOINT_OVERAGE_MICROSERVICE_URL') . '/invoice', );

        return $valid_response->status() === 200;
   }

   public function postOverage(string $whmcs_brand, int $whmcs_client_id, int $whmcs_service_id, string $whmcs_service_string, int $start, int $finish, int $commit, float $price, string $currency, int $version = 2, string $method = 'global'): bool
   {

        $payload = [
            'start'             => $start,
            'finish'            => $finish,
            'commit'            => $commit,
            'price'             => $price,
            'unit'              => $currency,
            'brand'             => $whmcs_brand,
            'client'            => $whmcs_client_id,
            'service'           => $whmcs_service_id,
            'service_extra'     => $whmcs_service_string,
            'flags'             => []
        ];

        if($method === 'australian') {
            $payload['flags'][] = 'au-agg';
        }

        try {
            $valid_response = Http::timeout(600)->withHeaders(['Content-Type' => 'application/json'])->post(env('ENDPOINT_OVERAGE_MICROSERVICE_URL') . ( $version === 1 ? '/invoice' : "/v$version/invoice" ), $payload);
    
            return $valid_response->status() === 200;
        }
        catch(\Exception $ex) {
            \Log::debug($ex);
        }

        return false;
   }
}