<?php

namespace Clonable\Services;

use Clonable\Objects\ClonableConfig;
use Clonable\Helpers\Functions;

defined('ABSPATH') || exit;

/**
 * Adds Clonable clone links to the WordPress admin bar.
 */
class AdminUIService
{
    private const PARENT_ID = 'clonable-clones';
    private $menu_image_path = "../images/Logo_Icon_white.svg";

    public function __construct()
    {
         // Hide admin bar on clone URL admin pages.
        add_action('init', [$this, 'hide_admin_bar_on_clone']);
        
        add_action('admin_bar_menu', [$this, 'register_admin_bar_items'], 100);

		add_action('admin_init', [$this, 'register_styles']);
    }

	public function register_styles() {
		// Runs in both admin and front-end when admin bar is visible.
		wp_enqueue_style('clonable-admin-bar', plugin_dir_url(__FILE__) . '../views/css/clonable-admin-bar.css');
	}

    /**
     * Register admin bar items for Clonable clones.
     *
     * @param \WP_Admin_Bar $wp_admin_bar
     * @return void
     */
    public function register_admin_bar_items($wp_admin_bar): void
    {
        if (
            ! is_user_logged_in()
            || ! current_user_can('manage_options')
            || ! is_admin_bar_showing()
            || ! $wp_admin_bar instanceof \WP_Admin_Bar
        ) {
            return;
        }

        $site = ClonableConfig::get_site();
	    if (empty($site)) {
		    return;
	    }

        $clones = $site->get_clones();
        if (empty($clones) || !is_array($clones) || is_wp_error($clones)) {
            return;
        }

        // Parent dropdown node with icon before title.
        $icon_url = plugin_dir_url(__FILE__) . $this->menu_image_path;
        $title_html = sprintf(
            '<span class="ab-icon"><img src="%s" alt="" width="16" height="16" style="display: inline-block" loading="lazy" decoding="async" /></span><span class="ab-label">%s</span>',
            esc_url($icon_url),
            esc_html__('Open clone editor', 'clonable')
        );

        $wp_admin_bar->add_node([
            'id'    => self::PARENT_ID,
            'title' => $title_html,
            'href'  => false,
            'meta'  => ['class' => 'clonable-clones-parent'],
        ]);

        foreach ($clones as $clone) {
            if (empty($clone['id'])) {
                continue;
            }
        
            $toolbar_url = $this->buildToolbarUrl($site->get_id(), $clone['id']);
            $frontend_url = $clone['domain'] . ($clone['subfolder_clone'] ?? '');
            $flag_code = explode('_', $clone['lang_code'])[1] ?? '';

            $title_html = sprintf(
                '<span class="fflag ff-sm fflag-%s" style="margin-right:6px" aria-hidden="true"></span><span class="ab-label">%s</span>',
                esc_attr($flag_code),
                esc_html($frontend_url)
            );

            $wp_admin_bar->add_node([
                'id'     => 'clonable-clone-' . sanitize_key((string) $clone['id']),
                'title'  => $title_html,
                'href'   => esc_url($toolbar_url),
                'parent' => self::PARENT_ID,
                'meta'   => ['class' => 'clonable-clone-item'],
            ]);
        }
    }


     // hide admin bar when on clone url admin page
    public function hide_admin_bar_on_clone(): void
    {
        if (!is_user_logged_in()) {
            return;
        }

        $site_main_url = home_url($_SERVER['REQUEST_URI']);
        $clonable_current_domain = clonable_current_domain();

        $site = ClonableConfig::get_site();
        if (empty($site)) {
            return;
        }

        foreach ($site->get_clones() as $index => $clone) {

            $clone_url = $site->get_clone_url($index);
            $clone_url_without_schema = preg_replace('#^https?://#', '', rtrim($clone_url, '/'));
            $is_probably_clone_url = Functions::str_starts_with($site_main_url, $clone_url_without_schema);

            if ($is_probably_clone_url) {
                remove_action('admin_bar_menu', [$this, 'register_admin_bar_items'], 100);
                add_filter('show_admin_bar', '__return_false');
                return;
            }

            // also check subfolder clones
            if (!empty($clone['subfolder_clone'])) {

                $clone_folder = rtrim($clone['subfolder_clone'], '/');
                $folder_check = strpos($clonable_current_domain, $clone_folder, 0);

                if ($folder_check !== false) {
                    remove_action('admin_bar_menu', [$this, 'register_admin_bar_items'], 100);
                    add_filter('show_admin_bar', '__return_false');
                    return;
                }
            }
        }
    }

    /**
     * Build the toolbar URL for a clone.
     *
     * @param string|int $siteId
     * @param string|int $cloneId
     * @return string
     */
    private function buildToolbarUrl($siteId, $cloneId): string
    {
        $siteId = (string) $siteId;
        $cloneId = (string) $cloneId;
        return "https://app.clonable.net/sites/{$siteId}/clones/{$cloneId}/toolbar";
    }
}