<?php

class mailNotification extends WireData implements Module, ConfigurableModule {

    protected $mailAddress, $notificationPublish, $notificationDelete, $notificationChange;

    public static function getModuleInfo() {
        return array(
            'title' => __('Mail Notification'),
            'version' => '003',
            'author' => 'Kreativmonkey',
            'summary' => __('Notification mail by saving or deleting Pages'),
            'autoload' => true
        );
    }

    public function ___install() {

    }

    public function setDefault() {
      $this->mailAddress = '';
      $this->notificationPublish = array();
      $this->notificationDelete = array();
      $this->notificationChange = array();
    }

    public function init() {

        $this->setDefault();

        if (isset($this->data['notificationPublish'])){
          $this->notificationPublish = $this->data['notificationPublish'];
        }

        if (isset($this->data['notificatioDelete'])){
          $this->notificationDelete = $this->data['notificationDelete'];
        }

        if (isset($this->data['notificationChange'])){
          $this->notificationChange = $this->data['notificationChange'];
        }

        if (isset($this->data['mailAddress'])){
          $this->mailAddress = $this->data['mailAddress'];
        }

        $this->addHook('Pages::saveReady', $this, "hookCheckNotification");
    }

    public function hookCheckNotification(HookEvent $event){
      $page = $event->arguments[0];
      $template = $page->template;
      $templates = $this->notificationChange;

      // if page have no id => return
      if(!$page->id || !$page->title) return;


      // Check if page is Deleted
      if($page->isTrash()){
        $this->notificationDelete($page);
        $this->log->save('message', "Page deleted: $page->title");
        return;
      }

      // Check if page is Changed
      if($page->isChanged()){
        if($page->isChanged("status") && !$page->is(PAGE::statusUnpublished)){
          if(!in_array($template->name, $this->notificationPublish)) return;

          $this->notificationPublish($page);
          $this->log->save('message', "Page published: $paget->title");
          return;
        }
        if(!in_array($template->name, $this->notificationChange)) return;

        $this->notificationChange($page);
        $this->log->save('message', "Page changed: $paget->title");
        return;
      }

    }

    public function notificationPublish(Page $page){
      $template = $page->template;

      // if this post wasn't made by an "user" don't continue
      if($page->createdUser->hasRole('admin|manager')) return;

      // only notify by published pages
      if($page->is(Page::statusUnpublished)) return;

      $subject = sprintf(__('Add new %s with title %s'), $template->name, $page->get('headline|title'));
      $message = sprintf(__("New %s from User %s \n========================= \n\nYou can show the new %s under:\n%s"), $template->name, $page->createdUser->get('name|title'), $template->name, $page->httpUrl);

      $this->sendMail($subject, $message);
      // Message to User
      $this->message(sprintf(__("Publish %s and send mail notification for new %s"), $page->title, $page->template->name));
    }


    public function notificationDelete(Page $page){
      $template = $page->template;
      $templates = $this->notificationDelete;

      // Return if page has no id
      if(!$page->id) return;

      // Return if template has no notification
      if(!in_array($template->name, $template)) return;

      // if this post wasn't made by an "user" don't continue
      if($page->createdUser->hasRole('admin|manager')) return;

      $subject = sprintf(__('%s has deleted by %s'), $page->get('headline|title'), $user->get('title'));
      $message = sprintf(__("%s deleted by %s \n========================= \n\nYou can find it in the bin and restore it."), $page->get('headline|title'), $user->get('name|title'));

      $this->sendMail($subject, $message);
      // Message to User
      $this->message(sprintf(__("Delete %s and send mail notification to administrator"), $page->title));
    }

    public function notificationChange(Page $page){
      $template = $page->template;
      $templates = $this->notificationDelete;
      $user = wire('user');
      // Überprüfen ob die Seite geändert wurde
      if(!$page->isChanged()) return;

      // Return if page has no id
      if(!$page->id) return;

      // Return if template has no notification
      if(!in_array($template->name, $this->notificationChange)) return;

      // if this post wasn't made by an "user" don't continue
      if($page->createdUser->hasRole('admin|manager')) return;

      $subject = sprintf(__('%s has changed by %s'), $page->get('headline|title'), $user->get('name|title'));
      $message = sprintf(__("%s has changed by %s \n========================= \n\nYou can look for the changes at:\n %s"), $page->get('headline|title'), $user->get('name|title'), $page->httpUrl);

      $this->sendMail($subject, $message);
      // Message to User
      $this->message(sprintf(__("Change %s and send mail notification to admin for changed %s."), $page->title, $page->template->name));
    }


    public function sendMail($subject, $message){
      // Do nothing if mailaddress is not set!
      if(empty($this->mailAddress)){
        $this->log->error(__("Can't send Notification, no mail address was set!"));
        return;
      }

      $mail = wireMail();
      $mail->to("{$this->mailAddress}")->from('notify@freifunk-myk.de');
      $mail->subject("$subject");
      $mail->body("$message");
      $mail->send();

      $this->log->message(sprintf(__("Send Mail: %s to %s"), $subject, $this->mailAddress));
    }

    /*public function hookModuleSave(){

    }*/

    static public function getModuleConfigInputfields(array $data) {
      $modules = wire('modules');
      $tmpTemplates = wire('templates');
  		foreach($tmpTemplates as $template) {
        // exclude system fields
  			if($template->flags & Template::flagSystem) continue;
  			$templates[] = $template;
      }

      $inputfields = new InputfieldWrapper();

      $mailAddressField = wire('modules')->get('InputfieldText');
      $mailAddressField->name = 'mailAddress';
      $mailAddressField->columnWidth = 80;
      $mailAddressField->label = __('Mail Addresses');
      $mailAddressField->required = 1;
      if (isset($data['mailAddress']))
        $mailAddressField->value = $data['mailAddress'];
      $mailAddressField->description = __('Mailaddresses like mail@domain.tdl or a username ore user groupe. You can choose more than one address by comma separet.');
      $inputfields->add($mailAddressField);

      // Included fields
  		$field = $modules->get("InputfieldAsmSelect");
  		$field->name = "notificationPublish";
  		$field->label = __("Notification by Publish");
  		$field->description = __("Choose the templates which should be notifyication by publishing.");
  		foreach($templates as $template) $field->addOption($template->name);
      if (isset($data['notificationPublish']))
  		  $field->value = $data['notificationPublish'];
  		//$field->notes = __('Be careful with this field. If you remove an entry all of it\'s "seo_*" fields get deleted (including the data).');
      $inputfields->add($field);

      // Included fields
  		$field = $modules->get("InputfieldAsmSelect");
  		$field->name = "notificationChange";
  		$field->label = __("Notificaltion by Changes");
  		$field->description = __("Choose the templates which should get notification by changes.");
  		foreach($templates as $template) $field->addOption($template->name);
      if (isset($data['notificationChange']))
    		$field->value = $data['notificationChange'];
      $inputfields->add($field);

      // Included fields
  		$field = $modules->get("InputfieldAsmSelect");
  		$field->name = "notificationDelete";
  		$field->label = __("Notification by Delete");
  		$field->description = __("Choose the templates which should get notification by deleting.");
  		foreach($templates as $template) $field->addOption($template->name);
      if (isset($data['notificationDelete']))
  		  $field->value = $data['notificationDelete'];
      $inputfields->add($field);

      return $inputfields;
    }
}
