<?php
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
App::uses('CakeSession', 'Model/Datasource');

/**
 * User Model
 *
 * @property Group $Group
 * @property Gender $Gender
 */
class User extends AppModel
{

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'user_name';

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'tos' => array(
			'notEmpty' => array(
				'rule'     => array('comparison', 'equal to', 1),
				'message'  => 'Please check this box if you want to proceed.'
			)
		),
		'first_name' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			)
		),
		'last_name' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			)
		),
		'zip' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'password' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'between' => array(
				'rule'    => array('between', 6, 40),
				'message' => 'Your password must be between 6 and 40 characters.'
			)
		),
		'password_new' => array(
			'between' => array(
				'rule'    => array('between', 6, 40),
				'allowEmpty' => true,
				'message' => 'Your password must be between 6 and 40 characters.'
			)
		),
		'password_confirm' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				'allowEmpty' => false,
				'on' => 'create', // Stop validation after this rule
			),
			'compareCreate' => array(
				'rule'    => array('compare_passwords'),
				'allowEmpty' => true,
				'message' => 'The passwords are not identical!',
			),
		),
		'email' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'email' => array(
				'rule' => array('email'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'isUnique' => array(
				'rule'    => array('isUnique'),
				'message' => 'This email address is already being in use.'
			)
		),
		'email_check' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
			),
			'email' => array(
				'rule' => array('email'),
			),
		),
		'email_key' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
			),
			'alphaNumeric' => array(
				'rule' => array('alphaNumeric'),
			),
		),
		'charged' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				'allowEmpty' => true,
			),
		),
		'charged_add_weeks' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				'allowEmpty' => true,
			),
		),
		'group_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'gender_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'captcha' => array(
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'check' => array(
				'rule' => 'checkCaptcha',
				'message' => 'You entered the wrong captcha code.',
			)
		),
		'date_of_birth' => array(
			'date' => array(
				'rule' => array('date'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'notEmpty' => array(
				'rule' => 'notBlank',
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'age' => array(
				'rule' => 'checkOver18',
				'message' => 'You must be over 18 years old'
			)
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'Group' => array(
			'className' => 'Group',
			'foreignKey' => 'group_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Country' => array(
			'className' => 'Country',
			'foreignKey' => 'country_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Gender' => array(
			'className' => 'Gender',
			'foreignKey' => 'gender_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

/**
 * hasMany associations
 *
 * @var array
 */
	public $hasMany = array(
		'Program' => array(
			'className' => 'Program',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

	public function beforeSave($options = Array())
	{
        //calculate weeks for charged
		if (!empty($this->data[$this->alias]['charged_add_weeks'])) {

            $now = new DateTime();
            $freeWeeksStart = new DateTime('2017-2-28');

            $weeks = floor($now->diff($freeWeeksStart)->days/7);
            $this->data[$this->alias]['charged'] = $this->data[$this->alias]['charged_add_weeks'] + $weeks;

        }
		if (!empty($this->data[$this->alias]['password_new']))
		{
			$passwordHasher = new BlowfishPasswordHasher();
			$this->data[$this->alias]['password'] = $passwordHasher->hash
			(
				$this->data[$this->alias]['password_new']
			);
		}
		elseif (!empty($this->data[$this->alias]['password']))
		{
			$passwordHasher = new BlowfishPasswordHasher();
			$this->data[$this->alias]['password'] = $passwordHasher->hash
			(
				$this->data[$this->alias]['password']
			);
		}
		return true;
	}
	public function checkOver18($data)
	{
	  $time = strtotime($data['date_of_birth']);
	  if (time() < strtotime('+18 years', $time)) return false;
	  return true;
	}
	public function compare_passwords($check) //password match check
 	{
        $this->log($check);
        $this->log('LEL');
		$data = (isset($this->data[$this->alias]['password'])) ? $this->data[$this->alias]['password'] : $this->data[$this->alias]['password_new'];
		return $data === $check['password_confirm'];
	}

	public function afterSave($created, $options = array())
	{
		if (CakeSession::read('Auth.User.id') == $this->data['User']['id'] && !$created)
		{
			$user = $this->find('first', array(
				'conditions' => array(
					'User.id' => $this->data['User']['id'],
				),
			));

			unset($user['User']['password']);

			$data = $user['User'];
			$data['Group'] = $user['Group'];
			$data['Gender'] = $user['Gender'];
            $data['Subscription']= CakeSession::read('Auth.User.Subscription');
            $data['Plan']= CakeSession::read('Auth.User.Plan');

			CakeSession::write('Auth.User', $data);
		}
	}

	public function checkCaptcha($data)
	{
		//$this->log($data['captcha']);
		//$this->log(CakeSession::read('captcha.code'));
		//$this->log($data['captcha']);
		//$this->log(CakeSession::read('captcha.code'));
		return (strtoupper($data['captcha']) === CakeSession::read('captcha.code')) ? true : false;
	}

    public function notTriedout()
    {
        if (!CakeSession::read('Auth.User.tryout')) {
            return true;
        }
    }

    public function isTryingout()
    {
        if (!CakeSession::read('Auth.User.tryout')) {
            return false;
        }
        $tryout = new DateTime(CakeSession::read('Auth.User.tryout'));
        $endTryout = clone $tryout;
        $endTryout->modify('+2 weeks');

        $current = new DateTime();
        //$this->log($endTryout->format('Y-m-d') . ':::' . $new->format('Y-m-d'));
        if ($endTryout >= $current) {
            return $endTryout->format('Y-m-d');
        }

        return false;
    }

    public function canTryout()
    {
        if(!CakeSession::read('Auth.User.tryout') && !CakeSession::read('Auth.User.stripe_customer_id')) {
            return false;
        }
        /*

        $tryout = new DateTime(CakeSession::read('Auth.User.tryout'));
        $endTryout = clone $tryout;
        $endTryout->modify('+2 weeks');

        if ($tryout <= new DateTime()) {
            return $endTryout->format('Y-m-d');
        }

        return false;
        */
    }

    public function isSubscribed()
    {
        if (CakeSession::check('Auth.User.Subscription.status')) {
            $status = CakeSession::read('Auth.User.Subscription.status');

            if($status === 'trialing' || $status === 'active') {
                return true;
            }
        }

        return false;
    }

    public function setSubscription($subscription)
    {
        $dataSubscription = array(
            'id' => $subscription->id,
            'created' => $subscription->created,
            'current_period_start' => $subscription->current_period_start,
            'current_period_end' => $subscription->current_period_end,
            'start' => $subscription->start,
            'status' => $subscription->status,
        );
        $dataPlan = array(
            'id' => $subscription->plan->id,
            'name' => $subscription->plan->name,
            'amount' => $subscription->plan->amount,
            'interval' => $subscription->plan->interval,
            'interval_count' => $subscription->plan->interval_count,
        );
        CakeSession::write('Auth.User.Plan', $dataPlan);
        CakeSession::write('Auth.User.Subscription', $dataSubscription);
    }

    public function unsetSubscription()
    {
        CakeSession::delete('Auth.User.Plan');
        CakeSession::delete('Auth.User.Subscription');
    }
    public function hasFreeCharge()
    {
        $now = new DateTime();
        $freeWeeksStart = new DateTime('2017-2-28');

        if (CakeSession::check('Auth.User.charged')) {
            $this->log('känguru');
            $charged = CakeSession::read('Auth.User.charged');
            $freeWeeksStart->modify('+' . $charged . 'weeks');

            if($freeWeeksStart > $now) {
                return true;
            }

        }
        return false;
    }
}
