<?php
/**
 * Open Source Social Network
 *
 * @package   (softlab24.com).ossn
 * @author    OSSN Core Team <info@softlab24.com>
 * @copyright 2014-2017 SOFTLAB24 LIMITED
 * @license   SOFTLAB24 LIMITED, COMMERCIAL LICENSE  https://www.softlab24.com/license/commercial-license-v1
 * @link      https://www.softlab24.com/
 */
namespace Softlab24\Ossn\Component;
class Polls extends \OssnObject {
		/** 
		 * Poll Add
		 * 
		 * @param string  $title A title for poll
		 * @param integer $container_guid  A guid who own the poll
		 * @param integer $container_type  A type of container
		 * @param array   #options     Poll options
		 * 
		 * @return boolean
		 */
		public function addPoll($title = '', $container_guid = 0, $container_type = 0, array $options = array()) {
				if (empty($container_guid) || empty($container_type) || empty($title) || empty($options)) {
						return false;
				}
				$options_hashed = array();
				foreach ($options as $option) {
						//we need these to make use in later for finding out the option votes
						$options_hashed[md5($option)] = trim($option);
				}
				$this->title       = $title;
				$this->description = json_encode($options_hashed, JSON_UNESCAPED_UNICODE);
				$this->type        = 'user';
				$this->subtype     = 'poll:item';
				$this->owner_guid  = ossn_loggedin_user()->guid; //because poll is always created by the user.
				
				$this->data->container_guid = $container_guid;
				$this->data->container_type = $container_type;
				$this->data->is_ended       = false;
				if ($guid = $this->addObject()) {
						$object     = ossn_get_object($guid);
						//entity is required for comments,  wall etc.
						$entity_add = ossn_add_entity(array(
								'type' => 'object',
								'subtype' => 'poll_entity',
								'value' => true,
								'owner_guid' => $guid
						));
						if ($entity_add) {
								//here we are passing object guid as item_guid because when we get item, it will have entity guid already
								$this->addWall($container_type, $container_guid, $guid);
								
								$entities = ossn_get_entities(array(
										'type' => 'object',
										'subtype' => 'poll_entity',
										'owner_guid' => $guid
								));
								if (isset($entities[0])) {
										$object->data->poll_entity = $entities[0]->guid;
										$object->save();
								}
						}
						ossn_trigger_callback('poll', 'created', array(
								'guid' => $guid
						));
						return $guid;
				}
				return false;
		
		    
		    
	$user = ossn_loggedin_user();
			
						$container_guid = $this->data->container_guid;
						$container_type = $this->data->container_type;
						if($this->addObject()) {
								$object_guid = $this->getObjectId();
								$this->addWall($container_type, $container_guid, $this->pollEntityAdd($object_guid));
								//add event image
								if(isset($_FILES['picture'])) {
										$this->file->owner_guid = $object_guid;
										$this->file->type       = 'object';
										$this->file->subtype    = 'poll:photo';
										$this->file->setFile('picture');
										$this->file->setPath('poll/photo/');
										$this->file->setExtension(array(
												'jpg',
												'png',
												'jpeg',
												'gif'
										));
										if(!$this->file->addFile()) {
												//delete event if image creation failed.
												$this->deleteObject($this->file->owner_guid);
												return false;
										}
										$resize = $this->file->getFiles();
										//resize event image and create one small one of 150x150
										if(isset($resize->{0})) {
												$guid      = $user->guid;
												$datadir   = ossn_get_userdata("object/{$this->file->owner_guid}/{$resize->{0}->value}");
												$file_name = str_replace('poll/photo/', '', $resize->{0}->value);
												
												$resized = ossn_resize_image($datadir, 250, 250, true);
												file_put_contents(ossn_get_userdata("object/{$this->file->owner_guid}/poll/photo/small_{$file_name}"), $resized);
										}
								}
								//return the event guid
								return $this->getObjectId();
						}
				
				return false;
		    
		    
		    
		    
		    
		    
		    
		    
		    
		}
		
		
		
		
		/** 
		 * Get options
		 *
		 * @return array
		 */
		public function getOptions() {
				return json_decode($this->description, true);
		}
		/** 
		 * Add poll to the wall
		 * 
		 * @param string  $walltype    User/group/page
		 * @param integer $owner_guid  Owner GUID
		 * @param integer $item_guid   Poll wall item guid
		 * 
		 * @return boolean
		 */
		public function addWall($walltype = "user", $owner_guid = "", $itemguid = '') {
				if (empty($itemguid) || !class_exists("OssnWall")) {
						return false;
				}
				$this->wall              = new \OssnWall;
				$this->wall->type        = $walltype;
				$this->wall->item_type   = 'poll:item';
				$this->wall->owner_guid  = $owner_guid;
				$this->wall->poster_guid = ossn_loggedin_user()->guid;
				$this->wall->item_guid   = $itemguid;
				if($walltype !== 'user'){
						$access = OSSN_PRIVATE;
				}	
				if ($this->wall->Post('null:data', '', '', $access)) {
						return true;
				}
				return false;
		}
		/** 
		 * Check if user has voted for poll or not
		 * 
		 * @return boolean
		 */
		public function hasVoted() {
				if (!isset($this->guid)) {
						return false;
				}
				$annotation = new \OssnAnnotation;
				$list       = $annotation->searchAnnotation(array(
						'type' => 'poll:item',
						'owner_guid' => ossn_loggedin_user()->guid,
						'subject_guid' => $this->guid,
						'offset' => 1,
				));
				if ($list) {
						return $list[0]->getParam('poll:item');
				}
				return false;
		}
		/** 
		 * Get all the votes for the poll
		 * 
		 * @return array
		 */
		public function getVotes() {
				if (!isset($this->guid)) {
						return false;
				}
				$annotation = new \OssnAnnotation;
				$list       = $annotation->searchAnnotation(array(
						'type' => 'poll:item',
						'subject_guid' => $this->guid,
						'page_limit' => false
				));
				$types      = array();
				if ($list) {
						foreach ($list as $item) {
								$types[$item->getParam('poll:item')][] = $item->id;
						}
						foreach ($types as $k => $type) {
								$results[$k] = count($type);
						}
						$total_votes = array_sum($results);
						foreach ($results as $r => $result) {
								$total_percentages[$r] = ceil(($result / $total_votes) * 100);
						}
						return $total_percentages;
				}
				return false;
		}
		/** 
		 * Add vote
		 * 
		 * @param string  $option    A option value
		 * 
		 * @return boolean
		 */
		public function addVote($option = '') {
				if (empty($option) || !isset($this->guid)) {
						return false;
				}
				if ($voted = $this->hasVoted()) {
						return $voted;
				}
				$annotation               = new \OssnAnnotation;
				$annotation->owner_guid   = ossn_loggedin_user()->guid;
				$annotation->subject_guid = $this->guid;
				$annotation->value        = $option;
				$annotation->type         = 'poll:item';
				if ($annotation->addAnnotation()) {
						return $option;
				}
				return false;
		}
		/**
		 * Get all Polls
		 *
		 * @param array $params A options
		 *
		 * @return array
		 */
		public function getAll(array $params = array()) {
				$default             = array();
				$default['type']     = 'user';
				$default['subtype']  = 'poll:item';
				$default['order_by'] = 'o.guid DESC';
				
				$vars = array_merge($default, $params);
				return $this->searchObject($vars);
		}
		/** 
		 * Get poll URL
		 * 
		 * @param boolean  $base   TRUE to include base URL
		 * 
		 * @return string
		 */
		public function getURL($base = true) {
				$title = \OssnTranslit::urlize($this->title);
				$URL   = "polls/view/{$this->guid}/{$title}";
				if (!$base) {
						return $URL;
				}
				return ossn_site_url($URL);
		}
		/**
		 * Remove file data
		 *
		 * @return void
		 */
		public function removeData() {
				$guid   = $this->guid;
				$entity = ossn_get_entities(array(
						'type' => 'object',
						'owner_guid' => $guid,
						'subtype' => 'poll_entity'
				));
				if (class_exists('OssnNotifications') && !empty($entity[0]->guid)) {
						$ndelete = new \OssnNotifications;
						$ndelete->deleteNotification(array(
								'subject_guid' => $entity[0]->guid,
								'type' => array(
										'comments:entity:poll_entity',
										'like:entity:poll_entity'
								)
						));
				}
				if (class_exists('OssnComments') && !empty($entity[0]->guid)) {
						$comments     = new \OssnComments;
						$comments_all = $comments->GetComments($entity[0]->guid, 'entity');
						foreach ($comments_all as $comment) {
								$comment->deleteComment($comment->id);
						}
				}
				if (class_exists('OssnLikes') && !empty($entity[0]->guid)) {
						$likes     = new \OssnLikes;
						$likes_all = $likes->deleteLikes($entity[0]->guid, 'entity');
				}
				if (class_exists('OssnWall') && !empty($guid)) {
						$wall       = new \OssnWall;
						$wall_posts = $wall->searchObject(array(
								'subtype' => 'wall',
								'entities_pairs' => array(
										array(
												'name' => 'item_type',
												'value' => 'poll:item'
										),
										array(
												'name' => 'item_guid',
												'value' => $guid
										)
								)
						));
						if ($wall_posts) {
								foreach ($wall_posts as $item) {
										$item->deletePost($item->guid);
								}
						}
				}
				$annotation = new \OssnAnnotation;
				$list       = $annotation->searchAnnotation(array(
						'type' => 'poll:item',
						'subject_guid' => $this->guid
				));
				if ($list) {
						foreach ($list as $item) {
								$item->deleteAnnotation($item->id);
						}
				}
		}
		
		
				public function saveImage($guid) {
				if(isset($_FILES['picture']) && !empty($_FILES['picture']['name']) && !empty($guid)) {
						
						$entity             = new OssnEntities;
						$entity->type       = 'object';
						$entity->owner_guid = $guid;
						$entity->subtype    = 'file:poll:photo';
						$pics               = $entity->get_entities();
						foreach($pics as $pic) {
								$entity->deleteEntity($pic->guid);
						}
						OssnFile::DeleteDir(ossn_get_userdata("object/{$guid}/poll/photo/"));
						
						self::initAttrs();
						$this->file->owner_guid = $guid;
						$this->file->type       = 'object';
						$this->file->subtype    = 'poll:photo';
						$this->file->setFile('picture');
						$this->file->setPath('poll/photo/');
						$this->file->setExtension(array(
								'jpg',
								'png',
								'jpeg',
								'gif'
						));
						
						if(!$this->file->addFile()) {
								return false;
						}
						
						//reget the files
						$resize = $this->file->getFiles();
						//resize event image and create one small one of 150x150
						if(isset($resize->{0})) {
								$guid      = $user->guid;
								$datadir   = ossn_get_userdata("object/{$this->file->owner_guid}/{$resize->{0}->value}");
								$file_name = str_replace('poll/photo/', '', $resize->{0}->value);
								
								$resized = ossn_resize_image($datadir, 250, 250, true);
								file_put_contents(ossn_get_userdata("object/{$this->file->owner_guid}/poll/photo/small_{$file_name}"), $resized);
						}
				}
				return true;
				}



public function iconURL($size = 'small') {
				$hash = md5($this->guid . $this->last_update);
				return ossn_site_url("poll/image/{$this->guid}/{$size}/{$hash}.jpg");
		}
		/**
		 * Event profile URL
		 *
		 * @return string
		 */
		public function profileURL() {
				$title = OssnTranslit::urlize($this->title);
				return ossn_site_url("poll/view/{$this->guid}/{$title}");
		}
		/**
		 * Get events
		 * 
		 * @param array $params A option values
		 *
		 * @return array
		 */
		public function getPolls(array $params = array()) {
				$default = array(
						'type' => 'user',
						'subtype' => 'poll',
						'order_by' => 'o.guid DESC',
				);
				if(POLLS_SORT_BY_DATE){
					$pairs = $params['entities_pairs'];
					unset($params['entities_pairs']);
					$params['entities_pairs'][] = array(
												'name' => 'date',
												'value' => false,
												'wheres' => 'emd0.value IS NOT NULL',
					);
					if(isset($pairs)){
						foreach($pairs as $pair){
								$params['entities_pairs'][] = $pair;
						}
					}
					$default['order_by'] = "STR_TO_DATE(emd0.value, '%c/%d/%Y') ASC";
				}				
				$vars    = array_merge($default, $params);
				return $this->searchObject($vars);
		}
		/**
		 * Event add entity for wall post
		 * 
		 * @param integer $guid A event GUID
		 *
		 * @return boolean
		 */
		private function pollEntityAdd($guid) {
				if(empty($guid)) {
						return false;
				}
				$entity             = new OssnEntities;
				$entity->type       = 'object';
				$entity->owner_guid = $guid;
				$entity->subtype    = 'poll:wall';
				$entity->value      = true;
				if($entity->add()) {
						return $entity->AddedEntityGuid();
				}
				return false;
		}





		
}





/**
 * Open Source Social Network
 *
 * @packageOpen Source Social Network
 * @author    Open Social Website Core Team <info@informatikon.com>
 * @copyright 2014 iNFORMATIKON TECHNOLOGIES
 * @license   General Public Licence http://www.opensource-socialnetwork.org/licence
 * @link      http://www.opensource-socialnetwork.org/licence
 */

		/**
		 * Initialize The Attrs
		 *
		 * @return void
		 */
	
		/**
		 * Add the event
		 * 
		 * @param  string $title A event title
		 * @param  string $info A description for event
		 * @param  $container_guid If its a group event
		 * @param  $params A option values
		 *
		 * @return boolean
		 */
	
				
		
		/**
		 * Save the image for event
		 * 
		 * @param integer $guid A event guid
		 *
		 * @return boolean
		 */

		
		/**
		 * Event icon URL
		 * 
		 * @param string $size A size of icon
		 *
		 * @return string
		 */
		
		
