<?php

/**
 * 
 */

require plugin_dir_path(dirname(__FILE__)) . '/olympus/DataClearer.php';
require plugin_dir_path(dirname(__FILE__)) . '/olympus/ServicesBuilder.php';
require plugin_dir_path(dirname(__FILE__)) . '/olympus/AboutPageBuilder.php';
require plugin_dir_path(dirname(__FILE__)) . '/olympus/HomePageBuilder.php';

class MioCommerceOlympusAutomatisation {
  private $formData;
  private $onboard_data;
  private $isPreview;
  private $dataClearer;
  private $servicesBuilder;
  private $chosenTheme;
  private $themeVariation;
  private $mainImageID;

  public function __construct($formData, $onboard_data, $isPreview = false) {
    $this->formData = $formData;
    $this->onboard_data = $onboard_data;
    $this->isPreview = $isPreview;


    $this->chosenTheme = 'ace';
    if ($onboard_data && $onboard_data['theme']) {
      $this->chosenTheme = $onboard_data['theme'];
    }

    $this->themeVariation = 'premium';
    if ($onboard_data && $onboard_data['variation']) {
      $this->themeVariation = $onboard_data['variation'];
    }

    $this->dataClearer = new MioCommerceOlympusDataClearer();
    $this->servicesBuilder = new MioCommerceOlympusServicesBuilder($formData, $this->chosenTheme);

    if (
      isset($formData['homePage'])
      && isset($formData['homePage']['heroBanner'])
      && isset($formData['homePage']['heroBanner']['heroImage'])
      && isset($formData['homePage']['heroBanner']['heroImage']['attachment_id'])
    ) {
      $this->mainImageID = $formData['homePage']['heroBanner']['heroImage']['attachment_id'];
    }
  }

  public function createWebsite() {
    try {
      error_log('=== DÉBUT CRÉATION WEBSITE ===');

      // Nettoyage
      $this->dataClearer->clearExistingData();

      // error_log('=== Form data base of the builder ===');
      // error_log(print_r($this->formData, true));

      // Création des contenus
      $reusableBlocks = $this->createReusableBlocks();

      $servicesOutput = $this->servicesBuilder->buildServices($reusableBlocks);
      $this->createTestimonials();
      $this->createFaqs();

      $this->setReusableBlocksContent($reusableBlocks, $servicesOutput['serviceCategoryPageUrl']);

      // Create pages
      $contactPageId = $this->createContactPage();
      $faqPageId = $this->createFaqPage();
      $aboutPageId = $this->createAboutPage();

      $pageUrls = [
        'faq' => get_permalink($faqPageId),
        'about' => get_permalink($aboutPageId),
        'contact' => get_permalink($contactPageId),
      ];

      if ($this->themeVariation == "premium") {
        $blogPageId = $this->createBlogPage($pageUrls);

        $pageUrls['blog'] = get_permalink($blogPageId);
      }

      $homePageId = $this->createHomePage($servicesOutput, $pageUrls, $reusableBlocks);

      // Options générales
      $this->setgeneralOptions($servicesOutput, $pageUrls);

      // Mise à jour du statut
      $this->updateSiteStatus();

      error_log('=== FIN CRÉATION WEBSITE ===');

      return [
        'status' => 'success',
        'message' => 'The website was successfully created.',
        'homepage_url' => get_home_url()
      ];
    } catch (Exception $e) {
      error_log('ERREUR: ' . $e->getMessage());
      return [
        'status' => 'error',
        'message' => $e->getMessage()
      ];
    }
  }

  private function updateSiteStatus() {
    update_option('wb_is_done_creating_site', !$this->isPreview);
  }

  private function createReusableBlocks() {
    $reusable_blocks_created = array();

    // Create Why Choose Us Reusable Block
    if (isset($this->formData['homePage']['sections'])) {
      foreach ($this->formData['homePage']['sections'] as $section) {
        if ($section['type'] !== 'why-choose-section') continue;

        if ($section['data']['isVisible']) {

          $why_choose_us_pattern_id = wp_insert_post(
            array(
              'post_title' => 'Why Choose Us - Pattern',
              'post_content' => "",
              'post_name' => sanitize_title('Why Choose Us - Pattern'),
              'post_status' => 'publish',
              'comment_status' => 'closed',
              'ping_status' => 'closed',
              'post_type' => 'wp_block',
            )
          );

          $reusable_blocks_created['whyChooseUs'] = $why_choose_us_pattern_id;
        }
      }
    }

    return $reusable_blocks_created;
  }

  private function setReusableBlocksContent($reusableBlocks, $serviceCategoryPageUrl) {
    // Add content in Why Choose Us Reusable Block
    if (isset($reusableBlocks['whyChooseUs'])) {

      if (isset($this->formData['homePage']['sections'])) {
        foreach ($this->formData['homePage']['sections'] as $section) {
          if ($section['type'] !== 'why-choose-section') continue;

          if ($section['data']['selectedStyle'] == 'triumph') {
            $whyChooseUsContent = require plugin_dir_path(__FILE__) . 'patterns/why-choose-us-triumph.php';
          } elseif ($section['data']['selectedStyle'] == 'accelerator') {
            $whyChooseUsContent = require plugin_dir_path(__FILE__) . 'patterns/why-choose-us-accelerator.php';
          } else {
            $whyChooseUsContent = require plugin_dir_path(__FILE__) . 'patterns/why-choose-us-ace.php';
          }

          $replacements = [
            '{{TITLE}}' => $section['data']['sectionTitle'],
            '{{SERVICES_PAGE_URL}}' => $serviceCategoryPageUrl,
            '{{CONTENT}}' => $section['data']['sectionContent'],
          ];

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

          wp_insert_post(
            array(
              'ID' => $reusableBlocks['whyChooseUs'],
              'post_content' => $whyChooseUsContent,
              'post_title' => 'Why Choose Us - Pattern',
              'post_name' => sanitize_title('Why Choose Us - Pattern'),
              'post_status' => 'publish',
              'comment_status' => 'closed',
              'ping_status' => 'closed',
              'post_type' => 'wp_block',
            )
          );
        }
      }
    }
  }

  private function createTestimonials() {
    if (!isset($this->formData['homePage']['sections'])) return;

    // Chercher la section testimonials
    foreach ($this->formData['homePage']['sections'] as $section) {
      if ($section['type'] !== 'testimonial-section') continue;

      foreach ($section['data']['testimonials'] as $testimonial) {
        $testimonialId = wp_insert_post([
          'post_type' => 'olympus-testimonials',
          'post_title' => $testimonial['name'],
          'post_content' => $testimonial['testimonial'],
          'post_status' => 'publish'
        ]);

        if (is_wp_error($testimonialId)) continue;

        // Mettre à jour les champs ACF
        update_field('testimonial_name', $testimonial['name'], $testimonialId);
        update_field('job_position', $testimonial['role'], $testimonialId);
      }
    }
  }

  private function createFaqs() {
    if (!isset($this->formData['faq']['sections'])) return;

    // Chercher la section FAQ
    foreach ($this->formData['faq']['sections'] as $section) {
      if ($section['type'] !== 'faq') continue;

      foreach ($section['data']['faqs'] as $faq) {
        wp_insert_post([
          'post_type' => 'olympus-faq',
          'post_title' => $faq['question'],
          'post_content' => $faq['answer'],
          'post_status' => 'publish'
        ]);
      }
    }
  }

  private function createContactPage() {

    $pageContent = require plugin_dir_path(__FILE__) . 'patterns/contact-us-page.php';

    $contactPageBookingScript = "";
    $addressLatLng = [
      "lat" => "",
      "lng" => ""
    ];
    $businessPhone = "";
    $businessEmail = "";

    if ($this->formData && $this->formData['generalInfo']) {
      if ($this->formData['generalInfo']['contactFormScript']) $contactPageBookingScript = $this->formData['generalInfo']['contactFormScript'];
      if ($this->formData['generalInfo']['businessPhone']) $businessPhone = $this->formData['generalInfo']['businessPhone'];
      if ($this->formData['generalInfo']['businessEmail']) $businessEmail = $this->formData['generalInfo']['businessEmail'];
      if ($this->formData['generalInfo']['latlng']) $addressLatLng = [
        "lat" => $this->formData['generalInfo']['latlng']['lat'],
        "lng" => $this->formData['generalInfo']['latlng']['lng']
      ];
    }

    // Remplacer les tokens dans le contenu
    $replacements = [
      '{{BOOKING_SCRIPT}}' => $contactPageBookingScript,
      '{{LAT}}' => $addressLatLng['lat'],
      '{{LNG}}' => $addressLatLng['lng'],
      '{{PHONE}}' => $businessPhone,
      '{{EMAIL}}' => $businessEmail
    ];

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

    $contactPage = wp_insert_post([
      'post_title'    => 'Contact Us',
      'post_type'      => 'page',
      'post_status'    => 'publish',
      'post_content'   => $pageContent,
      'comment_status' => 'closed',
      'ping_status'    => 'closed',
    ]);

    if ($this->mainImageID) set_post_thumbnail($contactPage, $this->mainImageID);

    return $contactPage;
  }

  private function createFaqPage() {

    $pageContent = require plugin_dir_path(__FILE__) . 'patterns/faq-page.php';

    $replacements = [
      '{{THEME}}' => $this->chosenTheme
    ];

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

    $faqPage = wp_insert_post([
      'post_title'    => 'Frequently Asked Questions',
      'post_type'      => 'page',
      'post_status'    => 'publish',
      'post_content'   => $pageContent,
      'comment_status' => 'closed',
      'ping_status'    => 'closed',
    ]);

    if ($this->mainImageID) set_post_thumbnail($faqPage, $this->mainImageID);

    return $faqPage;
  }

  private function createAboutPage() {

    $pageContent = require plugin_dir_path(__FILE__) . 'patterns/about-us/hero.php';

    if ($this->formData && $this->formData['aboutUs'] && $this->formData['aboutUs']['sections']) {
      $pageBuilder = new MioCommerceOlympusAboutPageBuilder();

      $pageContent .= $pageBuilder->buildPage($this->formData['aboutUs']['sections'], $this->formData['aboutUs']['sectionsOrder']);
    }

    $aboutPage = wp_insert_post([
      'post_title'    => 'About Us',
      'post_type'      => 'page',
      'post_status'    => 'publish',
      'post_content'   => $pageContent,
      'comment_status' => 'closed',
      'ping_status'    => 'closed',
    ]);

    if ($this->mainImageID) set_post_thumbnail($aboutPage, $this->mainImageID);

    return $aboutPage;
  }


  private function createHomePage($servicesOutput, $pageUrls, $reusableBlocks) {

    // This handles when we have no content in the form
    $pageContent = '<!-- wp:cover {"overlayColor":"contrast","isUserOverlayColor":true,"minHeight":800,"align":"full","style":{"spacing":{"padding":{"top":"var:preset|spacing|70","bottom":"var:preset|spacing|70"}}},"layout":{"type":"constrained"}} -->
<div class="wp-block-cover alignfull" style="padding-top:var(--wp--preset--spacing--70);padding-bottom:var(--wp--preset--spacing--70);min-height:800px"><span aria-hidden="true" class="wp-block-cover__background has-contrast-background-color has-background-dim-100 has-background-dim"></span><div class="wp-block-cover__inner-container"><!-- wp:heading {"textAlign":"center","level":3} -->
<h3 class="wp-block-heading has-text-align-center">Please input some content in the form before previewing!</h3>
<!-- /wp:heading --></div></div>
<!-- /wp:cover -->';

    if ($this->formData && $this->formData['homePage'] && $this->formData['homePage']['heroBanner']) {
      // Find selected service URL
      $selectedServiceUrl = '#';
      $selectedService = $this->formData['homePage']['heroBanner']['selectedService'];
      $selectedServiceExploded = explode(" - ", $selectedService);
      if (is_countable($selectedServiceExploded) && count($selectedServiceExploded) == 2) {
        $selectedServiceCat = $selectedServiceExploded[0];
        $selectedServiceService = $selectedServiceExploded[1];

        if ($servicesOutput['categoryPages'] && is_countable($servicesOutput['categoryPages'])) {
          foreach ($servicesOutput['categoryPages'] as $categorypage) {
            if ($categorypage['title'] == $selectedServiceCat) {
              foreach ($categorypage['services'] as $service) {
                if ($service['title'] == $selectedServiceService) $selectedServiceUrl = $service['url'];
              }
            }
          }
        }
      }


      global $homeHeroPatternParams;
      $homeHeroPatternParams = [
        "theme" => $this->formData['homePage']['heroBanner']['selectedStyle'],
        "variation" => $this->themeVariation,
        "main_title" => $this->formData['homePage']['heroBanner']['primaryTagline'],
        "subtitle" => $this->formData['homePage']['heroBanner']['serviceTagline'],
        "buttons" => $servicesOutput['categoryPages'],
        "image_id" => $this->mainImageID,
        "selling_points" => $this->formData['homePage']['heroBanner']['valuePropositions'],
        "price_card" => $this->formData['homePage']['heroBanner']['showPriceCard'] ? [
          'priceCardDescription' => $this->formData['homePage']['heroBanner']['priceCardDescription'],
          'priceCardLinkText' => $this->formData['homePage']['heroBanner']['priceCardLinkText'],
          'priceCardTitle' => $this->formData['homePage']['heroBanner']['priceCardTitle'],
          'selectedService' => $selectedServiceUrl,
        ] : null
      ];
      $pageContent = require plugin_dir_path(__FILE__) . 'patterns/home/hero.php';
    }


    if ($this->formData && $this->formData['homePage'] && $this->formData['homePage']['sections']) {
      $pageBuilder = new MioCommerceOlympusHomePageBuilder();

      $reviewPlatforms = [];
      if ($this->formData['generalInfo'] && $this->formData['generalInfo']['reviewPlatforms']) $reviewPlatforms = $this->formData['generalInfo']['reviewPlatforms'];

      $pageContent .= $pageBuilder->buildPage(
        $this->formData['homePage']['sections'],
        $this->formData['homePage']['sectionsOrder'],
        $servicesOutput,
        $this->chosenTheme,
        $pageUrls,
        $reviewPlatforms,
        $reusableBlocks
      );
    }

    $homePage = wp_insert_post([
      'post_title'    => 'Home',
      'post_type'      => 'page',
      'post_status'    => 'publish',
      'post_content'   => $pageContent,
      'comment_status' => 'closed',
      'ping_status'    => 'closed',
    ]);

    if ($this->mainImageID) set_post_thumbnail($homePage, $this->mainImageID);
    update_option('show_on_front', 'page');
    update_option('page_on_front', $homePage);
    return $homePage;
  }

  private function createBlogPage($pageUrls) {

    $genericBlogContent = require plugin_dir_path(__FILE__) . 'patterns/blogs/generic-blog.php';

    $contactPageUrl = $pageUrls['contact'];

    // Remplacer les tokens dans le contenu
    $replacements = [
      '{{CONTACT_URL}}' => $contactPageUrl
    ];

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

    // Create generic blog
    $genericBlog = wp_insert_post([
      'post_title'    => 'Why Hiring Professionals for Home Services Saves You Money in the Long Run',
      'post_type'      => 'post',
      'post_status'    => 'publish',
      'post_content'   => $genericBlogContent,
      'comment_status' => 'closed',
      'ping_status'    => 'closed',
      '_thumbnail_id' => 154,
    ]);

    // Create cleaning blog
    $industry = $this->onboard_data['industry'];
    if (in_array($industry, ['1', '2', '3', '7', '9', '18', '19', '37', '38'])) {
      $cleaningBlogContent = require plugin_dir_path(__FILE__) . 'patterns/blogs/cleaning-blog.php';

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

      $cleaningBlog = wp_insert_post([
        'post_title'    => '5 Cleaning Secrets the Professionals Don\'t Want You to Know',
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'post_content'   => $cleaningBlogContent,
        'comment_status' => 'closed',
        'ping_status'    => 'closed',
        '_thumbnail_id' => 9178,
      ]);
    }


    // Create the blogs index page
    $blogPage = wp_insert_post([
      'post_title'    => 'Blog',
      'post_type'      => 'page',
      'post_status'    => 'publish',
      'post_content'   => "",
      'comment_status' => 'closed',
      'ping_status'    => 'closed',
    ]);
    update_option('page_for_posts', $blogPage);

    return $blogPage;
  }

  private function setGeneralOptions($servicesOutput, $pageUrls) {
    if (!$this->formData || !$this->formData['generalInfo']) return;

    // colors
    $theme_json = file_get_contents(get_template_directory() . '/theme.json');
    if ($theme_json) {
      $primaryCol = ($this->formData['generalInfo']['primaryColor']) ? $this->formData['generalInfo']['primaryColor'] : '#0a1c44';
      $secondaryCol = ($this->formData['generalInfo']['secondaryColor']) ? $this->formData['generalInfo']['secondaryColor'] : '#0087ab';
      $theme_json = json_decode($theme_json, true);
      $theme_json['settings']['color']['palette'] = [
        [
          "color" => "#ffffff",
          "name" => "Base",
          "slug" => "base"
        ],
        [
          "color" => "#000000",
          "name" => "Contrast",
          "slug" => "contrast"
        ],
        [
          "color" => $primaryCol,
          "name" => "Primary",
          "slug" => "primary"
        ],
        [
          "color" => $secondaryCol,
          "name" => "Secondary",
          "slug" => "secondary"
        ],
        [
          "color" => "#f7f7f7",
          "name" => "Neutral",
          "slug" => "neutral"
        ]
      ];
      file_put_contents(get_template_directory() . '/theme.json', json_encode($theme_json));
    }

    // Theme selector
    update_field('theme', $this->chosenTheme, 'option');


    // Contact info
    $contactInfoField = [];
    if ($this->formData['generalInfo']['businessPhone']) {
      array_push($contactInfoField, [
        'field_5ec0ae80e32e2' => [
          'url' => '+tel' . $this->formData['generalInfo']['businessPhone'],
          'title' => $this->formData['generalInfo']['businessPhone']
        ],
        'field_65988aa50ef95' => 'phone-solid',
      ]);
    }

    if ($this->formData['generalInfo']['businessEmail']) {
      array_push($contactInfoField, [
        'field_5ec0ae80e32e2' => [
          'url' => 'mailto:' . $this->formData['generalInfo']['businessEmail'],
          'title' => $this->formData['generalInfo']['businessEmail'],
          "target" => "_blank"
        ],
        'field_65988aa50ef95' => 'envelope-regular',
      ]);
    }


    if ($contactInfoField) {
      update_field('general_contact_info', $contactInfoField, 'option');
    }

    // Social icons
    $socialIconsField = [];
    if ($this->formData['generalInfo']['socialMedia']) {
      foreach ($this->formData['generalInfo']['socialMedia'] as $socialMedias) {
        array_push($socialIconsField, [
          'field_5ec2c3f967960' => [
            'url' => $socialMedias['url'],
            'title' => "",
            "target" => "_blank"
          ],
          'field_65988a7ad0772' => $socialMedias['icon'],
        ]);
      }
    }

    if ($socialIconsField) {
      update_field('social_icons', $socialIconsField, 'option');
    }

    // Site logo and favicon
    // // logo
    if ($this->formData['generalInfo']['businessLogo']) {
      set_theme_mod('custom_logo', $this->formData['generalInfo']['businessLogo']['attachment_id']);

      update_field('logo_main_nav', $this->formData['generalInfo']['businessLogo']['attachment_id'], 'option');
      update_field('logo_footer', $this->formData['generalInfo']['businessLogo']['attachment_id'], 'option');
    }

    if ($this->formData['generalInfo']['favicon']) {
      update_option('site_icon', $this->formData['generalInfo']['favicon']['attachment_id']);
    }

    // Site title and description
    update_option('blogname', $this->formData['generalInfo']['businessName']);

    // Header
    $menuItems = [];
    // services menu
    if ($servicesOutput['categoryPages'] && is_countable($servicesOutput['categoryPages'])) {
      if (count($servicesOutput['categoryPages']) == 1) {
        $submenu = [];
        foreach ($servicesOutput['categoryPages'][0]['services'] as $service) {
          array_push($submenu, [
            'field_65961021a8506' => [
              'url' => $service['url'],
              'title' => $service['title']
            ]
          ]);
        }
        array_push($menuItems, [
          'field_65960fbea8503' => [
            'url' => $servicesOutput['categoryPages'][0]['url'],
            'title' => $servicesOutput['categoryPages'][0]['title']
          ],
          'field_65960ff4a8504' => 1,
          'field_6596100ca8505' => $submenu
        ]);
      } else if (count($servicesOutput['categoryPages']) > 1) {
        $submenu = [];
        foreach ($servicesOutput['categoryPages'] as $categoryPage) {
          $subSubmenu = [];
          foreach ($categoryPage['services'] as $service) {
            array_push($subSubmenu, [
              'field_6596104ba8509' => [
                'url' => $service['url'],
                'title' => $service['title']
              ]
            ]);
          }
          array_push($submenu, [
            'field_65961021a8506' => [
              'url' => $categoryPage['url'],
              'title' => $categoryPage['title']
            ],
            'field_6596102aa8507' => 1,
            'field_6596103ba8508' => $subSubmenu
          ]);
        }
        array_push($menuItems, [
          'field_65960fbea8503' => [
            'url' => $servicesOutput['categoryPages'][0]['url'],
            'title' => 'Our Services'
          ],
          'field_65960ff4a8504' => 1,
          'field_6596100ca8505' => $submenu
        ]);
      }
    }

    if ($pageUrls['about']) {
      $submenu = [
        [
          'field_65961021a8506' => [
            'url' => $pageUrls['about'],
            'title' => 'About us'
          ]
        ]
      ];

      if ($pageUrls['contact']) {
        array_push($submenu, [
          'field_65961021a8506' => [
            'url' => $pageUrls['contact'],
            'title' => 'Contact us'
          ]
        ]);
      }

      if ($pageUrls['faq']) {
        array_push($submenu, [
          'field_65961021a8506' => [
            'url' => $pageUrls['faq'],
            'title' => 'Frequently Asked Questions'
          ]
        ]);
      }

      array_push($menuItems, [
        'field_65960fbea8503' => [
          'url' => $pageUrls['about'],
          'title' => 'Our Company'
        ],
        'field_65960ff4a8504' => 1,
        'field_6596100ca8505' => $submenu
      ]);
    }

    if (isset($this->onboard_data['company_slug'])) {
      $loginLink = 'https://myservices.miocommerce.com/' . $this->onboard_data['company_slug'] . '/' . 'signin/';
      array_push($menuItems, [
        'field_65960fbea8503' => [
          'url' => $loginLink,
          'title' => 'Customer Login',
          'target' => '_blank'
        ]
      ]);
    }

    if (isset($pageUrls['blog'])) {
      array_push($menuItems, [
        'field_65960fbea8503' => [
          'url' => $pageUrls['blog'],
          'title' => 'Blog',
          'target' => ''
        ]
      ]);
    }

    if ($menuItems) update_field('menu_items', $menuItems, 'option');

    if (
      $servicesOutput['categoryPages'] &&
      $servicesOutput['categoryPages'][0] &&
      $servicesOutput['categoryPages'][0]['services'] &&
      $servicesOutput['categoryPages'][0]['services'][0] &&
      $servicesOutput['categoryPages'][0]['services'][0]['booking_page_url']
    ) {
      update_field('menu_call_to_action', [
        'title' => $servicesOutput['categoryPages'][0]['services'][0]['booking_cta_title'],
        'url' => $servicesOutput['categoryPages'][0]['services'][0]['booking_page_url']
      ], 'option');
    }

    $ctaMenuItems = [];
    if ($servicesOutput['categoryPages'] && is_countable($servicesOutput['categoryPages'])) {
      foreach ($servicesOutput['categoryPages'] as $categoryPage) {
        if (count($servicesOutput['categoryPages']) == 1) {
          foreach ($categoryPage['services'] as $service) {
            array_push($ctaMenuItems, [
              'field_659889028c2c9' => [
                'url' => $service['booking_page_url'],
                'title' => $service['title']
              ]
            ]);
          }
        } else {
          $submenu = [];
          foreach ($categoryPage['services'] as $service) {
            array_push($submenu, [
              'field_659889498c2cc' => [
                'url' => $service['booking_page_url'],
                'title' => $service['title']
              ]
            ]);
          }
          array_push($ctaMenuItems, [
            'field_659889028c2c9' => [
              'url' => $categoryPage['url'],
              'title' => $categoryPage['title']
            ],
            'field_659889288c2ca' => 1,
            'field_659889398c2cb' => $submenu
          ]);
        }
      }
    }
    if ($ctaMenuItems) {
      update_field('cta_has_submenu', 1, 'option');
      update_field('cta_submenu', $ctaMenuItems, 'option');
    }

    // Footer
    $footerMenuItems = [];

    $sitemapItems = [];
    array_push($sitemapItems, [
      'field_65a9fd9fd411e' => [
        'url' => '#',
        'title' => 'Sitemap'
      ]
    ]);
    if ($pageUrls['about']) {
      array_push($sitemapItems, [
        'field_65a9fd9fd411e' => [
          'url' => $pageUrls['about'],
          'title' => 'About us'
        ]
      ]);
    }

    if ($pageUrls['contact']) {
      array_push($sitemapItems, [
        'field_65a9fd9fd411e' => [
          'url' => $pageUrls['contact'],
          'title' => 'Contact us'
        ]
      ]);
    }

    if ($pageUrls['faq']) {
      array_push($sitemapItems, [
        'field_65a9fd9fd411e' => [
          'url' => $pageUrls['faq'],
          'title' => 'Frequently Asked Questions'
        ]
      ]);
    }

    if (isset($this->onboard_data['company_slug'])) {
      $loginLink = 'https://myservices.miocommerce.com/' . $this->onboard_data['company_slug'] . '/' . 'signin/';
      array_push($sitemapItems, [
        'field_65a9fd9fd411e' => [
          'url' => $loginLink,
          'title' => 'Customer Login',
          'target' => '_blank'
        ]
      ]);
    }


    if (isset($pageUrls['blog'])) {
      array_push($sitemapItems, [
        'field_65a9fd9fd411e' => [
          'url' => $pageUrls['blog'],
          'title' => 'Blog',
          'target' => ''
        ]
      ]);
    }


    if ($sitemapItems) {
      array_push($footerMenuItems, [
        'field_65a9fd88d411d' => $sitemapItems
      ]);
    }


    foreach ($servicesOutput['categoryPages'] as $categoryPage) {
      $submenu = [];
      array_push($submenu, [
        'field_65a9fd9fd411e' => [
          'url' => $categoryPage['url'],
          'title' => $categoryPage['title']
        ]
      ]);
      foreach ($categoryPage['services'] as $service) {
        array_push($submenu, [
          'field_65a9fd9fd411e' => [
            'url' => $service['url'],
            'title' => $service['title']
          ]
        ]);
      }
      array_push($footerMenuItems, [
        'field_65a9fd88d411d' => $submenu
      ]);
    }

    if ($footerMenuItems) update_field('f_menu_cols', $footerMenuItems, 'option');
    update_field('background_color', '#efefef', 'option');

    // Floating dock
    if ($this->formData['generalInfo']['floatingDockScript']) {
      update_field('floating_dock_script', $this->formData['generalInfo']['floatingDockScript'], 'option');
    }
  }
}
