<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;

class Shortio {

    public static function getUrl($link){
        if ($link) {

            if (!_env('APP_CONNECTION')){
                return $link;
            }

            $curl = curl_init();

            $payload = json_encode([
                'longDynamicLink' => "https://lnk.creditfair.in/?link=". $link,
                'suffix' => ['option' => 'SHORT']
            ]);

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=AIzaSyDZi7AW6ks8gryvVh9xtOl5yMGkbEmgnJs',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>$payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json'
                ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            $response = json_decode($response);
            if ($err) {
                return $link;
                //throw new \Exception('Short IO Error');
            } else {
                if (isset($response->shortLink)) {
                    return $response->shortLink;
                } else {
                    (new Slack(new Request(['title' => 'FireBase ShortLink Error', 'fields' => ['Response' => json_encode($response), 'Link' => $link], 'group' => Slack::$STAGE_TESTING])))->send();
                    //throw new \Exception('Short IO Error');
                    return $link;
                }
            }
        }

        if (empty($link)){
            return '';
        }

        throw new \Exception('Short IO Error');
    }

    // Short IO
    public static function getUrlShortIO($link){
        if ($link) {

            if (!_env('APP_CONNECTION')){
                return $link;
            }

            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://api.short.io/links",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => static::getPayload($link),
                CURLOPT_HTTPHEADER => array(
                    "authorization: " . _env('SHORT_PRIVATE'),
                    "content-type: application/json"
                ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);
            $response = json_decode($response);
            if ($err) {
                return $link;
                //throw new \Exception('Short IO Error');
            } else {
                if (isset($response->shortURL)) {
                    return $response->shortURL;
                } else {
                    //(new Slack(new Request(['title' => 'Short IO Error', 'fields' => ['Response' => json_encode($response), 'Link' => $link], 'group' => Slack::$STAGE_TESTING])))->send();
                    //throw new \Exception('Short IO Error');
                    return $link;
                }
            }
        }

        if (empty($link)){
            return '';
        }

        throw new \Exception('Short IO Error');
    }

    private static function getPayload($link){
        return json_encode([
            "domain" => 'link.creditfair.in',
            "originalURL" => $link,
            "title" => \request()->get('title') ?? 'Credit Fair',
            "tags" => [],
            "allowDuplicates" => false,
            "expiredURL" => \request()->getHost(),
            "iphoneURL" => $link,
            "androidURL" => $link,
            "utmSource" => \request()->get('source') ?? 'Credit Fair',
            "utmMedium" => \request()->get('medium') ?? 'Credit Fair',
            "utmCampaign" => \request()->get('campaign') ?? 'Credit Fair',
            "utmTerm" => \request()->get('term') ?? 'Credit Fair',
            "utmContent" => \request()->get('content') ?? 'Credit Fair',
            "cloaking" => 0,
            "redirectType" => 302
        ]);
    }
}
