<?php

class Lead extends Eloquent {

	protected $softDelete	 = true;
	protected $guarded		 = array();
	public static $rules	 = array();

	public function project() {
		return $this->belongsTo('Project');
	}

	public function site() {
		return $this->belongsTo('Site');
	}

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

	public function agent() {
		return $this->belongsTo('User', 'agent_id');
	}

	public function getDataArray() {
		$data = json_decode(json_decode($this->data), true);
		if (!is_array($data)) {
			$data = array();
		}
		return $data;
//		return json_decode(json_decode($this->data), true);
	}

	public function getBeforeCnt($projectId, $entrypoint, $date) {
		$projectId	 = e($projectId);
		$entrypoint	 = e($entrypoint);
		$dateWhere	 = "DATE(created_at)=DATE_SUB('{$date}', INTERVAL 1 DAY) AND TIME(created_at)<TIME(NOW())";
		return Lead::withTrashed()->whereRaw($dateWhere)->where('project_id', e($projectId))->where('entrypoint', $entrypoint)->count();
	}

	public function scopeInMyProjects() {
		return $this->whereRaw('project_id IN (SELECT users_projects.project_id FROM users_projects INNER JOIN projects ON projects.id=users_projects.project_id AND projects.usecrm=1 WHERE users_projects.user_id=' . Sentry::getUser()->id . ')');
	}

	public function leadstatOrder($sum) {
		try {
			if ($this->leadstat_lead_id) {
				$linkRNP = "http://leadstat.ru/papi/leadorder?lead_id={$this->leadstat_lead_id}&sum=".$sum*100;

				$curlInit = curl_init($linkRNP);
				curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
				curl_setopt($curlInit,CURLOPT_HEADER,true);
				curl_setopt($curlInit,CURLOPT_NOBODY,true);
				curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
				curl_exec($curlInit);
				curl_close($curlInit);
			}
		}
		catch (Exception $e) {
		}
	}

	public function leadstatPay($sum) {
		try {
			if ($this->leadstat_lead_id) {
				$linkRNP = "http://leadstat.ru/papi/leadpay?lead_id={$this->leadstat_lead_id}&sum=".$sum*100;

				$curlInit = curl_init($linkRNP);
				curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
				curl_setopt($curlInit,CURLOPT_HEADER,true);
				curl_setopt($curlInit,CURLOPT_NOBODY,true);
				curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
				curl_exec($curlInit);
				curl_close($curlInit);
			}
		}
		catch (Exception $e) {
		}
	}

}
