<?php

namespace Planaday\Database\MySQL\QueryBuilding;

use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLInsert;
use Planaday\Database\Abstraction\SQLQuery\QueryBuilding\SQLTable;

class MySQLInsert implements SQLInsert {
	protected bool $isMultipleRows = false;

	/**
	 * @param SQLTable $table
	 * @param mixed[] $row
	 */
	public function __construct(
		protected SQLTable $table,
		protected array $row
	) {}

	public function addRow( array $row ): void {
		if ( !$this->isMultipleRows ) {
			$this->row            = [ $this->row ];
			$this->isMultipleRows = true;
		}

		$this->row[] = $row;
	}

	public function toQuery(bool $asPrepareStatement = false):string {
		/** @var string[] $columns */
		$columns = [];

		$rows = $this->isMultipleRows ? $this->row : [ $this->row ];
		$values = '';

		foreach ( $rows as $key => $row ) {
			/** @var string[] $data */
			$data = [];

			foreach ( $row as $column => $value ) {
				if ( $key == 0 ) {
					$columns[] = $column;

					if ($asPrepareStatement){
						$data[] = '?';
						continue;
					}
				}

				if ( $value === null) {
					$data[] = 'NULL';
					continue;
				}

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

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

			$values .= '(' . implode(', ', $data) . '), ';
		}

		$update = [];
		foreach ($columns as $column){
			$update[] = $column . ' = VALUES(' . $column . ')';
		}

		return 'INSERT INTO ' . $this->table->getFromQuery() . ' (' . implode(', ', $columns) . ')' .
		       ' VALUES ' . substr($values, 0, -2) . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);
	}

}