<?php

class Mlsitcall extends \Eloquent {

	const API_KEY						 = 'Ntkjuhtqrf2210:';
	const STATUS_NONE				 = 0;
	const STATUS_ANSWERED		 = 1;
	const STATUS_NOANSWERED	 = 2;
	const STATUS_BUSY				 = 3;
	const STATUS_ERROR			 = 100;

	use SoftDeletingTrait;

	protected $guarded		 = array();

	public static function boot() {
		parent::boot();

		Mlsitcall::deleting(function ($mlsitcall) {
			File::deleteDirectory(public_path() . '/calls/' . $mlsitcall->partner_id . '/' . $mlsitcall->id);
			return true;
		});
	}

	public function partner() {
		return $this->belongsTo('Partner');
	}

	public function user() {
		return $this->belongsTo('User')->withTrashed()->remember(60);
	}

	private function numberof($numberof, $value, $suffix) {
		// не будем склонять отрицательные числа
		$numberof		 = abs($numberof);
		$keys				 = array(2, 0, 1, 1, 1, 2);
		$mod				 = $numberof % 100;
		$suffix_key	 = $mod > 4 && $mod < 20 ? 2 : $keys[min($mod % 10, 5)];

		return $value . $suffix[$suffix_key];
	}

	public function getStatusName() {
		$statusName = "нет информации о звонке";
		if ($this->call_state == Mlsitcall::STATUS_ANSWERED) {
			$duration			 = explode(":", gmdate("i:s", $this->call_duration));
			$duration[0]	 = (int) $duration[0];
			$duration[1]	 = (int) $duration[1];
			$durationText	 = "";
			if ($duration[0]) {
				$durationText .= "{$duration[0]} " . $this->numberof($duration[0], "минут", array('а', 'ы', '')) . " ";
			}
			if ($duration[1]) {
				$durationText .= "{$duration[1]} " . $this->numberof($duration[1], "секунд", array('а', 'ы', ''));
			}
			$statusName = "разговор {$durationText}";
		}
		elseif ($this->call_state == Mlsitcall::STATUS_NOANSWERED) {
			$statusName = "нет ответа";
		}
		elseif ($this->call_state == Mlsitcall::STATUS_BUSY) {
			$statusName = "занят";
		}
		return $statusName;
	}

	public function call() {
		$endpoint = 'http://calls.mlsit.ru/site/actions';

		$ch			 = curl_init(sprintf('%s?type=call&from=%s&to=%s&cid=%s&src=%s&fromtype=2', $endpoint, $this->user->sip_number, $this->phone, $this->id, md5(Mlsitcall::API_KEY . $this->id)));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result	 = curl_exec($ch);
		$result	 = json_decode($result, true);
		return $result;
	}

	public function checkStatus() {
		$endpoint = 'http://calls.mlsit.ru/site/actions';

		$ch			 = curl_init(sprintf('%s?type=getstatus&cid=%s&src=%s', $endpoint, $this->id, md5(Mlsitcall::API_KEY . $this->id)));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result	 = curl_exec($ch);
//		$result	 = str_replace("[", "", $result);
//		$result	 = str_replace("]", "", $result);
		$result	 = json_decode($result, true);
		if (is_array($result)) {
			$result = array_pop($result);

			if (isset($result['CallDate'])) {
				$this->call_date = $result['CallDate'];
			}
			if (isset($result['CallFrom'])) {
				$this->call_from = $result['CallFrom'];
			}
			if (isset($result['CallTo'])) {
				$this->call_to = $result['CallTo'];
			}
			if (isset($result['CallDuration'])) {
				$this->call_duration = $result['CallDuration'];
			}
			if (!isset($result['CallState'])) {
				$this->call_state = Mlsitcall::STATUS_NONE;
			}
			if (isset($result['CallState'])) {
				switch ($result['CallState']) {
					case 'ANSWERED':
						$this->call_state	 = Mlsitcall::STATUS_ANSWERED;
						$date							 = explode(" ", $this->call_date);
						$date[0]					 = explode("-", $date[0]);
						$this->filename		 = "{$this->user->first_name}_{$this->user->last_name}_{$date[0][2]}_{$date[0][1]}_{$date[0][0]}_в_{$date[1]}";
						break;
					case 'NO ANSWER':
						$this->call_state	 = Mlsitcall::STATUS_NOANSWERED;
						break;
					case 'BUSY':
						$this->call_state	 = Mlsitcall::STATUS_BUSY;
						break;
				}
			}
			else {
				$this->call_state = Mlsitcall::STATUS_ERROR;
			}
			$this->save();
		}
	}

	public function getCallFile() {
		$endpoint = 'http://calls.mlsit.ru/site/actions';

		$ch			 = curl_init(sprintf('%s?type=getrecordfile&cid=%s&src=%s', $endpoint, $this->id, md5(Mlsitcall::API_KEY . $this->id)));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result	 = curl_exec($ch);
		return $result;
	}

}
