<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Http\Helper\Helper;

class ContactAdd extends Notification
{
    use Queueable;
    private $email_template;
    private $notify_email_template;


    /**
     * Create a new notification instance.
     */
    public function __construct($email_template, $notify_email_template)
    {
        $this->email_template = $email_template;
        $this->notify_email_template = $notify_email_template;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {        
        // need to get customfields associat with contact so find contact
        $contact = \App\Models\Contact::findOrFail($notifiable->id);

        $settings = \DB::table('settings')->whereId(config('custom.app_id'))->first();
        $connection = Helper::configureSendingNode($settings->sending_type, $settings->sending_attributes);

          if(empty($settings->from_email)) {
            session()->flash('error', str_replace('[email]', $contact->email, __('app.no_email_set_for_settings')));
            return new MailMessage();
          }

          if($connection['success']) {
            // If Unsubscribe Email is set to 'Yes' for a list
            if($contact->list->welcome_email == 'Yes' || $contact->list->unsub_email == 'Yes') {
              // send email to contact 
              $send_email = false; //' It may possilbe one option is true other false
              // Run old emails that have no value set
              if($this->email_template == 'welcome-email' && $contact->list->welcome_email == 'Yes') {
                $page = \App\Models\EmailsPage::whereSlug($this->email_template)->whereAppId($contact->app_id)->first();
                $send_email = true;
              } elseif($this->email_template == 'unsub-email' && $contact->list->unsub_email == 'Yes') {
                $page = \App\Models\EmailsPage::whereSlug($this->email_template)->whereAppId($contact->app_id)->first();
                    $send_email = true;
              }

              if($send_email) {
                $from_email = $settings->from_email;
                $from_name = $settings->from_name;
                // get sending domain from email
                $sending_domain = Helper::getSendingDomainFromEmail($from_email);

                // Tracking domain would be app_url for the notification emails
                $tracking_domain = $settings->app_url;
                $message_id = Helper::getCustomMessageID($tracking_domain);
                

                $data_values = [
                  'sender-name'    => $from_name,
                  'sender-email'   => $from_email,
                  'domain'         => $tracking_domain,
                  'message-id'     => $message_id,
                ];
                $content = Helper::replaceSpintags(Helper::decodeString($page->content)); // replace spintags
                $content = Helper::replaceCustomFields($content, $contact->customFields); // replace custom field
                $content = Helper::replaceSystemVariables($contact, $content, $data_values); // replace system variables
                $content = Helper::spinTaxParser($content); // replace spintax
                $content = Helper::defaultValueParser($content);

                $subject = Helper::replaceSpintags(Helper::decodeString($page->email_subject)); // replace spintags
                $subject = Helper::replaceCustomFields($subject, $contact->customFields); // replace custom field
                $subject = Helper::replaceSystemVariables($contact, $subject, $data_values); // replace system variables
                $subject = Helper::spinTaxParser($subject); // replace spintax
                $subject = Helper::defaultValueParser($subject);

                $message = new \Symfony\Component\Mime\Email();
                $message->from(new \Symfony\Component\Mime\Address($from_email, $from_name));

                if(in_array($settings->sending_type, Helper::sendingServersFramworkSuported())) {

                  $headers= $message->getHeaders();
                  $headers->addIdHeader('Message-ID', $message_id);
                  $headers->addTextHeader('List-Unsubscribe', sprintf('<mailto:%s?subject=unsubscribe>', urlencode($from_email)));
                  $headers->addTextHeader('List-Unsubscribe-Post', 'List-Unsubscribe=One-Click');

                  $message->to($contact->email);
                  $message->subject($subject);
                  $message->html($content);
                  $message->text($content);
                  try {
                    $connection['transport']->send($message);
                    $status = 'Sent';
                  } catch(\Exception $e) {
                    //echo $e->getMessage();
                    $status = 'Failed';
                  }
                } elseif($settings->sending_type == 'sendgrid_api') {
                  $message->addTo($contact->email);
                  $message->setSubject($subject);
                  $message->addContent("text/html", $content);
                  $sendgrid = new \SendGrid(\Crypt::decrypt(json_decode($settings->sending_attributes)->api_key));
                  try {
                    $response = $sendgrid->send($message);
                    // status start with 2 consider as sent
                    if(substr($response->statusCode(), 1) == 2) {
                      $status = 'Sent';
                    } else {
                      $status = 'Failed';
                    }
                  } catch(\Exception $e) {
                    //echo $e->getMessage();
                    $status = 'Failed';
                  }
                }
              }
            }

            // send notification email
            if(!empty($contact->list->notify_email)) {
              $from_email = $settings->from_email;
              $from_name = $settings->from_name;
              // get sending domain from email
              $sending_domain = Helper::getSendingDomainFromEmail($from_email);
              // Tracking domain would be app_url for the notification emails
              $tracking_domain = $settings->app_url;
              $message_id = Helper::getCustomMessageID($tracking_domain);

              $data_values = [
                'sender-name'    => $from_name,
                'sender-email'   => $from_email,
                'domain'         => $tracking_domain,
                'message-id'     => $message_id,
              ];

              $page = \App\Models\EmailsPage::whereSlug($this->notify_email_template)->whereAppId($contact->app_id)->first();

              $content = Helper::replaceSpintags($page->content); // replace spintags
              $content = Helper::replaceCustomFields($content, $contact->customFields); // replace custom field
              $content = Helper::replaceSystemVariables($contact, $content, $data_values); // replace system variables
              $content = Helper::spinTaxParser($content); // replace spintax

              $subject = Helper::replaceSpintags($page->email_subject); // replace spintags
              $subject = Helper::replaceCustomFields($subject, $contact->customFields); // replace custom field
              $subject = Helper::replaceSystemVariables($contact, $subject, $data_values); // replace system variables
              $subject = Helper::spinTaxParser($subject); // replace spintax

              $message = new \Symfony\Component\Mime\Email();
              $message->from(new \Symfony\Component\Mime\Address($from_email, $from_name));
              if(in_array($settings->sending_type, Helper::sendingServersFramworkSuported())) {

                  $headers= $message->getHeaders();
                  $headers->addIdHeader('Message-ID', $message_id);
                  $headers->addTextHeader('List-Unsubscribe', sprintf('<mailto:%s?subject=unsubscribe>', urlencode($from_email)));
                  $headers->addTextHeader('List-Unsubscribe-Post', 'List-Unsubscribe=One-Click');

                  $message->to($contact->list->notify_email);
                  $message->subject($subject);
                  $message->html($content);
                  $message->text($content);
                  try {
                    $connection['transport']->send($message);
                    $status = 'Sent';
                  } catch(\Exception $e) {
                    //echo $e->getMessage();
                    $status = 'Failed';
                  }
              } elseif($settings->sending_type == 'sendgrid_api') {
                $message->addTo($contact->list->notify_email);
                $message->setSubject($subject);
                $message->addContent("text/html", $content);
                $sendgrid = new \SendGrid(json_decode($settings->sending_attributes)->api_key);
                try {
                  $response = $sendgrid->send($message);
                  $status = 'Sent';
                } catch(\Exception $e) {
                  //echo $e->getMessage();
                  $status = 'Failed';
                }
              }
            }
          } // if($connection['success'])
        return new MailMessage();
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            //
        ];
    }
}
