<?php
/**
 * Разработал Максим Руденко
 * email: rudenko.programmer@gmail.com
 * Дата: 15.12.2017
 */

namespace common\models\opportunities;

use common\models\team\Team;
use common\models\team\TeamUser;
use common\models\User;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;

/**
 * Class OpportunitiesModel
 * @package common\models\opportunities
 * @property integer id
 * @property integer owner_id --- ????
 * @property integer start_date
 * @property string title
 * @property string description
 * @property integer incorporation
 * @property string basecamp city and country
 * @property string main_markets city and country
 * @property string site_url
 * @property string social_in_url
 * @property string social_fb_url
 * @property string social_gp_url
 * @property string lifecycle_stage
 * @property string lifetime_rev_currency
 * @property integer lifetime_rev_value
 * @property string last_rev_currency
 * @property integer last_rev_value
 * @property string opportunity_purpose
 * @property string vision
 * @property string proposition
 * @property string key_customer
 * @property string target_markets
 * @property string interaction
 * @property integer funding
 * @property integer status
 * @property integer created_by
 * @property integer created_at
 * @property integer updated_by
 * @property integer updated_at
 * @property integer deleted_by
 * @property integer deleted_at
 * @method team
 */
class OpportunitiesModel extends ActiveRecord
{
	const member_types = [
		'partner' => 'Partner',
		'contributor' => 'Contributor',
		'sponsor' => 'Sponsor',
		'fan' => 'Fan',
	];

	const lifecycle_list = [
		'idea_generation'=>'Idea generation',
		'prototyping'=>'Prototyping',
		'early_adapters'=>'Early adapters',
		'paying_users'=>'Paying users'
	];

	const opportunity_purpose_list = [
		'find_talents'=>'Find Talents',
		'grow_an_opportunity'=>'Grow your opportunity',
		'tune_the_team'=>'Tune the team',
		'create_an_archipelago'=>'Join an archipelago',
	];

	const key_customer_list = [
		'b2b' => 'B2B',
		'b2c' => 'B2C',
		'marketplace' => 'Marketplace',
	];

	const interactions_list = [
		'face-to-face' => 'Face-to-face',
		'digital' => 'Digital',
	];

	const ACCEPTED   = 'ACCEPTED'; //Level A approve
	const UNACCEPTED = 'UNACCEPTED'; //Требует доработки
	const REJECTED   = 'REJECTED'; //Отменено админом
	const STEP_B_CREATE = 'STEP_B_CREATE';//Швг Б создан

	/**
	 * @return array
	 */
	public function behaviors()
	{
		return [
			[
				'class' => TimestampBehavior::className(),
				'attributes' => [
					ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
					ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
				],
			],
		];
	}


	/**
	 * @return string
	 */
	public static function tableName()
	{
		return 'opportunities';
	}

	/**
	 * @return array
	 */
	public function rules()
	{
		return [
			[['title', 'description', 'basecamp', 'site_url', 'social_in_url', 'social_fb_url', 'social_gp_url', 'lifecycle_stage', 'lifetime_rev_currency', 'last_rev_currency', 'opportunity_purpose', 'vision', 'proposition', 'key_customer', 'target_markets', 'interaction', 'status'], 'string'],
			[['start_date', 'owner_id', 'incorporation'], 'integer'],
			[['lifetime_rev_value', 'last_rev_value', '	main_markets', 'created_by', 'created_at', 'updated_by', 'updated_at', 'deleted_by', 'deleted_at', 'funding'], 'safe'],
		];
	}

	/**
	 * Get team owner
	 * @return \yii\db\ActiveQuery
	 */
	public function getOwner()
	{
		return $this->hasOne(User::className(), ['id' => 'owner_id']);
	}

	/**
	 * Get log data
	 * @return \yii\db\ActiveQuery
	 */
	public function getLog()
	{
		return $this->hasMany(OpportunitiesLogs::className(), ['opportunity_id' => 'id']);
	}

	/**
	 * Get log data
	 * @return \yii\db\ActiveQuery
	 */
	public function getTeam()
	{
		return $this->hasOne(Team::className(), ['opportunity_id' => 'id']);
	}

	/**
	 * Get owner status
	 * @param integer $id
	 *
	 * @return bool
	 */
	public function isOwner($id){
		return $id == $this->owner_id;
	}

	/**
	 * Get current user status in the team
	 * @param $id
	 *
	 * @return mixed|null|string
	 */
	public function currentUserStatus($id){
		if($this->isOwner($id)){
			return 'OWNER';
		}
		$team_id = $this->team->id;
		$team_user = TeamUser::find()->where(['user_id' => $id])->andWhere(['team_id' => $team_id])->one();
		if($team_user){
			return $team_user->status;
		}

		return null;
	}

	/**
	 * Get opport status
	 * if status equal STEP_B_CREATE user create all opport steps return true else false
	 * @return bool
	 */
	public function getOpportStatus(){

		if($this->status == $this::STEP_B_CREATE){
			return true;
		}
		return false;
	}

	/**
	 * Get team list for current user
	 *
	 * @param $user_id
	 *
	 * @return array|OpportunitiesLogs[]|ActiveRecord[]
	 */
	public function getTeamListForUser($user_id){
		$team_id = $this->team->id;
		return TeamUser::find()->where(['AND',
			['team_id' => $team_id],
			['OR',
				['user_id' => $user_id],
				['status' => TeamUser::STATUS_MEMBER]
			]
		])->all();
	}


	/**
	 * Get count of new opportunities
	 * @return int|string
	 */
	public static function getNewCount(){
		try{
			return self::find()
            ->andWhere(['is_new' => '1'])
            ->andWhere(['status' => self::UNACCEPTED])
            ->count();
		}catch (Exception $e){
			return null;
		}
	}

	/**
	 * Add opportunities to user wishlist
	 *
	 * @param $opportunity_id
	 * @param $user_id
	 *
	 * @return bool|TeamUser
	 */
	public static function addToWishList($opportunity_id, $user_id){
		$opportunity = OpportunitiesModel::findOne($opportunity_id);
		$user = User::findOne($user_id);
		if($opportunity && $user){
			/** @var Team $team */
			$team = $opportunity->team;
			if($team){
				$team_user = new TeamUser();
				$team_user->user_id = $user_id;
				$team_user->team_id = $team->id;
				$team_user->status = TeamUser::STATUS_WISHLIST;
				$team_user->save();

				return $team_user;
			}
		}

		return false;
	}

	/**
	 * Add to wishlist
	 *
	 * @param $opportunity_id
	 * @param $user_id
	 *
	 * @return bool|false|int
	 */
	public static function delFromWishList($opportunity_id, $user_id){
		$opportunity = OpportunitiesModel::findOne($opportunity_id);
		$user = User::findOne($user_id);
		if($opportunity && $user){
			/** @var Team $team */
			$team = $opportunity->team;
			if($team){
				$team_user = new TeamUser();
				return $team_user->delete();
			}
		}

		return false;
	}

	public function getJSData($json = false){
		$data = [
			'id' => $this->id,
			'purpose' => addslashes($this->opportunity_purpose),
			'headquarter' => str_replace("'", '',$this->basecamp),
			'markets' => addslashes($this->main_markets),
			'matching_score' => '',
			'passions' => '',
			'capabilities' => '',
			'wishlist' => ''
		];

		return $json?json_encode($data):$data;
	}
}