<?php

class userActions extends sfActions
{
  const TOKENPW = 'violet';
  
  public function executeTest() {
    var_dump(1);
    return sfView::NONE;
  }

  private function getUserField($fieldName, $value, $currentId = null) {
    $c = new Criteria();
    $c->add($fieldName, $value);
    if ($currentId) $c->add(TbluserPeer::US_ID, $currentId, Criteria::NOT_EQUAL);
    return TbluserPeer::doSelectOne($c);
  }

  private function validateData($name, $email, $phone, &$error, $checkfullname = true) {
	 $nameValid = $checkfullname ? ($name != null && !myUtility::validate('sfFilterValidator', $name, $error)) || 
		 ($name != null && !myUtility::validate('sfFullnameValidator', $name, $error)) : TRUE;
    return
    $nameValid  ||  ($email != null && !myUtility::validate('sfEmailValidator', $email, $error)) ||
    ($phone != null && !myUtility::validate('sfPhoneValidator', $phone, $error));
  }

  private function getUserInfo($tbluser) {
	$fullname = '';
	if ($tbluser->getUsStatus()<10) {
      if (null==$tbluser->getUsLastname() && null==$tbluser->getUsFirstname())
		  $fullname = '';        
      else
        $fullname = $tbluser->getUsLastname().' '.$tbluser->getUsFirstname();
    } else {
        $fullname = 'Đang bị khóa';
    }

    $result  = 'id='.$tbluser->getUsId();
    $result .= '&username='.$tbluser->getUsUsername();
    $result .= '&fullname='.$fullname;
    $result .= '&gender='.($tbluser->getUsSex()==1? 'male': 'female');
    $result .= '&email='.$tbluser->getUsEmail();
    $result .= '&phone='.$tbluser->getUSPhone();
    $result .= '&school='.$tbluser->getUsSchool();
    $result .= '&province='.$tbluser->getUsProvince();
    $result .= '&money='.$tbluser->getUsMoney();
    return $result;
  }

  private function getPEncrypted($tbluser) {
    $result  = 'pencrypted='.$tbluser->getUsPassword();
    return $result;
  }

  private function getLicense($tbluser) {
    $productId = $this->getRequestParameter('product');
    $version = $this->getRequestParameter('version');
    if ($productId == null) return;

    $c = new Criteria();
    $c->add(TblprolicensePeer::LI_TYPE, 1);
    $c->add(TblprolicensePeer::LI_CUSTOMER, $tbluser->getUsId());
    $c->add(TblprolicensePeer::LI_PRODUCT, $productId);
    $c->add(TblprolicensePeer::LI_VERSION, $version, Criteria::GREATER_EQUAL);
    $c->add(TblprolicensePeer::LI_EXPIREDATE, date('Y-m-d H:i:s'), Criteria::GREATER_EQUAL);
    $license = TblprolicensePeer::doSelectOne($c);
    $userdetail = TblblogcheckinfoPeer::retrieveByPk($tbluser->getUsId());
    if ($license == null && $userdetail != null) {
      $c = new Criteria();
      $c->add(TblprolicensePeer::LI_TYPE, 2);
      $c->add(TblprolicensePeer::LI_CUSTOMER, $userdetail->getCiSchool());
      $c->add(TblprolicensePeer::LI_PRODUCT, $productId);
      $c->add(TblprolicensePeer::LI_VERSION, $version, Criteria::GREATER_EQUAL);
      $c->add(TblprolicensePeer::LI_EXPIREDATE, date('Y-m-d H:i:s'), Criteria::GREATER_EQUAL);
      $license = TblprolicensePeer::doSelectOne($c);
    }
    return $license;
  }

  public function executeLogin() {
    $src = $this->getRequestParameter('src');
    $token = $this->getRequestParameter('token');
    $account = $this->getRequestParameter('username');
    $password = $this->getRequestParameter('password');		

    if ($account == null || $password == null) return $this->renderText('status=1&errMsg=Not enough data');
    if ($src == null || $token != md5($account.self::TOKENPW)) return $this->renderText('status=10');

    $tbluser = $this->getUserField(TbluserPeer::US_USERNAME, $account);

    if (!$tbluser) $tbluser = $this->getUserField(TbluserPeer::US_EMAIL, $account);
    if (!$tbluser) $tbluser = $this->getUserField(TbluserPeer::US_PHONE, $account);
    if (!$tbluser) return $this->renderText('status=2&errMsg=User not found');
    if ($tbluser->getUsPassword() != md5($password)) return $this->renderText('status=3&errMsg=Incorrect password');

    $loginResult = $this->getUserInfo($tbluser);
    if ($tbluser->getUsStatus() == 0) return $this->renderText($loginResult.'&status=4&errMsg=Account is not activated');
    
	if ($license = $this->getLicense($tbluser)) {
      $loginResult .= '&level='.$license->getLiLevel();
      $ltype = $license->getLiType();
      $cid = $license->getLiCustomer();
      $customer = $ltype == 1? $tbluser->getUsFullname(): TblblogschoolsPeer::retrieveByPk($cid)->getScName();
      $loginResult .= '&licType='.$ltype;
      $loginResult .= '&licCustomer='.$customer;
      $loginResult .= '&licCreate='.$license->getLiCreatedate('d/m/Y');
      $loginResult .= '&licExpire='.$license->getLiExpiredate('d/m/Y');
    }
    else 
		$loginResult .= '&level=0';

    $loginResult .= '&status=0';

    /*try {
      $this->getUser()->signIn($tbluser);
    } catch (Exception $e) {
      return $this->renderText('&status=5&errMsg='.$e->getMessage());
    }*/
    $ip = myUtility::getRealIpAddr();
    myUtility::log("$ip login from $src ($account)", 'apiuser.log');
    return $this->renderText($loginResult);
  }

  public function executeLogout() {
    $this->getUser()->signOut();
    return sfView::NONE;
  }

  /*public function executeGetinfo() {
    $src = $this->getRequestParameter('src');
    $us_id = $this->getRequestParameter('us_id');
    $uname = $this->getRequestParameter('username');
    $email = $this->getRequestParameter('email');
    $phone = $this->getRequestParameter('phone');
    $token = $this->getRequestParameter('token');
    if ($src == null) return sfView::NONE;

    if ($us_id && $token==md5($us_id.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_ID, $us_id);
    if ($uname && $token==md5($uname.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_USERNAME, $uname);
    if ($email && $token==md5($email.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_EMAIL, $email);
    if ($phone && $token==md5($phone.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_PHONE, $phone);

    if ($tbluser) $result = $this->getUserInfo($tbluser);
    else return sfView::NONE;

    $ip = myUtility::getRealIpAddr();
    myUtility::log("$ip get info from $src".($tbluser? ' ('.$tbluser->getUsUsername().')': ' failed'), 'apiuser.log');
    return $this->renderText($result);
  }*/

  public function executeGetinfo() {
    $src = $this->getRequestParameter('src');
    $us_id = $this->getRequestParameter('us_id');
    $uname = $this->getRequestParameter('username');
    $email = $this->getRequestParameter('email');
    $phone = $this->getRequestParameter('phone');
    $token = $this->getRequestParameter('token');

	$passwd_only = $this->getRequestParameter('ponly');

    if ($src == null) return sfView::NONE;

    if ($us_id && $token==md5($us_id.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_ID, $us_id);
    if ($uname && $token==md5($uname.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_USERNAME, $uname);
    if ($email && $token==md5($email.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_EMAIL, $email);
    if ($phone && $token==md5($phone.self::TOKENPW)) $tbluser = $this->getUserField(TbluserPeer::US_PHONE, $phone);

    if ($tbluser) 
		$result = !$passwd_only ? $this->getUserInfo($tbluser) : $this->getPEncrypted($tbluser);
    else return sfView::NONE;

    $ip = myUtility::getRealIpAddr();
    myUtility::log("$ip get info from $src".($tbluser? ' ('.$tbluser->getUsUsername().')': ' failed'), 'apiuser.log');
    return $this->renderText($result);
  }

  public function executeUpdate() {
    $src = $this->getRequestParameter('src');
    $us_id = $this->getRequestParameter('us_id');
    $username = $this->getRequestParameter('username');
    $password = $this->getRequestParameter('password');
    $fullname = $this->getRequestParameter('fullname'); 
    $gender = $this->getRequestParameter('gender'); 
    $email = $this->getRequestParameter('email');
    $phone = $this->getRequestParameter('phone');
    $school = $this->getRequestParameter('school');
    $province = $this->getRequestParameter('province');
    $token = $this->getRequestParameter('token');
    $sendmail = $this->getRequestParameter('sendmail');
    $oldpass = $this->getRequestParameter('oldpass');

    if ($src == null) return $this->renderText('status=10');
    //if ($this->validateData($fullname, $email, $phone, $error, false)) return $this->renderText('status=7&errMsg='.$error);
	
	if ($us_id == null) {      
      if ($token != md5($username.self::TOKENPW)) return $this->renderText('status=10');
      if (!$username || !$password /*|| !$fullname*/) return $this->renderText('status=1&errMsg=Not enough data');
      if ($this->getUserField(TbluserPeer::US_USERNAME, $username)) return $this->renderText('status=2&errMsg=Username has existed');
      if ($this->getUserField(TbluserPeer::US_EMAIL, $email)) return $this->renderText('status=3&errMsg=Email has existed');
      if ($this->getUserField(TbluserPeer::US_PHONE, $phone)) return $this->renderText('status=4&errMsg=Phone number has existed');
      
	  $tbluser = new Tbluser();
	  $tbluser->setUsRegisterdate(date('Y-m-d H:i:s'));
      $tbluser->setUsScore(sfConfig::get('app_user_start_point'));  	  

    } else {	  
      if ($token != md5($us_id.self::TOKENPW)) return $this->renderText('status=10');
      if ($username != null && $this->getUserField(TbluserPeer::US_USERNAME, $username, $us_id)) return $this->renderText('status=2&errMsg=Username has existed');
      if ($email != null && $this->getUserField(TbluserPeer::US_EMAIL, $email, $us_id)) return $this->renderText('status=3&errMsg=Email has existed');
      if ($phone != null && $this->getUserField(TbluserPeer::US_PHONE, $phone, $us_id)) return $this->renderText('status=4&errMsg=Phone number has existed');

      $tbluser = TbluserPeer::retrieveByPK($us_id);
      if ($tbluser == null) return $this->renderText('status=5&errMsg=User not found');
      if (($username != null || $password != null) && md5($oldpass) != $tbluser->getUsPassword() && $src != 'SBG') return $this->renderText('status=6&errMsg=Incorrect old password');
      if ($email != null && $email != $tbluser->getUsEmail()) $tbluser->setEmailConfirm(0);
      if ($phone != null && $phone != $tbluser->getUsPhone()) $tbluser->setMobileConfirm(0);
    }

    if ($username != null) $tbluser->setUsUsername($username);
    if ($password != null) $tbluser->setUsPassword(md5($password));
    if ($fullname != null) $tbluser->setUsFullname($fullname);
    if ($gender != null) $tbluser->setUsSex($gender=='male'? 1: 2);
    if ($email != null) $tbluser->setUsEmail($email);
    if ($phone != null) $tbluser->setUsPhone($phone);
    if ($school != null) $tbluser->setUsSchool($school);
    if ($province != null) $tbluser->setUsProvince($province);

	$tbluser->save();

	if ($sendmail == 'true') userMessage::sendConfirmEmail($tbluser, $password);
    $ip = myUtility::getRealIpAddr();
    $act = ($us_id == null? 'create': 'update');
    myUtility::log("$ip $act from $src".($tbluser? ' ('.$tbluser->getUsUsername().')': ' failed'), 'apiuser.log');
    return $this->renderText('status=0&id='.$tbluser->getUsId());
  }

  public function executeForgotpassword() {
    $src = $this->getRequestParameter('src');
    $email = $this->getRequestParameter('email');
    $token = $this->getRequestParameter('token');
    if ($src != null && $email != null && $token == md5($email.self::TOKENPW)) {
      $c = new Criteria();
      $c->add(TbluserPeer::US_EMAIL, trim($email));
      $tbluser = TbluserPeer::doSelectOne($c);
      if ($tbluser != null) {
        $res = userMessage::sendForgotPassEmail($tbluser);
        $ip = myUtility::getRealIpAddr();
        $acc = $tbluser->getUsUsername();
        myUtility::log("$ip from $src get password ($acc)".($res?'':' failed'), 'apiuser.log');
        return $this->renderText('status=0');
      }
      return $this->renderText('status=1&errMsg=Email not found');
    }
    return $this->renderText('status=10');
  }

  public function executeGetonlineuser() {
    return sfView::NONE;
  }

  public function executeGetprice() {
    $products = $this->getRequestParameter('product');
    $products = explode(',', $products);
    $result = '';
    foreach ($products as $product) {
      $c = new Criteria();
      $c->add(TblproductPeer::PRO_NAME, $product);
      $tblprod = TblproductPeer::doSelectOne($c);
      if ($tblprod) $result .= '&'.$product.'='.$tblprod->getProPrice();
    }
    return $this->renderText($result);
  }

  public function executePayment() {
    $src = $this->getRequestParameter('src');
    $us_id = $this->getRequestParameter('us_id');
    $product = $this->getRequestParameter('product');
    $token = $this->getRequestParameter('token');
    if ($src == null || $token != md5($us_id.self::TOKENPW)) return $this->renderText('status=10');

    $c = new Criteria();
    $c->add(TblproductPeer::PRO_NAME, $product);
    $tblprod = TblproductPeer::doSelectOne($c);
    $price = $tblprod->getProPrice();

    $tbluser = TbluserPeer::retrieveByPk($us_id);
    if ($tbluser == null) return $this->renderText('status=1&errMsg=User not found');
    if ($tbluser->getUsMoney() < $price) return $this->renderText('status=2&errMsg=Not enough money');
    $tbluser->doTransaction(-$price, 'pay', $product);

    if ($tblprod->getProType() > 0) {
      if ($tbllic = $tblprod->getUserLicense($us_id)) {
        $exp = $tbllic->getLiExpiredate();
        $start = strtotime($exp) > time()? $exp: date('Y-m-d H:i:s');
        $tbllic->setLiExpiredate(date('Y-m-d H:i:s', strtotime($start.' + 1 year')));
        $tbllic->save();
      } else {
        $tblprod->createUserLicense($us_id, 1);
      }
    }
    $ip = myUtility::getRealIpAddr();
    $acc = $tbluser->getUsUsername();
    myUtility::log("$ip pay $price from $src ($acc)", 'apiuser.log');
    return $this->renderText('status=0&price='.$price.'&money='.$tbluser->getUsMoney());
  }

  public function executeActivate() {
    $arParams['access_key']   = $this->getRequestParameter('access_key', 'no_access_key');
    $arParams['command']      = $this->getRequestParameter('command', 'no_command');
    $arParams['mo_message']   = $this->getRequestParameter('mo_message', 'no_mo_message');
    $arParams['msisdn']       = $this->getRequestParameter('msisdn', 'no_msisdn');
    $arParams['request_id']   = $this->getRequestParameter('request_id', 'no_request_id');
    $arParams['request_time'] = $this->getRequestParameter('request_time', 'no_request_time');
    $arParams['short_code']   = $this->getRequestParameter('short_code', 'no_short_code');
    $arParams['signature']    = $this->getRequestParameter('signature', 'no_signature');

    $data  = "access_key=" . $arParams['access_key'] . "&command=" . $arParams['command'] . "&mo_message=" . $arParams['mo_message'] . "&msisdn=" . $arParams['msisdn'];
    $data .= "&request_id=" . $arParams['request_id'] . "&request_time=" . $arParams['request_time'] . "&short_code=" . $arParams['short_code'];
    $secret = 'evvx931itxysfnp9m94rf2vxd101zegr';
    $signature = hash_hmac("sha256", $data, $secret);

    $smsPrice = array('80'=>500, '81'=>1000, '82'=>2000, '83'=>3000, '84'=>4000, '85'=>5000, '86'=>10000, '87'=>15000);
    $money = @$smsPrice[substr($arParams['short_code'], 0, 2)];

    if ($arParams['signature'] == $signature) {
      $phone = preg_replace('/^84/', '0', $arParams['msisdn']);
      preg_match('/^nc +(\w+) *(\d*)/i', $arParams['mo_message'], $match);
      $key = strtolower(@$match[1]);
      $uid = @$match[2];
      $findid = ($key == 'nt' && is_numeric($uid));
      if ($findid) $tbluser = TbluserPeer::retrieveByPk($uid);
      else $tbluser = $this->getUserField(TbluserPeer::US_PHONE, $phone);

      if ($tbluser != null) {
        switch ($key) {
        case 'kh':
          if ($tbluser->getMobileConfirm() == 0) {
            $tbluser->setUsScore($tbluser->getUsScore() + sfConfig::get('app_user_activate_point'));
            $tbluser->setMobileConfirm(1);
            $tbluser->save();
            $arResponse['sms'] = 'Kich hoat thanh cong tai khoan '.$tbluser->getUsUsername();
          } else {
            $arResponse['sms'] = 'Tai khoan '.$tbluser->getUsUsername().' da duoc kich hoat';
          }
          break;
        case 'mk':
          $passwd = myUtility::create_password();
          $tbluser->setUsPassword(md5($passwd));
          $tbluser->setMobileConfirm(1);
          $tbluser->save();
          $arResponse['sms'] = 'Tai khoan Violet.vn, ten truy nhap: '.$tbluser->getUsUsername().', mat khau: '.$passwd;
          break;
        case 'nt':
          $tbluser->doTransaction($money, 'sms', $phone);
          $arResponse['sms'] = 'Tai khoan '.$tbluser->getUsUsername().' da duoc nap them '.$money.' dong, hien dang co '.$tbluser->getUsMoney().' dong';
          break;
        default:
          $arResponse['sms'] = 'Tin nhan cua quy vi khong dung cu phap cua Violet.vn';
        }
      } else {
        $arResponse['sms'] = 'Khong tim thay tai khoan nao co '.($findid? ('id '.$uid): ('so dien thoai '.$phone)).' tren Violet.vn';
      }
    } else {
      $arResponse['sms'] = 'Sai chu ky';
    }

    $arResponse['status'] = 1;
    $arResponse['type'] = 'text';
    myUtility::log($arParams['msisdn'].': '.$arParams['mo_message'].' -> '.$arParams['short_code'].' | '.$arResponse['sms'], 'sms.log');
    return $this->renderText(json_encode($arResponse));
  }

  private function execPostRequest($url, $data){ 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);	
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);	 
    curl_close($ch);
    return $result;
  }

  public function executeCardcharge() {
    $src = $this->getRequestParameter('src');
    $us_id = $this->getRequestParameter('us_id');
    $token = $this->getRequestParameter('token');
    if ($src == null || $token != md5($us_id.self::TOKENPW)) return $this->renderText('status=10');

    $tbluser = TbluserPeer::retrieveByPk($us_id);
    if ($tbluser == null) return $this->renderText('status=5&errMsg=User not found');

    $access_key = 'in3je3d6lxh8zx8m68ox';
    $secret = 'evvx931itxysfnp9m94rf2vxd101zegr';
    $type = $this->getRequestParameter('type');
    $pin = $this->getRequestParameter('pin');
    $serial = $this->getRequestParameter('serial');

    $data = "access_key=".$access_key."&pin=".$pin."&serial=".$serial."&type=".$type;
    $signature = hash_hmac("sha256", $data, $secret);
    $data .= "&signature=".$signature;
    $res = json_decode($this->execPostRequest('https://api.1pay.vn/card-charging/v2/topup', $data));
    $status = (int)$res->status;
    $amount = (int)$res->amount;
    $desc = $res->description;

    if ($status == 0) $tbluser->doTransaction($amount*2, 'card', $serial);
    $ip = myUtility::getRealIpAddr();
    myUtility::log("$ip load $type $serial (pin $pin) from $src: ".($status==0? $amount.'VND': $desc), 'card.log');
    return $this->renderText('status='.$status.'&amount='.$amount.'&money='.$tbluser->getUsMoney().'&errMsg='.$desc);
  }
}

?>