<?php

namespace Planaday\Database\MySQL\QueryBuilding\SQLOperators;

use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLOperators\SQLIn;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLQuery;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLUseInterfaces\SQLComparable;
use Planaday\Platform\PlatformAbstraction\DataHandler;

class MySQLIn implements SQLIn {
	/**
	 * @param DataHandler $dataHandler
	 * @param SQLComparable $toBeTested the value to be tested
	 * @param array|SQLQuery $values can be an array of values or a subquery
	 * @param bool $inOrOutside if false will use NOT IN
	 */
	public function __construct(
		protected DataHandler $dataHandler,
		protected SQLComparable $toBeTested,
		protected array|SQLQuery $values,
		protected bool $inOrOutside = true
	) {}

	function toConditionQuery(): string {
		$output = $this->toBeTested->getCompareIdentifier();
		if(!$this->inOrOutside) $output .= ' NOT';
		$output .= ' IN (';

		if (is_array($this->values)){
			$escapedValues = [];

			foreach ($this->values as $value){
				if (!is_int($value) && !is_float($value)){
					$value = "'" . $this->dataHandler->escapeSql($value) . "'";
				}

				$escapedValues[] = $value;
			}

			$output .= implode(', ', $escapedValues);
		} elseif( $this->values instanceof SQLQuery) {
			$output .= $this->values->toQuery();
		}

		$output .= ')';

		return $output;
	}
}