<?php
namespace DatabaseHelper;

use DatabaseHelper\enums\Type;
use DatabaseHelper\enums\Operator;
use InvalidArgumentException;

class Update
{
    use Conditionable;

    protected Schema $table;
    protected array $values = [];

    public function __construct(Schema $table) {
        $this->table = $table;
    }

    /**
     * Sets a new value for a column.
     * @param string $col Column name.
     * @param mixed $val Value to set.
     * @return self Current instance for method chaining.
     * @throws InvalidArgumentException
     */
    public function set(string $col, mixed $val): self {
        $this->table->requireColumn($col);

        $columnType = $this->table->columnType($col);
        $castedValue = $columnType->dbCast($val);
        $this->values[$col] = $castedValue;
        return $this;
    }

    /**
     * Generates the SQL statement.
     * @return string SQL query.
     * @throws InvalidArgumentException
     */
    public function toSql(): string {
        if (empty($this->values))
            throw new InvalidArgumentException("No values have been set for the Update.");

        $table = $this->table->name;
        $setParts = [];
        foreach ($this->values as $col => $value)
            $setParts[] = "$col = $value";
        $setClause = implode(", ", $setParts);

        // FINAL SQL STATEMENT
        $update = "UPDATE $table SET $setClause";
        if($this->isConditioned()) {
            $whereClause = $this->combineConditions();
            $update .= " WHERE $whereClause";
        }
        return $update;
    }

    /**
     * Executes the SQL UPDATE query.
     * @return bool Returns true on success.
    */
    public function update(): bool {
        global $wpdb;
        $query = $this->toSql();
        $result = $wpdb->query($query);
        return boolval($result);
    }
}