<?php

/**
 * FAQ Block Template.
 *
 * @param   array $block The block settings and attributes.
 * @param   string $content The block inner HTML (empty).
 * @param   bool $is_preview True during backend preview render.
 * @param   int $post_id The post ID the block is rendering content against.
 *          This is either the post ID currently being displayed inside a query loop,
 *          or the post ID of the post hosting this block.
 * @param   array $context The context provided to the block by the post or it's parent block.
 */

// Support custom "anchor" values.
$anchor = '';
if (! empty($block['anchor'])) {
  $anchor = 'id="' . esc_attr($block['anchor']) . '" ';
}

// Create class attribute allowing for custom "className" and "align" values.
$class_name = 'olympus-faq';

$theme = get_field('theme');
if ($theme) {
  $class_name .= ' ' . $theme;
}

if (! empty($block['className'])) {
  $class_name .= ' ' . $block['className'];
}
if (! empty($block['align'])) {
  $class_name .= ' align' . $block['align'];
}

$show_all = get_field('show_all');
$questions_to_show = get_field('questions_to_show') ?? array();
$max_questions = get_field('max_questions');

$args = array(
  'post_type' => 'olympus-faq',
  'posts_per_page' => -1,
);

if (!$show_all) {
  $args['post__in'] = $questions_to_show;
}

if (!$show_all && !$questions_to_show && $max_questions) {
  $args['posts_per_page'] = $max_questions;
}

$primary_color = (get_field('primary_color')) ? get_field('primary_color') : "var(--wp--preset--color--primary)";
$primary_contrast_color = (get_field('primary_contrast_color')) ? get_field('primary_contrast_color') : "var(--wp--preset--color--base)";
$svg_styles = ($theme == 'triumph') ? 'background:' . $primary_color . ';fill:' . $primary_contrast_color . ';' : 'fill:' . $primary_color . ';';

// TODO: add structured data
?>
<div <?php echo $anchor; ?>class="<?php echo esc_attr($class_name); ?>">
  <?php
  $query = new WP_QUERY($args);
  if ($query->have_posts()):
    while ($query->have_posts()) : $query->the_post();
  ?>
      <div class="olympus-faq-item tod-accordion faq closed" style="border-color:<?php echo $primary_color ?>;">
        <div class="accordion-title">
          <h3><?php echo the_title() ?></h3>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" style="<?php echo $svg_styles ?>">
            <path d="M199 401c9.4 9.4 24.6 9.4 33.9 0L425 209c9.4-9.4 9.4-24.6 0-33.9s-24.6-9.4-33.9 0l-175 175L41 175c-9.4-9.4-24.6-9.4-33.9 0s-9.4 24.6 0 33.9L199 401z" />
          </svg>
        </div>
        <div class="accordion-content" style="display:<?php echo (is_admin()) ? 'block' : 'none' ?>;">
          <?php echo the_content() ?>
        </div>
      </div>
  <?php
    endwhile;
  endif;
  wp_reset_postdata();
  ?>
</div>