<?php
declare(strict_types=1);

namespace WP_AUX\Entities\HTML;

use WHOOP\Entities\Elements\Traits\ElementTraits;

class Table
{
  use ElementTraits;

  protected array $columns;
  protected array $rows;

  public function __construct(array $columns, array $rows) {
    $this->columns = $columns;
    $this->rows = $rows;

    $this->initProperties();
  }

  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();
  }
}
