<?php
declare(strict_types=1);

namespace WHOOP\Entities\Elements;

use WHOOP\Entities\Element;

class Table extends Element
{
  public const TAG = 'table';

  protected Thead $thead;
  protected Tbody $tbody;
  protected Tfoot $tfoot;
  protected array $columns;
  protected array $rows;

  protected function initElement(): void {
    $this->thead = Thead::create();
    $this->tbody = Tbody::create();
    $this->tfoot = Tfoot::create();

    $this->addElement($this->thead, 'head');
    $this->addElement($this->tbody, 'body');
    $this->addElement($this->tfoot, 'foot');
  }

  public function makeColumns(array $columns): void
  {
    $tr = Tr::create();

    $ci = 0;
    foreach ($columns as $columnKey => $column) {
      if (0 === $ci) {
        $columnElement = Th::create();
      } else {
        $columnElement = Td::create();
      }

      $columnElement->setContent(is_array($column) ? $column['label'] : $column);

      $tr->addElement($columnElement);
      $ci++;
    }

    $this->thead->addElement($tr);
  }

  public static function build(array $columns = [], array $rows = []): self
  {
    $table = new self();
    $table->makeColumns($columns);

    return $table;
  }

  public function ___toString(): string
  {
    ob_start();
    ?>
    <table <?php echo $this->getAttributesString(); ?>>
      <thead>
      <tr>
        <?php
        $ci = 0;
        foreach ($this->columns as $columnKey => $column) {
          if (0 === $ci) {
            $format = '<th>%s</th>';
          } else {
            $format = '<td>%s</td>';
          }

          echo sprintf($format, is_array($column) ? $column['label'] : $column);
          $ci++;
        }
        ?>
      </tr>
      </thead>
      <tbody>
      <?php
      foreach ($this->rows as $row) {
        ?>
        <tr>
          <?php
          $ci = 0;
          foreach ($this->columns as $columnKey => $column) {
            $cellValue = @$row[$columnKey];

            if (0 === $ci) {
              $format = '<th class="%s-cell">%s</th>';
            } else {
              $format = '<td class="%s-cell">%s</td>';
            }

            if (is_array($column) && isset($column['displayCallback'])) {
              $cellValue = call_user_func_array($column['displayCallback'], [$cellValue, $row]);
            }

            echo sprintf($format, $columnKey, $cellValue);
            $ci++;
          }
          ?>
        </tr>
        <?php
      }
      ?>
      </tbody>
    </table>
<?php
    return ob_get_clean();
  }
}
