<?php

/**
 * 
 */
class MioCommerceOlympusServicesBuilder {
  private $formData;
  private $chosenTheme;

  public function __construct($formData, $chosenTheme) {
    $this->formData = $formData;
    $this->chosenTheme = $chosenTheme;
  }

  public function buildServices($reusableBlocks) {
    if (!isset($this->formData['categoriesServices'])) return;
    $main_image_id = null;
    if (
      isset($this->formData['homePage'])
      && isset($this->formData['homePage']['heroBanner'])
      && isset($this->formData['homePage']['heroBanner']['heroImage'])
      && isset($this->formData['homePage']['heroBanner']['heroImage']['attachment_id'])
    ) {
      $main_image_id = $this->formData['homePage']['heroBanner']['heroImage']['attachment_id'];
    }
    $serviceCategoryPages = [];
    $serviceCategories = $this->formData['categoriesServices'];
    $serviceCategoryPageUrl = "";

    foreach ($serviceCategories as $category) {
      error_log("[Automator] Beginning automation of Service Category {$category['name']}");

      // 1. Création de la catégorie
      $term = wp_insert_term($category['name'], 'service-category');
      if (is_wp_error($term)) continue;

      $taxonomy_id = $term['term_id'];

      // 2. Création de la page de catégorie
      $category_slug = sanitize_title($category['name']);


      // Charger le pattern de la page catégorie (theme agnostic)
      $categoryContent = require plugin_dir_path(__FILE__) . 'patterns/services/category-page.php';

      // Remplacer les tokens dans le contenu
      $replacements = [
        '{{FILTER_SERVICES}}' => '1',
        '{{SERVICE_CAT}}' => $taxonomy_id,
        '{{THEME}}' => $this->chosenTheme,
        '{{ALIGN}}' => ($this->chosenTheme == 'triumph') ? 'wide' : 'none'
      ];

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

      $categoryPage = wp_insert_post([
        'post_title'     => $category['name'],
        'post_type'      => 'page',
        'post_name'      => $category_slug,
        'post_status'    => 'publish',
        'post_content'   => $categoryContent,
        'comment_status' => 'closed',
        'ping_status'    => 'closed',
        'post_author'    => 1,
        'menu_order'     => 0,
        'guid'           => $category_slug
      ]);

      if (!$serviceCategoryPageUrl) $serviceCategoryPageUrl = get_permalink($categoryPage);

      if ($main_image_id) set_post_thumbnail($categoryPage, $main_image_id);

      $servicesInsideCategory = [];
      // 3. Création des services individuels
      foreach ($category['services'] as $service) {

        $serviceCTA = ($service['ctaText']) ? $service['ctaText'] : "Book & Buy Now";

        // Créer la page de réservation d'abord pour avoir son URL (theme agnostic)
        $bookingContent = require plugin_dir_path(__FILE__) . 'patterns/services/booking-page.php';

        $bookingPageScript = '';
        if (isset($this->formData['generalInfo']['contactFormScript'])) {
          $bookingPageScript = $this->formData['generalInfo']['contactFormScript'];
        }

        if (isset($this->formData['bookingScript']['sections'][0]['data']['services'])) {
          $servicesBookingScripts = $this->formData['bookingScript']['sections'][0]['data']['services'];

          $matchedService = array_column($servicesBookingScripts, null, 'name')[$category['name'] . " %% " . $service['title']] ?? false;

          if ($matchedService && isset($matchedService['type']) && $matchedService['type'] == "custom" && isset($matchedService['script']) && $matchedService['script']) {
            $bookingPageScript = $matchedService['script'];
          }
        }

        $replacements = [
          '{{BOOKING_SCRIPT}}' => $bookingPageScript,
        ];

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

        $bookingPage = wp_insert_post([
          'post_title'     => $serviceCTA . ' - ' . $service['title'],
          'post_type'      => 'page',
          'post_name'      => sanitize_title($serviceCTA . ' - ' . $service['title']),
          'post_status'    => 'publish',
          'post_content'   => $bookingContent,
          'post_parent'    => $categoryPage,
          'comment_status' => 'closed',
          'ping_status'    => 'closed',
          'post_author'    => 1,
          'page_template'  => 'booking-page.php'
        ]);

        $bookingPageUrl = esc_url(get_permalink($bookingPage));

        // Create the service page, depending on the theme
        global $service_page_pattern_params;
        $service_page_pattern_params = [
          "categoryCTAText" => $serviceCTA,
          "bookingPageUrl" => $bookingPageUrl,
          "service" => $service,
          "reusableBlocks" => $reusableBlocks
        ];
        if ($this->chosenTheme == 'triumph') {
          $service_page_content = require plugin_dir_path(__FILE__) . 'patterns/services/service-page-triumph.php';
        } elseif ($this->chosenTheme == 'accelerator') {
          $service_page_content = require plugin_dir_path(__FILE__) . 'patterns/services/service-page-accelerator.php';
        } else {
          $service_page_content = require plugin_dir_path(__FILE__) . 'patterns/services/service-page-ace.php';
        }

        // Créer la page de service
        $serviceId = wp_insert_post([
          'post_type' => 'service',
          'post_title' => $service['title'],
          'post_name' => sanitize_title($service['title']),
          'post_content' => $service_page_content,
          'post_status' => 'publish'
        ]);

        if (is_wp_error($serviceId)) continue;

        // Associer à la catégorie
        wp_set_object_terms($serviceId, $term['term_id'], 'service-category');

        // Mettre à jour les champs ACF
        update_field('field_5ec6c038bb50c', [
          'url' => get_permalink($bookingPage),
          'title' => 'Book Now',
          'target' => ''
        ], $serviceId);
        update_field('field_5ec6c022bb50b', $serviceCTA, $serviceId);

        // Gérer les images
        if (!empty($service['mainImage']['attachment_id'])) {
          $imageId = $service['mainImage']['attachment_id'];
          set_post_thumbnail($serviceId, $imageId);
          set_post_thumbnail($bookingPage, $imageId);
        }

        array_push($servicesInsideCategory, [
          'title' => $service['title'],
          'url' => get_permalink($serviceId),
          'id' => $serviceId,
          'booking_cta_title' => $serviceCTA,
          'booking_page_url' => get_permalink($bookingPage),
          'booking_page_id' => $bookingPage,
        ]);
      }

      array_push($serviceCategoryPages, [
        'title' => $category['name'],
        'url' => get_permalink($categoryPage),
        'id' => $categoryPage,
        'taxonomy_id' => $taxonomy_id,
        'services' => $servicesInsideCategory
      ]);
    }

    return [
      'serviceCategoryPageUrl' => $serviceCategoryPageUrl,
      'categoryPages' => $serviceCategoryPages,
    ];
  }
}
