<?php

/**
 * BookiFlex
 *
 * @package   BookiFlex
 * @author    BookiFlex
 * @copyright Copyright (c) 2025 BookiFlex
 * @license   GPL-2.0-or-later
 *
 * @link      https://bookiflex.com
 */
declare (strict_types = 1);
namespace BookiFlex\Plugin\Admin;

use BookiFlex\Core\Admin\AbstractAssetsManager;
use BookiFlex\Core\Admin\AssetContext;
use BookiFlex\Core\Admin\CPT\AccommodationType;
use BookiFlex\Core\Admin\Settings\SettingsManager;
use BookiFlex\Core\Provider\LocalTimeZone;
defined( 'ABSPATH' ) || exit;
class AssetsManager extends AbstractAssetsManager {
    protected function mergeAdditionalManifests() : void {
    }

    public function enqueueAdminAssets() : void {
        if ( !$this->isBookiFlexAdminPage() ) {
            return;
        }
        // Vue — single path, dev manifest overrides prod vue path
        $this->enqueueScript( 'bookiflex-vue', $this->assetUrl( $this->asset( 'external', 'vue' ) ), ['wp-i18n'] );
        global $post_type;
        if ( $post_type === AccommodationType::POST_TYPE ) {
            $this->enqueueScript(
                'bookiflex-dynamic-checkboxes',
                $this->assetUrl( $this->asset(
                    'prod',
                    'core',
                    'dynamic-checkboxes',
                    'js'
                ) ),
                [
                    'jquery-core',
                    'carbon-fields-vendor',
                    'carbon-fields-core',
                    'carbon-fields-metaboxes',
                    'wp-hooks'
                ],
                true
            );
        }
        // Carbon fields style
        $this->enqueueStyle( 'carbon-fields-style', $this->assetUrl( 'assets/vendor/carbon_fields/style.css' ), ['carbon-fields-metaboxes'] );
        // Radio card field
        $this->enqueueScript(
            'bookiflex-radio-card',
            $this->assetUrl( 'assets/vendor/carbon_fields/radio-card.js' ),
            ['carbon-fields-vendor', 'carbon-fields-core', 'carbon-fields-metaboxes'],
            true
        );
        $this->enqueueAdminApp();
        $this->loadTranslationsFor( [$this->asset( 'prod', 'admin', 'js' )], AssetContext::ADMIN );
        $locale = get_locale();
        $manifest = $this->getManifest();
        $this->addBookiFlexData( [
            'restUrl'          => esc_url_raw( rest_url() ),
            'nonce'            => wp_create_nonce( 'wp_rest' ),
            'version'          => $manifest['version'] ?? '1.0.0',
            'localeTimeZone'   => LocalTimeZone::get()->getName(),
            'locale'           => ( strrpos( $locale, '_' ) > 0 ? explode( '_', $locale )[0] : $locale ),
            'shoelaceBasePath' => $this->assetUrl( $this->asset( 'external', 'shoelace', 'basePath' ) ),
        ], AssetContext::ADMIN );
    }

    protected function enqueueAdminApp() : void {
        $this->enqueueModuleScript( 'bookiflex-admin-app', $this->assetUrl( $this->asset( 'prod', 'admin', 'js' ) ) );
        $this->enqueueStyle( 'bookiflex-admin-style', $this->assetUrl( $this->asset( 'prod', 'admin', 'css' ) ) );
    }

    public function enqueueFrontendAssets() : void {
        // Vue — single path, dev manifest overrides prod vue path
        $this->enqueueScript( 'bookiflex-vue', $this->assetUrl( $this->asset( 'external', 'vue' ) ), ['wp-i18n'] );
        $config = $this->container->get( 'config' );
        if ( $config->isBookingButtonActive() || current_user_can( 'manage_options' ) ) {
            $this->enqueueScript(
                'bookiflex-magic-button',
                $this->assetUrl( $this->asset(
                    'prod',
                    'widgets',
                    'button',
                    'js'
                ) ),
                [],
                false,
                [
                    'strategy' => 'defer',
                ]
            );
        }
        // <bookiflex-search-form> web component — single WP handle (registered in
        // AbstractAssetsManager::registerBlockAssets), shared with the Gutenberg
        // block and the Elementor widget. Enqueuing by handle lets WP de-duplicate
        // the output when a block/widget already enqueued it on the same page.
        $this->enqueueScript( 'bookiflex-search-form' );
        // Widget controller - use WP 6.6+ Script Modules API
        $this->enqueueWidgetController();
        $widgetLocale = $config->getWidgetLanguage();
        $widgetLang = ( substr( $widgetLocale, 0, 2 ) ?: 'en' );
        // Calendar (unavailable dates / min nights / default guests) is a Pro-only
        // feature — its settings only exist when the UnavailableDates extension is
        // loaded, so Free gets fixed conservative defaults instead of reading them.
        $widget = [
            'locale'               => $widgetLang,
            'maxGuests'            => $config->getMaxGuests(),
            'children'             => $config->getChildrenGuestsConfig(),
            'promoCodeEnabled'     => false,
            'showUnavailableDates' => false,
            'minNights'            => 1,
            'defaultGuests'        => 2,
        ];
        $this->addBookiFlexData( [
            'restUrl'    => rest_url( '/' ),
            'nonce'      => wp_create_nonce( 'bookiflex_nonce' ),
            'widget'     => $widget,
            'controller' => [
                'scripts' => [$this->assetUrl( $this->asset(
                    'prod',
                    'widgets',
                    'booking',
                    'js'
                ) ) . "?ver={$this->plugin->getVersion()}"],
                'css'     => [$this->assetUrl( $this->asset(
                    'prod',
                    'vendor',
                    'glightbox',
                    'css'
                ) ) . "?ver={$this->plugin->getVersion()}"],
            ],
        ], AssetContext::FRONTEND );
        $this->loadTranslationsFor( [$this->asset(
            'prod',
            'widgets',
            'booking',
            'js'
        )], AssetContext::FRONTEND, $widgetLocale );
    }

    protected function enqueueWidgetController() : void {
        $this->enqueueModuleScript( 'bookiflex-widget-controller', $this->assetUrl( $this->asset(
            'prod',
            'widgets',
            'controller',
            'js'
        ) ) );
    }

    public function printFrontendModules() : void {
        $config = $this->container->get( 'config' );
        $isBookingButtonActive = $config->isBookingButtonActive();
        $canManageOptions = current_user_can( 'manage_options' );
        $isAdminPreview = !$isBookingButtonActive && $canManageOptions;
        if ( ($isBookingButtonActive || $canManageOptions) && $GLOBALS['pagenow'] !== 'wp-login.php' ) {
            ?>
            <booking-widget-button
                text="<?php 
            echo esc_attr( $config->getBookingButtonText() );
            ?>"
                position="<?php 
            echo esc_attr( $config->getBookingButtonPosition() );
            ?>"
                color="<?php 
            echo esc_attr( $config->getBookingButtonColor() );
            ?>"
                pulse="<?php 
            echo esc_attr( $config->isBookingButtonPulse() );
            ?>"
                <?php 
            if ( $isAdminPreview ) {
                ?>admin-preview="true"<?php 
            }
            ?>
            ></booking-widget-button>
            <?php 
        }
    }

    public function printFrontendHead() : void {
        $cssTokens = carbon_get_theme_option( SettingsManager::WIDGET_CSS_TOKENS );
        if ( !empty( $cssTokens ) ) {
            echo '<style id="bflex-widget-theme">#booking-widget, bflex-booking-widget, bookiflex-search-form {' . wp_strip_all_tags( $cssTokens ) . '}</style>';
        }
    }

    public function printAdminModules() : void {
        ?>
        <div id="bflex-app--app"></div>
        <?php 
    }

}
