<?php

/**
 * 
 */
class MioCommerceOlympusAboutPageBuilder {
  public function buildPage($sections, $sectionsOrder) {

    $pageContent = '';
    foreach ($sectionsOrder as $sectionId) {
      foreach ($sections as $section) {
        if ($section['id'] != $sectionId || !$section['data']['isVisible']) continue;

        if ($section['type'] == 'about-us-banner') $pageContent .= $this->buildAboutUsBannerSection($section);

        if ($section['type'] == 'mission-vision') $pageContent .= $this->buildAboutUsMissionSection($section);

        if ($section['type'] == 'guarantee') $pageContent .= $this->buildAboutUsGuaranteeSection($section);
      }
    }

    return $pageContent;
  }

  private function buildAboutUsBannerSection($section) {
    $sectionContent = require plugin_dir_path(__FILE__) . 'patterns/about-us/banner.php';

    $replacements = [
      '{{TITLE}}' => $section['data']['title'],
      '{{CONTENT}}' => $section['data']['content'],
      '{{IMAGE_ID}}' => $section['data']['image']['attachment_id'],
      '{{IMAGE_SRC}}' => $section['data']['image']['url']
    ];

    $sectionContent = str_replace(
      array_keys($replacements),
      array_values($replacements),
      $sectionContent
    );

    return $sectionContent;
  }

  private function buildAboutUsMissionSection($section) {
    $sectionContent = require plugin_dir_path(__FILE__) . 'patterns/about-us/mission.php';

    $columnsContent = "";
    $columnsCounter = 0;

    foreach ($section['data']['columns'] as $column) {
      if ($columnsCounter % 3 == 0) {
        $columnsContent .= '<!-- wp:columns -->
<div class="wp-block-columns">';
      }

      $columnsContent .= '<!-- wp:column -->
<div class="wp-block-column"><!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading">' . $column['title'] . '</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>' . $column['text'] . '</p>
<!-- /wp:paragraph --></div>
<!-- /wp:column -->';

      if ($columnsCounter == count($section['data']['columns']) - 1 || ($columnsCounter + 1) % 3 == 0) {
        $columnsContent .= '</div><!-- /wp:columns -->';
      }

      $columnsCounter++;
    }

    $replacements = [
      '{{TITLE}}' => $section['data']['title'],
      '{{CONTENT}}' => $columnsContent,
    ];

    $sectionContent = str_replace(
      array_keys($replacements),
      array_values($replacements),
      $sectionContent
    );

    return $sectionContent;
  }

  private function buildAboutUsGuaranteeSection($section) {
    $sectionContent = require plugin_dir_path(__FILE__) . 'patterns/about-us/guarantee.php';

    $replacements = [
      '{{TITLE}}' => $section['data']['title'],
      '{{CONTENT}}' => $section['data']['content']
    ];

    $sectionContent = str_replace(
      array_keys($replacements),
      array_values($replacements),
      $sectionContent
    );

    return $sectionContent;
  }
}
