<?php
namespace Modules\Partners\Customers\Deduplicate\Model\CronJobSuggestions;

/**
 * A suggestions class that goes through the whole DB and returns all possible combinations
 * - doesn't use any sql special cases to try and pre-order/filter any kind of results
 * - REALLY SLOW, avoid unless needed
 * - it should give the most accurate results, but with lots of low-grade-scores
 * - it will issue a LOT of simple SQL statements
 * - the most basic scanner
 * @author Lucian Sirbu
 *
 */
class Simple extends GeneralAbstract
{

	private $results;

	public function initialize()
	{
	}

	public function destroy()
	{
		$this->results = [];
	}

	public function getGroups()
	{
		global $DBTCustomers;

		$query = "SELECT `id` FROM `{$DBTCustomers}`
			WHERE 1
				AND deleted=0
				AND locked=0
				AND idRealCustomer=0
			ORDER BY
				`id` ASC
		";

		if ($this->resultsLimit) {
			$query.= " LIMIT {$this->resultsLimit}";
		}

		$results = \DB::getInstance()->Execute($query);
		if (\DB::getInstance()->ErrorNo()) {
			throw new \DBException("Could not get the customers list", $query);
		}

		$f = function($collection) {
			foreach( $collection as $element ) {
				yield $element['id'];
		    }
		};

		$this->results = $f($results);
		return $this->results;
	}

	public function getGroupCounts()
	{
		global $DBTCustomers;

		$query = "SELECT COUNT(*) FROM `{$DBTCustomers}`
			WHERE 1
				AND deleted=0
				AND locked=0
				AND idRealCustomer=0
		";

		if ($this->resultsLimit) {
			$query.= " LIMIT {$this->resultsLimit}";
		}

		$results = \DB::getInstance()->GetOne($query);
		if (\DB::getInstance()->ErrorNo()) {
			throw new \DBException("Could not get the customers list", $query);
		}

		return $results;
	}

	public function getGroupMatches($group)
	{
		global $DBTCustomers;

		$query = "SELECT c1.`id` AS id1, c2.`id` AS id2
			FROM `{$DBTCustomers}` AS c1, `{$DBTCustomers}` AS c2
			WHERE 1
				AND c1.deleted=0
				AND c1.locked=0
				AND c1.idRealCustomer=0
				AND c2.deleted=0
				AND c2.locked=0
				AND c2.idRealCustomer=0
				AND c1.id=?
				AND c2.id>c1.id
			ORDER BY
				c2.`id` ASC
		";

		$results = \DB::getInstance()->Execute($query, [$group, ]);
		if (\DB::getInstance()->ErrorNo()) {
			throw new \DBException("Could not get the customers list", $query);
		}

		return $results;
	}

	public function getGroupMatchesCounts($group)
	{
		global $DBTCustomers;

		$query = "SELECT COUNT(*)
			FROM `{$DBTCustomers}` AS c1, `{$DBTCustomers}` AS c2
			WHERE 1
				AND c1.deleted=0
				AND c1.locked=0
				AND c1.idRealCustomer=0
				AND c2.deleted=0
				AND c2.locked=0
				AND c2.idRealCustomer=0
				AND c1.id=?
				AND c2.id>c1.id
		";

		$results = \DB::getInstance()->GetOne($query, [$group, ]);
		if (\DB::getInstance()->ErrorNo()) {
			throw new \DBException("Could not get the customers list", $query);
		}

		return $results;
	}
}
