/**
  * @param     $message
  * @param int $code
  *
  * @return Exception
  */
 public function __construct($message, $code = 0)
 {
     MarketPlugin::log($message, LogLevel::Error);
     parent::__construct($message, $code);
 }
 /**
  * Handler for order status change event
  *
  * @param Event $event
  *
  * @throws Exception
  */
 public function statusChangeHandler(Event $event)
 {
     /** @var Market_OrderModel $order */
     $order = $event->params['order'];
     if (!$order->orderStatusId) {
         return;
     }
     $status = craft()->market_orderStatus->getById($order->orderStatusId);
     if (!$status || !$status->emails) {
         MarketPlugin::log("Can't send email if no status or emails exist.", LogLevel::Info, true);
         return;
     }
     //sending emails
     $renderVariables = ['order' => $order, 'update' => $event->params['orderHistory']];
     //substitute templates path
     $oldPath = craft()->path->getTemplatesPath();
     $newPath = craft()->path->getSiteTemplatesPath();
     craft()->path->setTemplatesPath($newPath);
     foreach ($status->emails as $email) {
         $craftEmail = new EmailModel();
         if (craft()->market_settings->getSettings()->emailSenderAddress) {
             $craftEmail->fromEmail = craft()->market_settings->getSettings()->emailSenderAddress;
         }
         if (craft()->market_settings->getSettings()->emailSenderName) {
             $craftEmail->fromName = craft()->market_settings->getSettings()->emailSenderName;
         }
         $craftEmail->toEmail = $to = craft()->templates->renderString($email->to, $renderVariables);
         $craftEmail->bcc = craft()->templates->renderString($email->bcc, $renderVariables);
         $craftEmail->subject = craft()->templates->renderString($email->subject, $renderVariables);
         $body = $email->type == Market_EmailRecord::TYPE_HTML ? 'htmlBody' : 'body';
         $craftEmail->{$body} = craft()->templates->render($email->templatePath, $renderVariables);
         if (!craft()->email->sendEmail($craftEmail)) {
             throw new Exception('Email sending error: ' . implode(', ', $email->getAllErrors()));
         }
         //logging
         $log = sprintf('Order #%d got new status "%s". Email "%s" %d was sent to %s', $order->id, $order->orderStatus, $email->name, $email->id, $to);
         MarketPlugin::log($log, LogLevel::Info, true);
     }
     //put old template path back
     craft()->path->setTemplatesPath($oldPath);
 }