<?php
// Add this at the very top of the file
$cookie_name = 'itinerator_completed_stops';
$completed_stops = isset($_COOKIE[$cookie_name]) ?
  json_decode(stripslashes($_COOKIE[$cookie_name]), true) :
  array();

// Add this at the top of your file, before the HTML
if (isset($_GET['complete_stop'])) {
  $stop_param = sanitize_text_field($_GET['complete_stop']);
  $cookie_name = 'itinerator_completed_stops';

  // Get existing completed stops
  $completed_stops = isset($_COOKIE[$cookie_name]) ?
    json_decode(stripslashes($_COOKIE[$cookie_name]), true) :
    array();

  // Loop through legs and stops to validate the parameter
  foreach ($this->itinerary->legs as $leg) {
    foreach ($leg->stops as $stop) {
      if (!empty($stop->record_details)) {
        $stop_slug = sanitize_title($stop->name);
        $stop_id = $stop_slug . '-' . $stop->id;

        if ($stop_param === $stop_id) {
          if (!in_array($stop->id, $completed_stops)) {
            $completed_stops[] = $stop->id;
            setcookie(
              $cookie_name,
              json_encode($completed_stops),
              time() + (86400 * 30),
              '/',
              '',
              true,
              true
            );
          }
          break 2;
        }
      }
    }
  }
}
?>
<div class="itin itinerator-itinerary <?= $this->attributes['className'] ?? ''; ?>">
  <dialog id="stopModal" class="stop-modal">
    <div class="modal-header">
      <h5 class="modal-title" id="stopModalLabel"></h5>
      <button type="button" class="close-button" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body" id="stopModalContent"></div>
  </dialog>

  <?php
  // Add this where you define your modal content
  $modal_content = array();
  foreach ($this->itinerary->legs as $leg) {
    foreach ($leg->stops as $stop) {
      $full_listing = '';
      if (!empty($stop->record_details)) {
        $full_listing = $this->query_listing_data($stop->record_details->id);
      }
      if (!empty($stop->record_details)) {
        $stop_slug = sanitize_title($stop->name);
        $stop_id = $stop_slug . '-' . $stop->id;

        $modal_content[$stop_id] = array(
          'title' => $stop->name,
          'content' => '<div class="modal-stop-content">' .
            '<div class="modal-description">' .
            (function() use ($full_listing) {
              if (empty($full_listing->contents)) {
                return '';
              }

              return array_reduce(
                $full_listing->contents,
                function($carry, $content) {
                  if ($content->content_type_name === "Dino Trail Content") {
                    return $content->html;
                  }
                  return $carry;
                },
                ''
              );
            })() .
            '</div>' .
            '</div>'
        );
      }
    }
  }

  // Output modal content as JSON for JavaScript
  echo "<script>
    window.modalContent = " . json_encode($modal_content) . ";
    console.log('Modal content initialized:', window.modalContent); // Debug
</script>";
  ?>

  <section class="section-itinerary anchor-point" id="trail">
    <div class="container-fluid">

      <ul class="nav nav-pills nav-justified d-md-none sticky-top py-4" role="tablist">
        <li class="nav-item d-none" role="presentation">
          <a class="nav-link active" id="itinerary-tab" data-toggle="pill" href="#itinerary" role="tab" aria-controls="itinerary" aria-selected="true">View Itinerary</a>
        </li>
        <li class="nav-item" role="presentation">
          <a class="nav-link" id="map-tab" data-toggle="pill" href="#map" role="tab" aria-controls="map" aria-selected="false">View Map</a>
        </li>
      </ul>

      <div class="tab-content row">
        <div class="tab-pane active d-md-block col-12 col-md-6" id="itinerary" role="tabpanel" aria-labelledby="itinerary-tab">
          <div class="row m-0">
            <div class="col-12 itinerary-content">
              <div class="group-start mt-3">
                <!-- <div class="media">
                  <div class="media-body">
                    <h2 class="itineray-name"><?php echo $this->itinerary->name; ?></h2>
                    <div class="has-md-font-size"><?php echo $this->parse_markdown($this->itinerary->description); ?></div>
                  </div>
                </div> -->

                <?php /** Days (POI) start here */
                $modal_content = array();
                foreach ($this->itinerary->legs as $leg) {
                ?>
                  <div class="leg-title"><?= $leg->title ?></div>
                  <ul class="list-group list-group-flush">
                    <?php foreach ($leg->stops as $stop) {
                      $record_details = $stop->record_details;
                      $full_listing = '';
                      if (!empty($record_details)) {
                        $full_listing = $this->query_listing_data($record_details->id);
                        // echo '<pre>';
                        // print_r($full_listing->contents);
                        // echo '</pre>';
                      }

                      // $modal_content[$stop_id] = array(
                      //   'title' => $stop->name,
                      //   'content' => '<div class="modal-stop-content">' .
                      //     '<div class="modal-description">' .
                      //     (!empty($full_listing->contents) ? array_reduce($full_listing->contents, function($carry, $content) {
                      //       return $content->content_type_name === "Dino Trail Content" ? $content->html : $carry;
                      //     }, '') : '') .
                      //     '</div>' .
                      //     '</div>'
                      // );

                      //If Note
                      if (!isset($stop->target_type)) { ?>
                        <div class="media section px-2 py-3">
                          <div class="media-body">
                            <?php if (isset($stop->hero)) { ?>
                              <img class="w-100 mb-3" src=<?php echo $stop->hero->getUrl('medium') ?> />
                            <?php } ?>
                            <?php echo $this->parse_markdown($stop->description); ?>
                            <?php if (!empty($stop->form_ids)) : ?>
                              <?php foreach ($stop->form_ids as $form) : ?>
                                <div class="form-wrapper">
                                  <?php echo do_shortcode('[tourismo-form-block show_name="true" show_description="true" custom_template_name="" selected_form="' . esc_attr($form) . '" class_name="" align="" ]'); ?>
                                </div>
                              <?php endforeach; ?>
                            <?php endif; ?>
                          </div>
                        </div>
                      <?php } ?>

                      <?php //If Stop
                      if (!empty($record_details)) {
                        $stop_slug = sanitize_title($stop->name);
                        $stop_id = $stop_slug . '-' . $stop->id;
                        $is_completed = in_array($stop->id, $completed_stops);
                      ?>
                        <li class="list-group-item <?php echo $is_completed ? 'completed-stop' : ''; ?> type-<?= !empty($stop->main_type) ? strtolower($stop->main_type) : '' ?>" data-poi-index="<?php echo $stop->total_position; ?>" data-stop-id="<?php echo $stop->id; ?>">
                          <div class="badge-col">
                            <div class="badge badge-pill">
                              <?php if ($stop->main_type === "Dinosaur") : ?>
                                <?php
                                // Initialize a flag to check if an award image has been displayed
                                $award_image_displayed = false;
                                // Check if there are contents in the full listing
                                if (!empty($full_listing->contents)) :
                                  // Iterate over each content in the full listing
                                  foreach ($full_listing->contents as $content) :
                                    // Check if the content type matches the completion status and has media
                                    if (($is_completed && $content->content_type_name === "Dino Award Filled" ||
                                        !$is_completed && $content->content_type_name === "Dino Award Empty") &&
                                      !empty($content->media[0]->url)
                                    ) :
                                ?>
                                      <img src="<?php echo $content->media[0]->url; ?>" style="" alt="Dinosaur Logo" class="award-image">
                                  <?php
                                      $award_image_displayed = true;
                                      break;
                                    endif;
                                  endforeach;
                                endif;

                                // If no award image was displayed, show the appropriate fallback
                                if (!$award_image_displayed) :
                                  $fallback_svg = $is_completed ?
                                    'DinoTrails-Fallback-Dino-filled.svg' :
                                    'DinoTrails-Fallback-Dino-empty.svg';
                                  ?>
                                  <object type="image/svg+xml"
                                    data="<?php echo plugin_dir_url(__FILE__) . $fallback_svg; ?>"
                                    style="padding:10px;"
                                    alt="Dinosaur Logo" class="award-image"></object>
                                <?php endif; ?>
                              <?php elseif ($stop->main_type === "Business") : ?>
                                <!-- Display a business icon if the main type is "Business" -->
                                <object type="image/svg+xml" data="<?php echo plugin_dir_url(__FILE__); ?>DinoTrails-Business-Pin.svg" alt="Business Logo" class="award-image"></object>
                              <?php endif; ?>
                            </div>
                          </div>
                          <div class="content">
                            <div class="h4">
                              <?php if (!empty($stop->name) && $stop->main_type === "Dinosaur") : ?>
                                <a class="title-link <?php echo $stop->main_type === "Business" ? 'text-dark' : '' ?>" href="<?php echo $record_details->path; ?>">
                                  <?= $stop->name; ?>
                                </a>
                              <?php else : ?>
                                <span class="title-link text-dark"><?= $stop->name; ?></span>
                              <?php endif; ?>
                              <?php if ($is_completed): ?>
                                <span class="completion-status">(Completed!)</span>
                              <?php endif; ?>
                              <!-- <?php
                              // Debug output - you can remove this later
                              // $stop_slug = sanitize_title($stop->name);
                              // $stop_id = $stop_slug . '-' . $stop->id;
                              // echo '<div style="color: #666; font-size: 12px; margin-top: 5px;">Parameter: ' . $stop_id . '</div>';
                              ?> -->
                            </div>
                            <?php if ($stop->target_type === "Listing") : ?>
                              <div class="contact-details small mb-2">
                                <?php if (!empty($record_details->full_address)) : ?>
                                  <div class="address"><?php echo $record_details->full_address; ?></div>
                                <?php endif; ?>
                              </div>
                            <?php endif; ?>

                            <?php if (!empty($record_details->short_description)) : ?>
                              <div class="short-description"><?php echo $this->parse_markdown($record_details->short_description); ?></div>
                            <?php endif; ?>

                            <?php if (!empty($stop->hero)) : ?>
                              <?php echo $stop->hero->getImg(null, "img-fluid mb-3 mt-5", "style='max-height: 300px; width: auto;'"); ?>
                            <?php endif; ?>

                            <?php if (!empty($record_details->website)) : ?>
                              <div class="btn-wrapper">
                                <a class="btn btn-secondary mx-0" href="<?= $record_details->website; ?>" target="_blank">
                                  <span>Visit Website</span>
                                  <i class="fa-minus fas button-icon-right" aria-hidden="true"></i>
                                </a>
                              </div>
                            <?php endif; ?>



                          </div>
                        </li>
                    <?php
                      }
                    } ?>
                  </ul>
                <?php
                }
                // Output modal content as JSON for JavaScript
                //                 echo "<script>
                // const modalContent = " . json_encode($modal_content) . ";
                // </script>";
                ?>

              </div>
            </div>
          </div>
        </div>
        <div class="tab-pane d-md-block col-12 col-md-6" id="map" role="tabpanel" aria-labelledby="map-tab">
          <!-- <x-alert dated='yes' type='trails' /> -->
          <div class="map-container sticky-top">
            <div class="google-map">
              <div class="map-internals" style="display: none;">
                <!-- Reset for map  -->
                <?php foreach ($this->itinerary->legs as $leg) : ?>
                  <?php foreach ($leg->stops as $stop) : ?>
                    <?php $record_details = $stop->record_details;
                    $full_listing = '';
                    if (!empty($record_details)) {
                      $full_listing = $this->query_listing_data($record_details->id);
                      // echo '<pre>';
                      // print_r($full_listing->contents);
                      // echo '</pre>';
                    }
                    ?>
                    <?php if (!empty($record_details)) :
                      if (!empty($record_details)) {
                        $stop_slug = sanitize_title($stop->name);
                        $stop_id = $stop_slug . '-' . $stop->id;
                        $is_completed = in_array($stop->id, $completed_stops);
                      }
                    ?>
                      <div class="marker" data-lat="<?php echo $record_details->lat; ?>" data-lng="<?php echo $record_details->lng; ?>" data-title="<?php echo $stop->name; ?>" data-poi-index="<?php echo $stop->total_position; ?>" data-stop-id="<?php echo $stop->id; ?>" data-part="<?php echo $leg->order_on_itin; ?>" <?php echo in_array($stop->total_stop_number, $completed_stops) ? 'class="completed-stop"' : ''; ?>>
                        <div class="marker-badge-container" data-marker>
                          <span class="badge map-badge badge-pill <?php echo in_array($stop->id, $completed_stops) ? 'completed-stop' : ''; ?> type-<?= !empty($stop->main_type) ? strtolower($stop->main_type) : '' ?>">
                            <?php if ($stop->main_type === "Dinosaur") : ?>
                              <?php
                              // Initialize a flag to check if an award image has been displayed
                              $award_image_displayed = false;
                              // Check if there are contents in the full listing
                              if (!empty($full_listing->contents)) :
                                // Iterate over each content in the full listing
                                foreach ($full_listing->contents as $content) :
                                  // Check if the content type matches the completion status and has media
                                  if (($is_completed && $content->content_type_name === "Dino Award Filled" ||
                                      !$is_completed && $content->content_type_name === "Dino Award Empty") &&
                                    !empty($content->media[0]->url)
                                  ) :
                              ?>
                                    <img src="<?php echo $content->media[0]->url; ?>" style="height: 50px;" alt="Dinosaur Logo">
                                <?php
                                    $award_image_displayed = true;
                                    break;
                                  endif;
                                endforeach;
                              endif;

                              // If no award image was displayed, show the appropriate fallback
                              if (!$award_image_displayed) :
                                $fallback_svg = $is_completed ?
                                  'DinoTrails-Fallback-Dino-filled.svg' :
                                  'DinoTrails-Fallback-Dino-empty.svg';
                                ?>
                                <object type="image/svg+xml"
                                  data="<?php echo plugin_dir_url(__FILE__) . $fallback_svg; ?>"
                                  style="height: 50px; padding: 5px;"
                                  alt="Dinosaur Logo"></object>
                              <?php endif; ?>
                            <?php elseif ($stop->main_type === "Business") : ?>
                              <object type="image/svg+xml" data="<?php echo plugin_dir_url(__FILE__); ?>DinoTrails-Business-Pin.svg" style="height: 50px;" alt="Business Logo"></object>
                            <?php endif; ?>
                          </span>
                        </div>
                        <div data-infowindow>
                          <div class="media media-infowindow">
                            <div class="media-body">
                              <div class="title">
                                <a class="title-link" href="<?php echo $record_details->path; ?>">
                                  <?= $stop->name; ?>
                                </a>
                              </div>
                              <?php if ($stop->target_type === "Listing") : ?>
                                <div class="contact-details small mb-2">
                                  <?php if (!empty($record_details->full_address)) : ?>
                                    <div class="address"><?php echo $record_details->full_address; ?></div>
                                  <?php endif; ?>
                                  <?php if (!empty($record_details->website)) : ?>
                                    <a class="t-book-now-itinerary" href="<?= $record_details->website; ?>" target="_blank">
                                      Visit Website
                                    </a>
                                  <?php endif; ?>
                                </div>
                              <?php endif; ?>
                            </div>
                          </div>
                        </div>
                      </div>
                    <?php endif; ?>
                  <?php endforeach; ?>
                <?php endforeach; ?>
              </div>
            </div>
          </div>
        </div>
      </div>
  </section>
</div>