<?php

namespace Velis\Bpm\Workflow\Handler;

use Velis\Bpm\Workflow\Handler;
use Velis\Bpm\Workflow;
use Velis\Lang;
use Velis\Notification\SmsRecipient;
use Velis\Sms as SmsMessage;
use Velis\Filter;
use User\User;
use Exception;

/**
 * SMS message workflow handler
 * @author Olek Procki <olo@velis.pl>
 */
class Sms extends Handler
{

    /**
     * Handler execution method
     *
     * @param \Velis\Bpm\Workflow\Subject $subject
     * @param mixed $additionalData
     */
    public function run($subject, $additionalData)
    {
        $recipients = [];

        if (!empty($this['user_id'])) {
            if (User::isCacheable()) {
                $recipients[] = User::get($this['user_id']);
            } else {
                $recipients[] = User::instance($this['user_id']);
            }
        }

        if ($this['responsible']) {
            $recipients[] = $subject->getOperator();
        }
        if ($this['reporter']) {
            $recipients[] = $subject->getReporter();
        }
        if ($this['observers']) {
            foreach ($subject->getObservers() as $observer) {
                $recipients[] = $observer;
            }
        }

        if ($recipients) {
            foreach ($recipients as $recipient) {
                if ($recipient instanceof SmsRecipient) {
                    if (!$recipient->getMobile()) {
                        $this->notice(
                            $subject,
                            $additionalData,
                            'Mobile number not set for this recipient'
                        );
                    } else {
                        $this['message'] = strip_tags($subject->translatePlaceholders($this['message']));
                        $sms = new SmsMessage();
                        $sms->setContent(preg_replace('!\s+!', ' ', $this['message']));

                        $sms->setRecipientNumber($recipient->getMobile());
                        try {
                            $sms->send();
                            $this->success($subject, $additionalData);
                        } catch (Exception $e) {
                            $this->error($subject, $additionalData, $e);
                        }
                    }
                }
            }
        } else {
            $this->notice(
                $subject,
                $additionalData,
                'Recipient not found'
            );
        }
    }


    /**
     * Returns parameters reflection info
     * @return array
     */
    public static function getParamsReflection()
    {
        return array(
            'user_id' => array(
                'label' => Lang::get('GENERAL_USER'),
                'type'  => Workflow::PARAM_USER
            ),
            'message' => array(
                'label' => Lang::get('GENERAL_CONTENT'),
                'type'  => Workflow::PARAM_STRING
            )
        );
    }
}
