<?php

class Webdialer
{

    public static function dial()
    {
        $user = @$_REQUEST['user'];
        $to = @$_REQUEST['to'];
        $clip = @$_REQUEST['clip'];
        $token = @$_REQUEST['token'];

        if (empty($user)) {
            throw new CHttpException(500, 'Missing parameter "user"!');
        }
        if (empty($to)) {
            throw new CHttpException(500, 'Missing parameter "to"!');
        }

        if (!isset($clip)) {
            $clip = '';
        }

        $userModel = User::model()->findByAttributes(array('name' => $user));
        if (!$userModel) {
            throw new CHttpException(500, 'User not found!');
        }
        if (empty($token) || $token !== cfg('CALL_SERVICE_AUTHTOKEN')) {
            throw new CHttpException(500, 'Wrong Token!');
        }

        $id = $userModel->id;

        if (Webdialer::getUserPhoneCount($id) > 1) {
            return Webdialer::createUCItem($userModel, $to, $clip);
        }

        $phone = Webdialer::getUserPhone($id);
        if (Webdialer::phoneDoesSupportURLDial($phone)) {
            if (!Webdialer::makeUrlCall($to, $id, $phone, $clip)) {
                return Webdialer::createUCItem($userModel, $to, $clip);
            }
        } else {
            return Webdialer::createUCItem($userModel, $to, $clip);
        }
    }

    protected static function getUserPhoneCount($id)
    {
        $count = 0;
        $sipAccount = Webdialer::getUserSipAccount($id);
        if ($sipAccount) {
            $count = Phones::model()->countAllByAttributes(array('sip_account_id' => $sipAccount->id));
        }
        return (int) $count;
    }

    protected static function getUserSipAccount($id)
    {
        return SipAccounts::model()->findByAttributes(array('user_id' => $id, 'state' => 'online'));
    }

    protected static function createUCItem($userModel, $to, $clip = '')
    {
        $model = new UCItem();
        $model->owner_id = $userModel->id;
        $model->to = $to;
        if (!empty($clip)) {
            $model->setValueForKey('clip', $clip);
        }
        $model->typ = UCType::CTIcall;
        $model->save();
        echo "Dialing $to from $userModel->extension";
    }

    protected static function phoneDoesSupportURLDial($phone)
    {
        $result = false;
        if (!empty($phone)) {
            $phoneModel = PhoneModelFactory::getPhoneModelOfType($phone->type);
            if (method_exists($phoneModel, 'phoneDoesSupportURLDial')) {
                $result = $phoneModel->phoneDoesSupportURLDial($phone);
            }
        }
        return $result;
    }

    protected static function getUserPhone($id)
    {
        $phone = '';
        $sipAccount = Webdialer::getUserSipAccount($id);
        if ($sipAccount) {
            $phone = Phones::model()->findByAttributes(array('sip_account_id' => $sipAccount->id));
        }
        return $phone;
    }

    protected static function makeUrlCall($to, $id, $phone, $clip)
    {
        $url = $phone->getCallServiceURL($to, $id, $phone, $clip);
        return Webdialer::getCurlResult($url);
    }

    protected static function getCurlResult($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = false;
        if (($httpcode == 200)) {
            $result = true;
        }
        return $result;
    }
}
