<?php

namespace Planaday\Database\MySQL\QueryBuilding;

use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLTable;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLUpdate;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLUseInterfaces\SQLCondition;

class MySQLUpdate implements SQLUpdate {
	/**
	 * @param SQLTable $table
	 * @param SQLCondition $where
	 * @param array<string, int|string|null> $values
	 */
	public function __construct(
		protected SQLTable $table,
		protected SQLCondition $where,
		protected array $values
	) {}

	public function toQuery():string {
		/** @var string[] $data */
		$data = [];

		foreach($this->values as $column => $value) {
			if ($value === null) {
				$data[$column] = 'NULL';
				continue;
			}

			if (is_int($value)) {
				$data[$column] = (string) $value;
				continue;
			}

			$data[$column] = "'" . addcslashes( $value, '\\\'"' ) . "'";
		}

		$query = 'UPDATE ' . $this->table->getFromQuery() . ' SET ';

		foreach ($data as $column => $value) {
			$query .= $column . ' = ' . $value . ', ';
		}

		$query = substr($query, 0, -2);

		$query .= ' WHERE ' . $this->where->toConditionQuery();
		return $query;
	}
}