<?php

namespace App\Traits;
use Carbon\Carbon;
use App\Models\Admin\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\Admin\EmailHost;
use App\Models\Admin\SmsHost;
use App\Models\Admin\NotificationHost;
use App\Models\Admin\Email_templates;
use App\Mail\SingleMail;
use App\helpers\Malath_SMS;
use App\Models\Admin\NotificationTemplate;
use Mail;
use Response;
use Validator;
use Config;
use App\Models\Project\Alerts;
use Spatie\Activitylog\Models\Activity;

trait CommunicationTrait
{
    public function SendSingleMail($request)
    {
        //dd($request['subject']);
        if(isset($request['uid']) && !empty($request['uid'])){
            if (isset($request['hosts']) && !empty($request['hosts'])) {
              $host = EmailHost::where('id', $request['hosts'])->first();
            } else{
              $host = EmailHost::where('is_default', '1')->first();
            }
            /* checking cc and bcc email status */
            $cc_email=$bcc_email="";
            if ($host->cc_status == 1) {
              $cc_email = $host->cc_email;
            }
      
            if ($host->bcc_status == 1) {
              $bcc_email = $host->bcc_email;
            }
            /*set env*/
            Config::set('MAIL_HOST', $host->name);
            Config::set('MAIL_PORT', $host->port);
            Config::set('MAIL_USERNAME', $host->username);
            Config::set('MAIL_PASSWORD', $host->secret);
            Config::set('MAIL_ENCRYPTION', $host->security);
            Config::set('MAIL_FROM_ADDRESS', $host->from_email);
            Config::set('MAIL_FROM_NAME', $host->from_name);
      
            if (!empty($request['subject']) && !empty($request['message'])) {
              $subject = trim($request['subject']);
              $msg = trim($request['message']);
              $files = $request['attach'];
                try{
                    $username = getAny('name', 'users', 'id', $request['uid']);
                    $email = getAny('email', 'users', 'id', $request['uid']);
                    if (isset($request['template']) && !empty($request['template'])) {
                        $template = Email_templates::where('id', $request['template'])->first();
                        $params = explode(',', $template->params);
                        foreach ($params as $value) {
                            $msg = str_replace($value, $username, $msg);
                        }
                    } else{
                      $msg = str_replace('{{username}}', $username, $msg);
                    }
                  $data2 = [
                    'email' => $email,
                    'username' => $username,
                    'subject' => $subject,
                    'content' => $msg,
                    'from_name' => $host->from_name,
                    'from_email' => $host->from_email,
                  ];
                  Mail::to($email, $username)
                  ->cc($cc_email)
                  ->bcc($bcc_email)
                  ->send(new SingleMail($data2, $files));
                  $message = trans('admin.Mail_has_been_send');
                }catch(Exception $ex){
                    $message = trans('admin.Connection_Fail');
                }
                activity('Mail Send')
                ->causedBy(Auth::user())
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Email Send by ' . Auth::user()->name.' to '.$data2['email']);   
                echo json_encode(array('text' => $message, 'cls' => 'success'));
            } else{
              echo json_encode(array('text' => trans('admin.write_somethings'), 'cls' => 'warn'));
            }
        } else{
            echo json_encode(array('text' => trans('admin.user_not_found'), 'cls' => 'info'));
        }
    }

    // notification
    public function SendSingleNotification($request)
    {
        if (!$request['uid']) {
            echo json_encode(array('text' => 'Make sure all requested information are complete', 'cls' => 'error'));
        }
        $validator = Validator::make($request, [
            'uid' => 'required|integer',
            'title' => 'required',
            'message' => 'required',
        ]);
    
        if ($validator->fails()) {
            echo json_encode(array('text' => 'Make sure all requested information are complete(title, message, user id)', 'cls' => 'error'));
        } else {
            /*host*/
            if (isset($request['hosts']) && !empty($request['hosts'])) {
                $host = NotificationHost::where('id', $request['hosts'])->first();
            } else{
                $host = NotificationHost::where('is_default', '1')->first();
            }
            $serverkey = $host->serverkey;
        
            // dd($request->all());
            $token = getToken($request['uid'], 'ios');
            if ($token != "") {
                sendNotification($token, $request['title'], $request['message'], $serverkey);
            }
    
            $token = getToken($request['uid'], 'android');
            if ($token != "") {
                sendNotification($token, $request['title'], $request['message'], $serverkey);
            }
            $alert_entry = [
                'user_id' => $request['uid'] ,
                'ref_id' => 0,
                'title' =>  $request['title'],
                'title_ar' => $request['title'],
                'description' => $request['message'],
                'description_ar' => $request['message'],
                'alert_type' => 4,
                'created_at' => Carbon::now(),
            ];
            Alerts::insert($alert_entry);

            activity('Notification Send')
            ->causedBy(Auth::user())
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Notification Send by ' . Auth::user()->name);
            echo json_encode(array('text' => 'Notification sent Successfully', 'cls' => 'success'));
        }
    }

    // send sigle sms
    public function SendSingleSms($request)
    {
        if(isset($request['uid']) && !empty($request['uid'])){
            if (isset($request['hosts']) && !empty($request['hosts'])) {
              $host = SmsHost::where('id', $request['hosts'])->first();
            } else{
              $host = SmsHost::where('is_default', '1')->first();
            }
            /*host setting*/
        
            if (!empty($request['title']) && !empty($request['title'])) {
              $title = trim($request['title']);
              $message = trim($request['title']);
              try{
                  $username = getAny('name', 'users', 'id', $request['uid']);
                  $mobile = getAny('mobile', 'users', 'id', $request['uid']);
                  /*mobile sms sending api*/
                  if ($host->slug == "malath_sms_api") {
                      $DTT_SMS    = new Malath_SMS($host->username, $host->secret, 'UTF-8');
                      $Credits    = $DTT_SMS->GetCredits();
                      $SenderName = $DTT_SMS->GetSenders();
                      $CheckUser  = $DTT_SMS->CheckUserPassword();
                      $SmS_Msg    = $message;
                      $Originator = $host->mask;
                      $Send = $DTT_SMS->Send_SMS($mobile, $Originator, $SmS_Msg, $CheckUser);
                  }
                  $msg = 'Message has been send';
              }catch(Exception $ex){
                  $msg = trans('admin.Connection_Fail');
              }
              activity('SMS Send')
                ->causedBy(Auth::user())
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('SMS Send by ' . Auth::user()->name);
              echo json_encode(array('text' => $msg, 'cls' => 'success'));
            } else{
              echo json_encode(array('text' => trans('admin.write_somethings'), 'cls' => 'warn'));
            }
        } else{
            echo json_encode(array('text' => trans('admin.Select_user'), 'cls' => 'info'));
        }
    }

    // for alertting, for using inside methods
    // notification
    public function SendAlertNotification($request)
    {
        /*host*/
        $host = NotificationHost::where('is_default', '1')->first();
        $serverkey="";
        if (!empty($host)) {
            $serverkey = $host->serverkey;
        }    
        // dd($request->all());
        $token = getToken($request['uid'], 'ios');
        if ($token != "") {
            sendNotification($token, $request['title'], $request['message'], $serverkey);
        }

        $token = getToken($request['uid'], 'android');
        if ($token != "") {
            sendNotification_andriod($token, $request['title'], $request['message'], $serverkey,$request['type'],$request['apptype'],$request['ref_id']);
        }
        // activity
       /* activity('Notification Send')
        ->causedBy(Auth::user())
        ->log('Notification Send by ' . Auth::user()->name);*/
    }

    public function SendAlertMail($request)
    {
        //dd($request['subject']);
        if(isset($request['uid']) && !empty($request['uid'])){
            $host = EmailHost::where('is_default', '1')->first();
            /* checking cc and bcc email status */
            $cc_email=$bcc_email="";
            if ($host->cc_status == 1) {
              $cc_email = $host->cc_email;
            }
      
            if ($host->bcc_status == 1) {
              $bcc_email = $host->bcc_email;
            }
            /*set env*/
            Config::set('MAIL_HOST', $host->name);
            Config::set('MAIL_PORT', $host->port);
            Config::set('MAIL_USERNAME', $host->username);
            Config::set('MAIL_PASSWORD', $host->secret);
            Config::set('MAIL_ENCRYPTION', $host->security);
            Config::set('MAIL_FROM_ADDRESS', $host->from_email);
            Config::set('MAIL_FROM_NAME', $host->from_name);
      
            $msg = trim($request['description']);
            try{
                $subject="Transaction";
                $username = getAny('name', 'users', 'id', $request['uid']);
                $email = getAny('email', 'users', 'id', $request['uid']);
                $template = Email_templates::where('slug', 'payment_mail')->first();
                if (isset($template) && !empty($template)) {                    
                    $params = explode(',', $template->params);
                    foreach ($params as $value) {
                        $msg = str_replace($value, $username, $msg);
                        $msg = str_replace($value, $msg, $template->content);
                    }
                    $subject=$template->subject;
                } else{
                    $msg = str_replace('{{username}}', $username, $msg);
                    $msg = str_replace('{{message}}', $msg, $template->content);
                }
                $data2 = [
                'email' => $email,
                'username' => $username,
                'subject' => $subject,
                'content' => $msg,
                'from_name' => $host->from_name,
                'from_email' => $host->from_email,
                ];
                Mail::to($email, $username)
                ->cc($cc_email)
                ->bcc($bcc_email)
                ->send(new SingleMail($data2));
                $message = trans('admin.Mail_has_been_send');
            }catch(Exception $ex){
                $message = trans('admin.Connection_Fail');
            }
            activity('Payment Mail Send')
            ->causedBy(Auth::user())
            ->log('Payment Email Send by ' . Auth::user()->name.' to '.$data2['email']);   
            //echo json_encode(array('text' => $message, 'cls' => 'success'));
        }
    }
}