<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;
use Auth;

class ProfileViews extends Model {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'profile_views';

	/** 
	 * The attributes that are mass assignable.
	 *
	 * @var array 
	 */
	protected $fillable = ['visitor_profile_id','visited_profile_id', 'ip_address'];


	protected function getViewerIds($profile_id)
	{
		$result = $this->where('visited_profile_id', '=', $profile_id)->get();
		$arr_ids = array();
		foreach ($result as $key => $value) {
			$arr_ids[] = $value->visitor_profile_id;
		}
		return $arr_ids;
	}

	protected function getLastViewerIds($profile_id, $days)
	{ 
		$interval = DB::select("SELECT DATE_SUB(NOW(),INTERVAL {$days} DAY) AS cutoff_date");
		$result = $this->where('visited_profile_id', '=', $profile_id)->where('created_at', '>', $interval[0]->cutoff_date )->get();
		$arr_ids = array();
		foreach ($result as $key => $value) {
			$arr_ids[] = $value->visitor_profile_id;
		}
                //echo count($arr_ids); exit;
		return $arr_ids;		
	}

	protected function getViewCount($profile_id, $days = 0, $operator = '>')
	{
		if($days)
		{
			$interval = DB::select("SELECT DATE_SUB(NOW(),INTERVAL {$days} DAY) AS cutoff_date");
			$result = $this->where('visited_profile_id', '=', $profile_id)->where('created_at', $operator, $interval[0]->cutoff_date )->groupBy('visitor_profile_id')->get()->count();
		}
		else
		{
			$result = $this->where('visited_profile_id', '=', $profile_id)->groupBy('visitor_profile_id')->get()->count();
		}
		return $result;
	}

	protected function getVisitorsList($profile_id, $days = 0)
	{
		$result = array();
		if($days)
			$arr_ids = $this->getLastViewerIds($profile_id, $days);
		else
			$arr_ids = $this->getViewerIds($profile_id);
		if(count($arr_ids))
			$result = DB::select("select p.id,p.profile_image,p.profile_type,p.name from profiles as p LEFT JOIN users as u ON u.id = p.user_id where p.id in (" . implode(',', $arr_ids) . ")");
		return $result;
	}

	protected function getChartData($profile_id)
	{
		$result = DB::select("SELECT YEAR(created_at) AS y, MONTH(created_at) AS m, MONTHNAME(created_at) AS m_name, COUNT(DISTINCT id) total_views FROM `profile_views` WHERE visited_profile_id = ".$profile_id." GROUP BY y, m");
		return $result;
	}
}