<?php
/*
 * Copyright (c) 2026, Tribal Limited
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Zenario, Tribal Limited nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TRIBAL LTD BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


namespace ze;

class smartGroup {
	
	//Formerly "ZENARIO_NOT_IN_SMART_GROUP"
	const NOT_IN_SMART_GROUP = 'AND FALSE';
	

	public static function details($smartGroupId) {
		return \ze\row::get('smart_groups',
			[
				'name',
				'intended_usage',
				'must_match',
				'created_on',
				'created_by',
				'last_modified_on',
				'last_modified_by'
			]
			, $smartGroupId);
	}


	public static function sql(&$and, &$tableJoins, $smartGroupId, $list = true, $usersTableAlias = 'u', $customTableAlias = 'ucd') {
		return require \ze::funIncPath(__FILE__, __FUNCTION__);
	}

	public static function countMembers($smartGroupId) {
	
		$and = $tableJoins = '';
		if (\ze\smartGroup::sql($and, $tableJoins, $smartGroupId)) {
			return \ze\sql::fetchValue("
				SELECT COUNT(DISTINCT u.id)
				FROM ". DB_PREFIX. "users AS u
				LEFT JOIN ". DB_PREFIX. "users_custom_data AS ucd
				   ON ucd.user_id = u.id
				". $tableJoins. "
				WHERE TRUE
				". $and);
		}
	
		return false;
	}
	
	public static function countOptedOutMembers($smartGroupIds) {
		$optedOutMembers = [];
		
		foreach (\ze\ray::explodeAndTrim($smartGroupIds) as $smartGroupId) {
			$and = $tableJoins = '';
			if (\ze\smartGroup::sql($and, $tableJoins, $smartGroupId)) {
				$result = \ze\sql::select("
					SELECT DISTINCT u.id
					FROM ". DB_PREFIX. "users AS u
					LEFT JOIN ". DB_PREFIX. "users_custom_data AS ucd
					   ON ucd.user_id = u.id
					". $tableJoins. "
					WHERE TRUE
					AND ucd.all_newsletters_opt_out = 1
					". $and);
				
				while ($id = \ze\sql::fetchValue($result)) {
					if (!in_array($id, $optedOutMembers)) {
						$optedOutMembers[] = $id;
					}
				}
			}
		}
	
		return count($optedOutMembers);
	}
	
	public static function countMembersWhoDidNotAcceptTC($smartGroupIds) {
		$optedOutMembers = [];
		
		foreach (\ze\ray::explodeAndTrim($smartGroupIds) as $smartGroupId) {
			$and = $tableJoins = '';
			if (\ze\smartGroup::sql($and, $tableJoins, $smartGroupId)) {
				$result = \ze\sql::select("
					SELECT DISTINCT u.id
					FROM ". DB_PREFIX. "users AS u
					LEFT JOIN ". DB_PREFIX. "users_custom_data AS ucd
					   ON ucd.user_id = u.id
					". $tableJoins. "
					WHERE TRUE
					AND u.terms_and_conditions_accepted = 0
					". $and);
				
				while ($id = \ze\sql::fetchValue($result)) {
					if (!in_array($id, $optedOutMembers)) {
						$optedOutMembers[] = $id;
					}
				}
			}
		}
	
		return count($optedOutMembers);
	}
	
	public static function getMemberIds($smartGroupId) {
	
		$and = $tableJoins = '';
		if (\ze\smartGroup::sql($and, $tableJoins, $smartGroupId)) {
			$memberIds = [];
			$result = \ze\sql::select("
				SELECT u.id
				FROM ". DB_PREFIX. "users AS u
				LEFT JOIN ". DB_PREFIX. "users_custom_data AS ucd
				   ON ucd.user_id = u.id
				". $tableJoins. "
				WHERE TRUE
				". $and);
				
			while ($row = \ze\sql::fetchAssoc($result)) {
				$memberIds[] = $row['id'];
			}
			return $memberIds;
		}
	
		return false;
	}

	public static function isUserIn($smartGroupId, $userId = -1) {
	
		$and = $tableJoins = '';
		if ($userId === -1) {
			$userId = \ze\user::id();
		}
	
		if ($userId && \ze\smartGroup::sql($and, $tableJoins, $smartGroupId, false)) {
			return (bool) \ze\sql::fetchRow("
				SELECT 1
				FROM ". DB_PREFIX. "users AS u
				LEFT JOIN ". DB_PREFIX. "users_custom_data AS ucd
				   ON ucd.user_id = u.id
				". $tableJoins. "
				WHERE u.id = ". (int) $userId. "
				". $and. "
				LIMIT 1"
			);
		}
	
		return false;
	}

}