<?php

include_once 'AbstractXmlApp.php';

abstract class AbstractXMLPhoneLoginApp extends AbstractXMLApp
{

    protected $extension;
    protected $pin;

    public function run($controller)
    {
        parent::run($controller);
        $this->setAttributes();

        if ($this->extension) {
            $extension = $this->extension;
            return $this->checkForExtension($extension);
        }
        $this->renderLoginExtension();
    }

    protected function setAttributes()
    {
        $this->extension = @$_REQUEST["extension"];
        $this->pin = @$_REQUEST["pin"];
    }

    protected function checkForExtension($extension)
    {
        $model = User::model()->findByAttributes(array('extension' => $extension));

        if ($model != null) {
            $sip = SipAccounts::model()->findByAttributes(array('authname' => $extension));
            $this->checkForSipAccount($model, $sip);
        } else {
            $this->renderNoExtensionFound();
        }
    }

    protected function checkForSipAccount($model, $sip)
    {
        if ($sip) {
            $this->checkForPIN($model, $sip);
        } else {
            $this->renderNoSipFound();
        }
    }

    protected function checkForPIN($model, $sip)
    {
        if ($this->pin) {
            if ($this->pin == $model->pin) {
                $this->assignNewUser($sip);
                return $this->renderSucces();
            } else {
                return $this->renderWrongPIN();
            }
        }
        return $this->renderLoginPIN();
    }

    protected function assignNewUser($sip)
    {
        $this->mPhone->sip_account_id = $sip->id;
        $this->mPhone->last_sip_account_id = null;
        $this->mPhone->save();
        $this->mPhone->triggerProvisioning();
    }
}
