<?php

namespace App\Utils\Db\ManageRecords;

class Update extends InsertUpdateAbstract
{

	/**
	 * The report DB table alias.
	 * @var string
	 */
	 private $populatingTableAlias;

	 /**
	 * Sets the report table name. Also sets the active columns (optionally).
	 * @param string $populatingTableName
	 */
	public function __construct($populatingTableName, $populatingTableAlias, ?array $activeColumns = null)
	{
		if (!$populatingTableName) {
			throw new \Exception('You must set the populating table name.');
		}
		if (!$populatingTableAlias) {
			throw new \Exception('You must set the populating table alias.');
		}

		$this->populatingTableName	= $populatingTableName;
		$this->populatingTableAlias	= $populatingTableAlias;

		// also sets the active columns
		if ($activeColumns!==null) {
			$this->setActiveColumns($activeColumns);
		}
	}

	 /**
	 * Composes the UPDATE SQL. Returns an array with two keys: 'sql' and 'bindVars'.
	 * @return array
	 */
	protected function getSQL() :array
	{

		$bindVars = [];

		// add UPDATE clause
		$sql = "UPDATE ".$this->getSQL_tables();

		// add columns
		$sql .= ' SET '.$this->getSQL_set();

		// add WHERE
		$whereSQL = $this->getSQL_where();
		if ($whereSQL['sql']) {
			$sql .= " WHERE ".$whereSQL['sql'];
			$bindVars = $whereSQL['bindVars'];
		}

		return [ 'sql'=>$sql, 'bindVars'=>$bindVars ];

	}

	/**
	 * Composes the FROM part of the SQL - adds all tables and joins them.
	 * @return string
	 */
	protected function getSQL_tables()
	{

		$return = "`{$this->populatingTableName}` AS {$this->populatingTableAlias}";
		foreach($this->sqlData['tables'] as $tbl=>$nada) {
			if ($tbl!=$this->populatingTableAlias) { // skip report table from the list
				// check that the all table aliases exist
				if ($tbl and !$this->joinTablesList[$tbl]) {
					throw new \Exception("Invalid table alias joined: `{$tbl}`");
				}
				// add this joined table
				$tblDet = $this->joinTablesList[$tbl];
				$return .= " {$tblDet['joinType']} JOIN `{$tblDet['table']}` AS {$tbl} ON ({$tblDet['foreignKeyRef']})";
			}
		}
		return $return;
	}


	/**
	 * Composes the SET columns part of the SQL.
	 * @return string
	 */
	private function getSQL_set()
	{

		$columnsList = [];
		foreach ($this->sqlData['columns'] as $fieldColum=>$dataColumn) {
			$columnsList[] = "{$fieldColum} = {$dataColumn}";
		}

		return implode(', ', $columnsList);

	}

}