<?php

class Lead extends Eloquent {

	use SoftDeletingTrait;

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

	public function visitor() {
		return $this->belongsTo('Visitor')->remember(60);
	}

	public function visit() {
		return $this->belongsTo('Visit')->remember(60);
	}

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

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

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

	public function partner() {
		return $this->hasOne('Partner')->remember(60);
	}

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

	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=' . Auth::user()->id . ')');
	}

	public function setCostAttribute($value) {
		$value										 = str_replace(',', '.', $value);
		$value										 = str_replace(' ', '', $value);
		$this->attributes['cost']	 = round($value * 100, 0);
	}

	public function getCostAttribute() {
		return round($this->attributes['cost'] / 100, 2);
	}

	public function setPaymentSum($value) {
		$value													 = str_replace(',', '.', $value);
		$value													 = str_replace(' ', '', $value);
		$this->attributes['payment_sum'] = round($value * 100, 0);
	}

	public function getPaymentSum() {
		return round($this->attributes['payment_sum'] / 100, 2);
	}

	public function setOrderSum($value) {
		$value												 = str_replace(',', '.', $value);
		$value												 = str_replace(' ', '', $value);
		$this->attributes['order_sum'] = round($value * 100, 0);
	}

	public function getOrderSum() {
		return round($this->attributes['order_sum'] / 100, 2);
	}

}
