<?php

namespace DaftPlug\Generatify\Admin;

use DaftPlug\Generatify\Helpers\Utils;
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class UI {
    public function __construct() {
        add_filter( 'plugin_action_links_' . GENERATIFY_BASENAME, [$this, 'addPluginActionLinks'] );
        add_action( 'admin_enqueue_scripts', [$this, 'loadAssets'] );
        add_action( 'admin_menu', [$this, 'addMenuPages'] );
        \DaftPlug\Generatify\generatify_pro()->add_filter( 'pricing_url', [$this, 'customizePricingUrl'] );
        \DaftPlug\Generatify\generatify_pro()->add_filter(
            'is_submenu_visible',
            [$this, 'showContactOrSupportForum'],
            10,
            2
        );
        if ( \DaftPlug\Generatify\generatify_pro()->is_premium() ) {
            \DaftPlug\Generatify\generatify_pro()->add_filter( 'connect/before', [$this, 'customizeActivationScreen'] );
        }
    }

    public function customizeActivationScreen( $activation_state ) {
        $pluginIconUrl = esc_url( plugins_url( 'assets/media/icons/logo.png', GENERATIFY_FILE ) );
        echo '
      <script>
        document.addEventListener("DOMContentLoaded", function() {
          const pluginIconUrl = "' . esc_js( $pluginIconUrl ) . '";
          const pluginIconImg = document.querySelector("#fs_connect .fs-header .fs-plugin-icon img");
          if (pluginIconImg) {
            pluginIconImg.src = pluginIconUrl;
          }
        });
      </script>
    ';
        if ( $activation_state['is_license_activation'] ) {
            echo '
        <style>
          #fs_connect {
            width: 530px;
            margin: 80px auto 20px;
          }

          #fs_connect .fs-box-container {
            background-color: #ffffff;
            border: 1px solid #e5e7eb;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            border-radius: 0.75rem;
          }

          #fs_connect .fs-content {
            padding: 20px;
          }

          #fs_connect .fs-license-key-container {
            width: auto;
            margin-top: 15px;
          }

          #fs_connect .fs-header .fs-plugin-icon {
            top: -50px;
          }

          #fs_connect #fs_license_key {
            padding: 0.5rem 0.75rem;
            width: 100%;
            border: 1px solid #e5e7eb;
            border-radius: 0.5rem;
            font-size: 0.875rem;
            color: #000000;
            background-color: #ffffff;
            line-height: 1.25rem;
          }

          #fs_connect #fs_license_key:focus {
            border-color: #3b82f6;
            outline: none;
          }

          #fs_connect .dashicons-admin-network {
            display: none;
          }

          #fs_connect a.show-license-resend-modal,
          #fs_connect #license_issues_link {
            margin-top: 5px;
            font-size: 0.75rem;
            line-height: 1.25rem;
            color: #6b7280;
            cursor: pointer;
            text-decoration: none;
            outline: none;
          }

          #fs_connect a.show-license-resend-modal:hover,
          #fs_connect #license_issues_link:hover {
            color: #374151;
            text-decoration: underline;
          }

          #fs_connect .fs-actions .button-primary {
            padding: 0.625rem 1.5rem;
            font-size: 0.875rem;
            line-height: 1.25rem;
            font-weight: 600;
            border-radius: 0.5rem;
            background-color: #2563eb;
            color: #ffffff;
            cursor: pointer;
            height: auto;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05) !important;
          }

          #fs_connect .fs-actions .button-primary:hover {
            background-color: #1d4ed8;
          }

          #fs_connect .fs-actions .button-primary:disabled {
            opacity: 0.7;
            cursor: not-allowed;
          }
        </style>
      ';
        }
    }

    public function customizePricingUrl( $url ) {
        return Utils::getUpgradeUrl();
    }

    public function showContactOrSupportForum( $is_visible, $menu_id ) {
        if ( $menu_id === 'contact' ) {
            return \DaftPlug\Generatify\generatify_pro()->can_use_premium_code();
        }
        if ( $menu_id === 'support' ) {
            return !\DaftPlug\Generatify\generatify_pro()->can_use_premium_code();
        }
        return $is_visible;
    }

    public function addPluginActionLinks( $links ) {
        $links['upgrade'] = '<a href="' . Utils::getUpgradeUrl() . '" style="color:#2563eb;font-weight:700;display:inline-flex;align-items:center;gap:4px;">' . __( 'Upgrade to Pro 🚀', 'generatify' ) . '</a>';
        $links['settings'] = '<a href="' . esc_url( admin_url( 'admin.php?page=generatify' ) ) . '">' . __( 'Settings', 'generatify' ) . '</a>';
        return $links;
    }

    public function addMenuPages() {
        add_menu_page(
            'Generatify',
            'Generatify',
            'manage_options',
            'generatify',
            [$this, 'renderOverviewPage'],
            plugins_url( 'assets/media/icons/menu.png', GENERATIFY_FILE ),
            55
        );
        add_submenu_page(
            'generatify',
            'Overview',
            'Overview',
            'manage_options',
            'generatify-overview',
            [$this, 'renderOverviewPage'],
            1
        );
        add_submenu_page(
            'generatify',
            'Settings',
            'Settings',
            'manage_options',
            'generatify-settings',
            [$this, 'renderSettingsPage'],
            2
        );
        remove_submenu_page( 'generatify', 'generatify' );
        $this->addMenuSeparators();
    }

    private function addMenuSeparators() {
        global $menu;
        $position = null;
        foreach ( $menu as $key => $item ) {
            if ( isset( $item[2] ) && $item[2] === 'generatify' ) {
                $position = $key;
                break;
            }
        }
        if ( $position !== null ) {
            if ( !isset( $menu[(int) ($position - 1)] ) ) {
                $menu[(int) ($position - 1)] = [
                    '',
                    'read',
                    'separator-generatify-top',
                    '',
                    'wp-menu-separator generatify'
                ];
            }
            if ( !isset( $menu[(int) ($position + 1)] ) ) {
                $menu[(int) ($position + 1)] = [
                    '',
                    'read',
                    'separator-generatify-bottom',
                    '',
                    'wp-menu-separator generatify'
                ];
            }
            ksort( $menu );
        }
    }

    public function loadAssets( $hook ) {
        wp_register_script(
            'generatify-upgrade-menu-item-edit',
            false,
            [],
            GENERATIFY_VERSION,
            true
        );
        wp_enqueue_script( 'generatify-upgrade-menu-item-edit' );
        $js = "\r\n      document.addEventListener('DOMContentLoaded', function () {\r\n        const fsUpgradeItems = document.querySelectorAll(\r\n          'span.fs-submenu-item.pricing.upgrade-mode'\r\n        );\r\n\r\n        fsUpgradeItems.forEach(function(fsUpgradeItem) {\r\n          const parentLink = fsUpgradeItem.closest('a');\r\n          if (parentLink) {\r\n            parentLink.removeAttribute('target');\r\n            parentLink.removeAttribute('rel');\r\n          }\r\n\r\n          fsUpgradeItem.textContent = 'Upgrade to Pro 🚀';\r\n          fsUpgradeItem.style.color = '#fff';\r\n          fsUpgradeItem.style.fontWeight = '500';\r\n          fsUpgradeItem.style.fontSize = '12px';\r\n          fsUpgradeItem.style.lineHeight = '1';\r\n          fsUpgradeItem.style.background = '#155dfc';\r\n          fsUpgradeItem.style.padding = '9px';\r\n          fsUpgradeItem.style.display = 'flex';\r\n          fsUpgradeItem.style.alignItems = 'center';\r\n          fsUpgradeItem.style.justifyContent = 'center';\r\n          fsUpgradeItem.style.borderRadius = '6px';\r\n          fsUpgradeItem.style.border = '1px solid transparent';\r\n          fsUpgradeItem.style.textDecoration = 'none';\r\n        });\r\n      });\r\n    ";
        wp_add_inline_script( 'generatify-upgrade-menu-item-edit', $js );
        if ( $hook && strpos( $hook, 'generatify' ) !== false ) {
            remove_all_actions( 'admin_notices' );
            remove_all_actions( 'all_admin_notices' );
            $dependencies = [];
            $dependencies[] = 'wp-i18n';
            $dependencies[] = 'jquery';
            // Load Freemius
            wp_enqueue_script(
                'generatify-freemius',
                'https://checkout.freemius.com/js/v1/',
                $dependencies,
                GENERATIFY_VERSION,
                true
            );
            $dependencies[] = 'generatify-freemius';
            // load admin styles and scripts
            wp_enqueue_style(
                'generatify-admin',
                plugins_url( 'assets/css/admin.min.css', GENERATIFY_FILE ),
                [],
                GENERATIFY_VERSION
            );
            wp_enqueue_script(
                'generatify-admin',
                plugins_url( 'assets/js/admin.min.js', GENERATIFY_FILE ),
                $dependencies,
                GENERATIFY_VERSION,
                true
            );
            wp_set_script_translations( 'generatify-admin', 'generatify' );
            $dependencies[] = 'generatify-admin';
            // WP media
            wp_enqueue_media();
            // Pass PHP variables to JS
            wp_localize_script( 'generatify-admin', 'generatify_admin_js_vars', apply_filters( 'generatify_admin_js_vars', [
                'siteName'     => get_bloginfo( 'name' ),
                'homeUrl'      => Utils::getHomeUrl( '/', false ),
                'pluginDirUrl' => GENERATIFY_DIR_URL,
                'adminUrl'     => trailingslashit( admin_url( '/', 'https' ) ),
                'hasActivePro' => \DaftPlug\Generatify\generatify_pro()->can_use_premium_code(),
                'settings'     => get_option( 'generatify_settings', [] ),
            ] ) );
        }
    }

    public function renderPage( $pageId ) {
        ?>
<style>
#wpfooter {
  display: none !important;
}

#wpbody-content {
  padding-bottom: 0 !important;
}
</style>
<div id="daftplugAdmin">
  <div id="daftplugAdminWrapper" class="relative flex flex-col -ml-2.5 sm:-ml-5 [&_*::-webkit-scrollbar]:w-2 [&_*::-webkit-scrollbar-thumb]:rounded-full [&_*::-webkit-scrollbar-track]:bg-transparent [&_*::-webkit-scrollbar-thumb]:bg-gray-400 [&_*::-webkit-scrollbar-thumb:hover]:bg-gray-500 -daftplugLoading">
    <main id="content" class="flex flex-col w-full py-5 px-2 sm:px-5">
      <?php 
        include_once path_join( GENERATIFY_DIR_PATH, 'includes/admin/views/' . $pageId . '.php' );
        ?>
    </main>
  </div>
</div>
<?php 
    }

    public function renderOverviewPage() {
        return $this->renderPage( 'overview' );
    }

    public function renderSettingsPage() {
        return $this->renderPage( 'settings' );
    }

}
