<?php

declare(strict_types=1);

namespace ACP\Search\Helper\Sql\Comparison;

use ACP\Search\Helper\Sql\Comparison;
use ACP\Search\Value;
use LogicException;

class In extends Comparison implements Negatable
{
    public function __construct(string $column, Value $value)
    {
        $operator = 'IN';

        if ($this->is_negated()) {
            $operator = 'NOT ' . $operator;
        }

        parent::__construct($column, $operator, $value);
    }

    public function get_statement(): string
    {
        return sprintf('%s %s (?)', $this->column, $this->operator);
    }

    public function is_negated(): bool
    {
        return false;
    }

    public function bind_value(Value $value): self
    {
        if (! is_array($value->get_value())) {
            throw new LogicException('Value can only be an array.');
        }

        $type = $value->get_type();
        $values = $value->get_value();

        foreach ($values as $new_value) {
            parent::bind_value(new Value($new_value, $type));
        }

        return $this;
    }

    public function prepare(): string
    {
        $this->statement = str_replace('?', implode(', ', array_fill(0, count($this->values), '?')), $this->statement);

        return parent::prepare();
    }

}
