<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/

class Stories_Model_DbTable_Userinfos extends Core_Model_Item_DbTable_Abstract
{
	protected $_rowClass = "Stories_Model_Userinfo";
	protected $_name = "stories_userinfos";

	public function getAllUserHaveStories($params = array())
	{

		// Get an array of friend ids
		$viewer = Engine_Api::_()->user()->getViewer();
		$userTable = Engine_Api::_()->getItemTable('user');
		$selectFriend = $viewer->membership()->getMembersSelect('user_id');
		$friends = $userTable->fetchAll($selectFriend);
		// Get stuff
		$ids = array('0');
		foreach ($friends as $friend) {
			$ids[] = $friend->user_id;
		}

		$storiesTable = Engine_Api::_()->getDbTable('stories', 'stories');
		$storiesTableName = $storiesTable->info('name');

		$tableName = $this->info('name');
		$days = Engine_Api::_()->getApi('settings', 'core')->getSetting("stories.dayslimit", 1);

		$privacy = array();

		$privacy[] = "(engine4_stories_userinfos.view_privacy = 'onlyme' AND engine4_stories_userinfos.owner_id = " . $params['user_id'] . ' )';
		$privacy[] = "(engine4_stories_userinfos.view_privacy = 'owner' AND engine4_stories_userinfos.owner_id = " . $params['user_id'] . ' )';
		$privacy[] = "(engine4_stories_userinfos.view_privacy = 'owner_member' AND engine4_stories_userinfos.owner_id IN ( " . implode(",", $ids) . ")" . ' )';
		$privacy[] = "(engine4_stories_userinfos.view_privacy = 'registered' AND " . $viewer->getIdentity() . " != 0" . ' )';
		$privacySql = implode(" OR ", $privacy);

		$select = $this->select()
			->setIntegrityCheck(false)
			->from($tableName)
			->joinRight($storiesTableName, $storiesTableName . '.owner_id =' . $tableName . '.owner_id', null)
			->where($storiesTableName . '.creation_date >= now() - INTERVAL ' . $days . ' DAY')
			->group($storiesTableName . '.owner_id');
		//If current user have friends then friends and registered member story see
		$select->where($privacySql);
		return $this->fetchAll($select);
	}

	public function isPrivacyExist($user_id)
	{

		$userinfoTableName = $this->info('name');
		return $this->select()
			->from($userinfoTableName, 'view_privacy')
			->where('owner_id = ?', $user_id)
			->query()
			->fetchColumn();
	}
}
