<?php

namespace App;

use App\Http\Controllers\MicrosoftAuthController;
use App\Logging\CloudWatchLoggerFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Slack{

    public $ms_auth_user_id = 27;
    private $request;
    private $payload;
    private $field = [];
    private $endPoint = '';
    private $techBug = 'https://hooks.slack.com/services/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';
    private $prodTechBug = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:6777aace064f42b1ae6250675cc5fe21@thread.tacv2/messages';
    public static $PROD_TECH_BUG = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:6777aace064f42b1ae6250675cc5fe21@thread.tacv2/messages';
    private $cosumerappgroup = 'https://hooks.slack.com/services/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';
    private $businessdevelopment = 'https://hooks.slack.com/services/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';
    public static $customer_documents = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:123d3e7e1a4a4e2f93d8299a71c6535f@thread.tacv2/messages';//'https://kmgcreditfair.webhook.office.com/webhookb2/30147ab2-ee16-46d0-8f94-25bb253479a0@525fc419-d89c-42af-bd40-496874a9fee5/IncomingWebhook/928510510eab4b75b10cf3be0dae692d/ae8181c7-c6a7-421d-b7b9-feb8320d122b/V2mPx1JA_TU-bqgp8UKhygWxNC20_2qRbp_G33hNWDsnI1';//https://hooks.slack.com/services/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';
    private $payment_collection = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:d6a16326987e48bdbdfaa6b8ef28b7bf@thread.tacv2/messages';//'https://kmgcreditfair.webhook.office.com/webhookb2/30147ab2-ee16-46d0-8f94-25bb253479a0@525fc419-d89c-42af-bd40-496874a9fee5/IncomingWebhook/a919e41283e144a0a0d0365979a15d14/ae8181c7-c6a7-421d-b7b9-feb8320d122b/V2eBFa1HQJE99prDp1SwR_hXeHWvlFlen1k0Ayq6uPEaQ1';//'https://hooks.slack.com/services/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';
    public static $application_reminder = 'https://hooks.slack.com/services/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';
    public static $PAYMENT_RECONCILIATION = 'https://hooks.slack.com/services/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';
    public static $DAILY_TASK = 'https://hooks.slack.com/services/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';
    public static $MERCHANT_ACTIVITY = 'https://hooks.slack.com/services/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';
    public static $HR = 'https://hooks.slack.com/services/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';
    public static $BIRTHDAY_REMINDER = 'https://hooks.slack.com/services/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';
    public static $TALLY_INTEGRATION = 'https://hooks.slack.com/services/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';
    public static $APPLICATIONS_THROUGH_CONSUMER_APP = 'https://hooks.slack.com/services/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';
    public static $INTERNAL_ERROR_HANDLER = 'https://hooks.slack.com/services/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';
    public static $CHAT_BOT = 'https://hooks.slack.com/services/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';
    public static $loan_disbursement_grp = 'https://hooks.slack.com/services/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';
    public static $STAGE_TESTING = 'https://hooks.slack.com/services/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';
    public static $JUSPAY_DIGIO = 'https://hooks.slack.com/services/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';
    public static $NACH_ERROR = 'https://hooks.slack.com/services/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';
    public static $DISBURSEMENT_QUERY = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:fNqNnM2y73Pm5UiOHQkHdtGBC2EdM-1ECzY7oPFjGlY1@thread.tacv2/messages';
    public static $CASE_REVIEWS = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:2fa97c3c8d994d2394ed35cdae844b84@thread.tacv2/messages';//'https://kmgcreditfair.webhook.office.com/webhookb2/30147ab2-ee16-46d0-8f94-25bb253479a0@525fc419-d89c-42af-bd40-496874a9fee5/IncomingWebhook/8c6556b30fe043a28e30fe2eccb1e091/ae8181c7-c6a7-421d-b7b9-feb8320d122b/V2wNGQ50mEG4a-T4aWL6mx5KxuYB99c2fbw1dXtS3eRRU1';//'https://hooks.slack.com/services/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';
    public static $CREDIT_DECISION = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:f39433cf31304c749d8b046e3ee7941a@thread.tacv2/messages';//'https://hooks.slack.com/services/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';
    public static $permissions_data_alerts = 'https://hooks.slack.com/services/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';
    public static $merchant_customer_review = 'https://graph.microsoft.com/v1.0/teams/30147ab2-ee16-46d0-8f94-25bb253479a0/channels/19:2181f8eb084b4b07ad729ae9923dfeff@thread.tacv2/messages';//'https://kmgcreditfair.webhook.office.com/webhookb2/30147ab2-ee16-46d0-8f94-25bb253479a0@525fc419-d89c-42af-bd40-496874a9fee5/IncomingWebhook/c4a12c13b60c46d5b3e970f05596bfb1/ae8181c7-c6a7-421d-b7b9-feb8320d122b/V2lSSyMyjLjb3rq1PLRZLOv5WlRml2huxJzWrCRnNDlRA1';//'https://hooks.slack.com/services/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';
    public static $accounting_entries = 'https://hooks.slack.com/services/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';
    public static $AVANSE_DISBURSEMENT = 'https://hooks.slack.com/services/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';
    public static $M_CONNECT = 'https://hooks.slack.com/services/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';
    public static $ABLF_UTR_UPDATE = 'https://hooks.slack.com/services/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';
    public static $CRED_TEAM_SOFT_APPROVAL = 'https://hooks.slack.com/services/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';
    public static $TECH_TEAMS = 'https://kmgcreditfair.webhook.office.com/webhookb2/30147ab2-ee16-46d0-8f94-25bb253479a0@525fc419-d89c-42af-bd40-496874a9fee5/IncomingWebhook/88e1f157759a419c9c3df164fe9addf9/ae8181c7-c6a7-421d-b7b9-feb8320d122b/V2jttioIGulH1exDafscWwrwl5VZ03_EHuIlItjX9mCbQ1';

    private $users = [];
    private $isMicroSoftTeams = true;
    private $headers = array(
        "Content-Type: application/x-www-form-urlencoded",
    );
    private $ms_mention_string = [];
    private $ms_mention_string_content = '';
    /**
     * @var string
     */
    private $ref_token = null;

    public function __construct(Request $request){
        $this->request = $request;
        $this->prepare();
    }

    public function prepare(){
        $this->setFields();
        $userString = $this->slackUsers($this->request->get('tagging'));
        $this->payload = ($this->request->has('payload')) ? $this->request->get('payload') : json_encode(array('text'=>$this->request->get('title'), "username" => (Auth::user()) ? Auth::user()->name : 'System','attachments'=>array(array('fields'=>$this->field), array('text' =>$userString))));
        if($this->request->has('group') && $this->request->get('group') == 'loan_application'){
            $this->endPoint = $this->cosumerappgroup;
        }else if($this->request->has('group') && $this->request->get('group') == 'businessdevelopment'){
            $this->endPoint = $this->businessdevelopment;
        }else if($this->request->has('group') && $this->request->get('group') == 'customer_documents'){
            $this->endPoint = self::$customer_documents;
        }else if($this->request->has('group') && $this->request->get('group') == 'payment_collection'){
            $this->endPoint = $this->payment_collection;
        }else if ($this->request->has('group')){
            $this->endPoint = $this->request->get('group');
        }
    }

    public function sendCWNotif(){
        $cwFactory = new CloudWatchLoggerFactory();
        $_title = array('message' => $this->request->get('title'));
        $_data = array_merge($_title, $this->request->get('fields'));
        $cwFactory->logger(json_encode($_data));
    }

    public function sendCWNotifWithData($message, $data){
        $cwFactory = new CloudWatchLoggerFactory();
        $_title = array('message' => $message);
        $_data = array_merge($_title, $data);
        $cwFactory->logger(json_encode($_data));
    }

    public function slackUsers($user){

        $userString = '';

        if($user) {
            $users = User::whereIn('id', $user)->get(['id', 'name', 'slack_id']);

            if ($users) {
                foreach ($users as $segment) {
                    if ($segment->slack_id) {
                        //$userString .= '<@' . $segment->slack_id . "|" . str_replace(' ', '',$segment->name) . '>';
                        $this->ms_mention_string[] = [
                            "id" => 0,
                            "mentionText" => $segment->name,
                            "mentioned" => [
                            "user" => [
                                "id" => $segment->slack_id,//"ae8181c7-c6a7-421d-b7b9-feb8320d122b",
                                "displayName" => $segment->name,
                                //"userPrincipalName" => "sunil@creditfair.in"
                                ]
                            ]
                        ];

                        $this->ms_mention_string_content .= "<at id=\"0\">".$segment->name."</at>";
                    }
                }
            }
        }

        // Get Access Token
        $this->ref_token = (new MicrosoftAuthController())->getAccessToken($this->ms_auth_user_id);
        //$this->sendCWNotifWithData('Slack Message Alert', ['ref_token' => json_encode($this->ref_token), 'title' => $this->request->get('title')]);

        //$this->ref_token = $userToken->access_token ?? $userToken;
        //End
        //return $userString ? 'Please acknowledge '.$userString : '';
        return '';
    }

    public function setFields(){
        foreach ($this->request->get('fields') as $title=>$field){
            if ($title && $field)
                $this->field[] = array('title' => ucwords(str_replace('_',' ',$title)), "value" => $field, "short" => true);
        }

        if (!$this->request->has('hide_footer') || !$this->request->get('hide_footer')) {
            $this->field[] = array('title'=>'ENV', 'value' => (env('APP_CONNECTION') == 0) ? 'Staging' : 'Production','short'=>true);
        }
    }

    public function send(){
        if ($this->ms_mention_string && !$this->ref_token){
            return true;
        }

        if (in_array($this->endPoint, [$this->payment_collection, self::$CASE_REVIEWS, self::$DISBURSEMENT_QUERY, self::$customer_documents, self::$merchant_customer_review, self::$CREDIT_DECISION, self::$PROD_TECH_BUG])){
            // Pass
        }else{ //in_array($this->endPoint, [self::$BIRTHDAY_REMINDER, self::$NACH_ERROR,self::$application_reminder,self::$CREDIT_DECISION,self::$customer_documents,self::$APPLICATIONS_THROUGH_CONSUMER_APP,self::$MERCHANT_ACTIVITY,self::$JUSPAY_DIGIO,self::$AVANSE_DISBURSEMENT,self::$STAGE_TESTING, self::$PROD_TECH_BUG, $this->techBug, $this->prodTechBug, self::$M_CONNECT, self::$CREDIT_DECISION, $this->businessdevelopment])
            $this->sendCWNotif();
            return true;
        }

        if ((env('APP_CONNECTION') == 0) || empty($this->endPoint)) {
            $this->endPoint = $this->techBug;
            return true;
        }

        if ($this->endPoint == $this->techBug && env('APP_CONNECTION')){
            $this->endPoint = $this->prodTechBug;
            return true;
        }

        try {
            //$this->sendCWNotifWithData('Slack Message Alert', ['header' => json_encode($this->headers), 'payload' => $this->getPayload(), 'title' => $this->request->get('title')]);
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPoint,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->getPayload(),
                CURLOPT_HTTPHEADER => $this->headers,
            ));

            $res = curl_exec($curl);
            $err = curl_error($curl);
            //$this->sendCWNotifWithData('Slack Message Alert', ['res' => json_encode($res), 'error' => $err, 'title' => $this->request->get('title')]);
            curl_close($curl);
        }catch (\Exception $e){}
    }

    private function getPayload(){
        if ($this->isMicroSoftTeams){
            return json_encode($this->getMSTeamsPayloadV1());
            //return json_encode($this->getMSTeamsPayload());
        }
        return "payload=" . $this->payload;
    }

    private function getMSTeamsPayload(){
        $this->headers = array("Content-Type: application/json");

        $content = [
            '$schema' => "http =>//adaptivecards.io/schemas/adaptive-card.json",
            "type" => "AdaptiveCard",
            "version" => "1.2",
            "body" => [
                [
                    "type" => "TextBlock",
                    "text" => $this->request->get('title'),
                    "weight" => "bolder"
                ],
                [
                    "type" => "TextBlock",
                    "text" => 'By '.((Auth::user()) ? Auth::user()->name : 'System')
                ],
                [
                    "type" => "FactSet",
                    "facts" => $this->field
                ]
            ]
        ];

        /*$content['msteams'] = [
                "entities" => [
                    [
                        "type" => "mention",
                        "text" => "<at>John Doe</at>",
                        "mentioned" => [
                            "id" => "29:123124124124",
                            "name" => "John Doe"
                        ]
                    ]
                ]
        ];*/

        return [
            "type" => "message",
            "attachments" => [
                [
                    "contentType" => "application/vnd.microsoft.card.adaptive",
                    "content" => $content
                ]
            ]
        ];
    }


    public function getMSTeamsPayloadV1(){

        //$this->sendCWNotifWithData('Slack Message Alert', ['Auth Header' => $this->ref_token]);

        $this->headers = array("Content-Type: application/json", "Authorization: Bearer ".$this->ref_token);

        $field_string = '';
        foreach($this->field as $field){
            $field_string .= "<tr><td style='width:100px; vertical-align:top;'><b>".$field['title'].":</b></td><td>".$field['value']."</td></tr>";
        }

        if (!$this->request->has('hide_footer') || !$this->request->get('hide_footer')) {
            $field_string .= "<tr><td style='width:100px; vertical-align:top;'><b>By:</b></td><td>".((Auth::user()) ? Auth::user()->name : 'System')."</td></tr>";
        }


        $tableHtml = '';
        if (!empty($field_string)) {
            $tableHtml = "<br /><br /> <table style='border-collapse:collapse;border-color:#292929;'>".$field_string."</table>";
        }
        $content = "<div style='font-family:Segoe UI, sans-serif; font-size:14px;'> <b>".$this->request->get('title')."</b>".$tableHtml." </div>";
        if (!empty($this->ms_mention_string_content)) {
            $content .= "<br />".$this->ms_mention_string_content;
        }

        $payload = [
            "body" => [
                "contentType" => "html",
                "content" => $content
            ]
        ];

        if ($this->ms_mention_string) {
            $payload["mentions"] = $this->ms_mention_string;
        }

        return $payload;
    }

    public function send_dm(){

        // $this->payload = ($this->request->has('payload')) ? $this->request->get('payload') : json_encode(array('attachment'=>json_encode($this->request->get('fields')), "channel" => $this->request->get('channel')));
        $this->payload = ($this->request->has('payload')) ? $this->request->get('payload') : json_encode(array('channel'=>$this->request->get('channel'), 'text' => $this->request->get('title'), 'attachments'=>array(array('fields'=>$this->field))));

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://slack.com/api/chat.postMessage",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $this->payload,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "Authorization: Bearer ".env('SLACK_DM_AUTH')
            ),
        ));

        $res = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
    }
}
