<?php
namespace Hona\ApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Hona\AdminBundle\Entity\User;
use Hona\AdminBundle\Entity\UserHasAddress;
use Hona\ApiBundle\Library\Utils;
use Hona\ApiBundle\Exception\DuplicatedUniqueFieldsException;
use Hona\ApiBundle\Exception\NotFoundEntityException;
use Hona\ApiBundle\Exception\NotValidRelationshipException;
class UserController extends EntityController
{
protected $required = array("name", "last_name");
protected $unique = array("email");
protected $relationship = array("address", "control_gate", "residential");
protected function _validateAfterGET(Request $request, $entity, $uuid, &$data, $clean){
if(!empty($request->get("fields"))){
$fields = explode(",", $request->get("fields"));
foreach ($fields as $field) {
if($field != "notification_setting"){
$this->_addListEntities($field, "user_has_".$field, $data["id"], $data, $clean);
}
}
if (in_array("notification_setting", $fields)) {
$this->_addEntity("notification_setting", array("user_id" => $data["id"]), $data);
}
}
if(!empty($data["media_path"])){
$data["media_path"] = Utils::addMediaDomainToPath($data["media_path"]);
}
if(!empty($data["thumb_path"])){
$data["thumb_path"] = Utils::addMediaDomainToPath($data["thumb_path"]);
}
}
protected function _validateBeforePOST(Request $request, $entity, &$data){
if(array_key_exists("password", $data)){
$data["password"] = hash($this->container->getParameter('encryption_hash'), $data["password"]);
}
if(!isset($data["status"])){
$data["status"] = Utils::ACTIVE;
}
}
protected function _validateAfterPOST(Request $request, $entity, $uuid, &$data, $clean){
}
protected function _validateBeforePUT(Request $request, $entity, $uuid, &$data){
if(array_key_exists("password", $data)){
$data["password"] = hash($this->container->getParameter('encryption_hash'), $data["password"]);
}
}
/**
* @Route("/user/{uuid}", name="user_get_uuid", methods={"GET"})
* @param $request
*/
public function userGETAction(Request $request, $uuid)
{
return $this->_entityGET($request, "user", $uuid);
}
/**
* @Route("/user", name="user_post_uuid", methods={"POST"})
* @param $request
*/
public function userPOSTAction(Request $request)
{
return $this->_entityPOST($request, "user");
}
/**
* @Route("/user/family/member/create", name="family_post_uuid", methods={"POST"})
* @param $request
*/
public function userFamiliyPOSTAction(Request $request)
{
try{
$entityManager = $this->getDoctrine()->getManager();
$parentUser = $this->getUser();
$dataRequest = json_decode($request->getContent(), true);
$addressUuid = $dataRequest["addressUuid"];
$address = $entityManager->getRepository(Utils::getClassName("Address"))->findOneByUuid($addressUuid);
$user = null;
if(isset($dataRequest["email"]) && isset($dataRequest["phone"])){
$user = $entityManager->getRepository(Utils::getClassName("User"))->findOneByEmailOrPhone($dataRequest["email"], $dataRequest["phone"]);
}elseif(isset($dataRequest["email"])){
$user = $entityManager->getRepository(Utils::getClassName("User"))->findOneByEmail($dataRequest["email"]);
}
elseif(isset($dataRequest["phone"])){
$user = $entityManager->getRepository(Utils::getClassName("User"))->findOneByPhone($dataRequest["phone"]);
}
if($user == null){
$dataUser = array();
$dataUser["name"] = $dataRequest["name"];
$dataUser["last_name"] = $dataRequest["lastName"];
$dataUser["status"] = Utils::NEEDCONFIRMATION;
$dataUser["email_verification"] = false;
$dataUser["phone_verification"] = false;
$sendMail = false;
if(isset($dataRequest["email"]) && !empty($dataRequest["email"])){
$dataUser["email"] = $dataRequest["email"];
$sendMail = true;
}
if(isset($dataRequest["phone"]) && !empty($dataRequest["phone"])){
$dataUser["phone"] = $dataRequest["phone"];
}
if(isset($dataRequest["profileImage"])){
$imagePath = Utils::base64ToImage($dataRequest["profileImage"], strstr($email, '@', true), "user");
$dataUser["media_path"] = $imagePath;
$dataUser["thumb_path"] = $imagePath;
}
$familiyUser = $this->_entityPOST($request, "user", $dataUser);
if($sendMail){
$user = $entityManager->getRepository(Utils::getClassName("User"))->findOneByEmail($dataRequest["email"]);
$response = Utils::sendConfirmationEmail($this->get('twig'), $dataUser);
}else{
$user = $entityManager->getRepository(Utils::getClassName("User"))->findOneByPhone($dataRequest["phone"]);
}
}else{
$dataUser = array();
$dataUser["name"] = $dataRequest["name"];
$dataUser["last_name"] = $dataRequest["lastName"];
if(isset($dataRequest["email"]) && !empty($dataRequest["email"])){
$dataUser["email"] = $dataRequest["email"];
}
if(isset($dataRequest["phone"]) && !empty($dataRequest["phone"])){
$dataUser["phone"] = $dataRequest["phone"];
}
$familiyUser = $this->_entityPUT($request, "user", $user->getUuid(), $dataUser);
}
$userAddress = $entityManager->getRepository(Utils::getClassName("User_Has_Address"))->findOneByPrimaryKey(
array(
"userId" => $user->getId(),
"addressId" => $address->getId()
)
);
/*$parentUserAddress = $entityManager->getRepository(Utils::getClassName("User_Has_Address"))->findOneByPrimaryKey(
array(
"userId" => $parentUser->getId(),
"addressId" => $address->getId()
)
);*/
$permissionJson = Utils::getPermissionJson($dataRequest);
$color = $dataRequest["color"];
if($userAddress != null){
if($userAddress->getStatus() == Utils::DELETED){
$dataAddress = array();
$dataAddress['parent_id'] = $parentUser->getId();
$dataAddress['status'] = Utils::ACTIVE;
$dataAddress['date_modified'] = new \DateTime();
$dataAddress['permission'] = json_encode($permissionJson);
$dataAddress['color'] = $color;
/*if(isset($parentUserAddress)){
$dataAddress['rent'] = $parentUserAddress->getRent();
}else{
$dataAddress['rent'] = -1;
}*/
$familiyAddress = $this->forward('HonaApiBundle:UserHasAddress:userHasAddressPUT', [
'request' => $request,
'user_uuid' => $user->getUuid(),
'address_uuid' => $address->getUuid(),
'data' => $dataAddress
]);
/*if($user->getStatus() == Utils::NEEDCONFIRMATION){
$dataUser = array();
$dataUser["name"] = $dataRequest["name"];
$dataUser["last_name"] = $dataRequest["lastName"];
$dataUser["email"] = $email;
$response = Utils::sendConfirmationEmail($this->get('twig'), $dataUser);
}*/
}else{
throw new DuplicatedUniqueFieldsException(array("user_id","address_id"));
}
}else{
$dataAddress = array();
$dataAddress['user_id'] = $user->getId();
$dataAddress['address_id'] = $address->getId();
$dataAddress['parent_id'] = $parentUser->getId();
$dataAddress['status'] = Utils::ACTIVE;
$dataAddress['date_created'] = new \DateTime();
$dataAddress['date_modified'] = new \DateTime();
$dataAddress['permission'] = json_encode($permissionJson);
$dataAddress['color'] = $color;
$familiyAddress = $this->forward('HonaApiBundle:UserHasAddress:userHasAddressPOST', [
'request' => $request,
'user_uuid' => $user->getUuid(),
'address_uuid' => $address->getUuid(),
'data' => $dataAddress
]);
}
$request->attributes->set('fields', 'address');
$userFamiliy = $this->_entityGET($request, "user", $user->getUuid());
return $userFamiliy;
}catch(ErrorCodeException $exception){
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
'code' => $exception->getErrorCode()
];
return new JsonResponse($data, $exception->getStatusCode());
}catch(DuplicatedUniqueFieldsException $exception){
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
'code' => $exception->getErrorCode()
];
return new JsonResponse($data, $exception->getStatusCode());
}catch(HttpException $exception){
$data = [
'message' => $exception->getMessage()
];
return new JsonResponse($data, $exception->getStatusCode());
}
}
/**
* @Route("/user/family/member/{uuid}/address/{addressUuid}", name="family_put_uuid", methods={"PUT"})
* @param $request
*/
public function userFamiliyPUTAction(Request $request, $uuid, $addressUuid)
{
try{
$entityManager = $this->getDoctrine()->getManager();
$user = $entityManager->getRepository(Utils::getClassName("User"))->findOneByUuid($uuid);
if($user != null){
$dataRequest = json_decode($request->getContent(), true);
$dataUser = array();
$update = false;
if(isset($dataRequest["name"])){
$dataUser["name"] = $dataRequest["name"];
$update = true;
}
if(isset($dataRequest["lastName"])){
$dataUser["last_name"] = $dataRequest["lastName"];
$update = true;
}
if(isset($dataRequest["phone"])){
$dataUser["phone"] = $dataRequest["phone"];
$update = true;
}
if(isset($dataRequest["email"]) && !empty($dataRequest["email"])){
if($user->getEmail() != $dataRequest["email"] && $user->getEmailVerification() == 0){
$dataUser["email"] = $dataRequest["email"];
$update = true;
$response = Utils::sendConfirmationEmail($this->get('twig'), $dataUser);
}
}
if(isset($dataRequest["profileImage"])){
$imagePath = Utils::base64ToImage($dataRequest["profileImage"], strstr($user->getEmail(), '@', true), "user");
$dataUser["media_path"] = $imagePath;
$dataUser["thumb_path"] = $imagePath;
$update = true;
}
if($update)
$familiyUser = $this->_entityPUT($request, "user", $uuid, $dataUser);
$address = $entityManager->getRepository(Utils::getClassName("Address"))->findOneByUuid($addressUuid);
if($address == null)
throw new NotFoundEntityException($addressUuid);
$userAddress = $entityManager->getRepository(Utils::getClassName("User_Has_Address"))->findOneByPrimaryKey(
array(
"userId" => $user->getId(),
"addressId" => $address->getId()
)
);
if($userAddress != null){
$updateAddress = false;
$permission = Utils::getPermissionJson($dataRequest);
$dataAddress = array();
if(!empty($permission)){
$dataAddress['permission'] = json_encode($permission);
$updateAddress = true;
}
if(isset($dataRequest["color"])){
$dataAddress['color'] = $dataRequest["color"];
$updateAddress = true;
}
if($updateAddress){
$dataAddress['date_modified'] = new \DateTime();
$familiyAddress = $this->forward('HonaApiBundle:UserHasAddress:userHasAddressPUT', [
'request' => $request,
'user_uuid' => $user->getUuid(),
'address_uuid' => $address->getUuid(),
'data' => $dataAddress
]);
}
}else{
throw new NotValidRelationshipException("address_id");
}
$request->attributes->set('fields', 'address');
$userFamiliy = $this->forward('HonaApiBundle:User:userGET', [
'request' => $request,
'uuid' => $user->getUuid()
]);
return $userFamiliy;
}else{
throw new NotFoundEntityException($uuid);
}
}catch(ErrorCodeException $exception){
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
'code' => $exception->getErrorCode()
];
return new JsonResponse($data, $exception->getStatusCode());
}catch(NotFoundEntityException $exception){
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
'code' => $exception->getErrorCode()
];
return new JsonResponse($data, $exception->getStatusCode());
}catch(NotValidRelationshipException $exception){
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
'code' => $exception->getErrorCode()
];
return new JsonResponse($data, $exception->getStatusCode());
}catch(HttpException $exception){
$data = [
'message' => $exception->getMessage()
];
return new JsonResponse($data, $exception->getStatusCode());
}
}
/**
* @Route("/user/{uuid}", name="user_put_uuid", methods={"PUT"})
* @param $request
*/
public function userPUTAction(Request $request, $uuid, $data=null)
{
return $this->_entityPUT($request, "user", $uuid, $data);
}
/**
* @Route("/user/{uuid}", name="user_delete_uuid", methods={"DELETE"})
* @param $request
*/
public function userDELETEAction(Request $request, $uuid)
{
return $this->_entityDELETE($request, "user", $uuid);
}
}