<?php
/**
 * Admin asset enqueuer.
 *
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class ZINV_Assets {

    public static function register(): void {
        add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue' ] );
        // Invalidate cached script-data settings whenever settings change.
        add_action( 'zinv_settings_saved', [ __CLASS__, 'flush_settings_cache' ] );
    }

    public static function flush_settings_cache(): void {
        wp_cache_delete( 'zinv_assets_settings', 'zoventic-invoices' );
        if ( class_exists( 'ZINV_PDF_Generator' ) ) {
            ZINV_PDF_Generator::delete_all_cached_pdfs();
        }
    }

    public static function enqueue( string $hook ): void {
        if ( 'toplevel_page_zoventic-invoices' !== $hook ) {
            return;
        }

        self::enqueue_app();
    }


    private static function enqueue_app(): void {
        $assets_url = ZINV_PLUGIN_URL . 'assets/admin';
        $assets_dir = ZINV_PLUGIN_DIR . 'assets/admin';
        $version    = ZINV_VERSION;

        wp_enqueue_script(
            'zoventic-invoices-admin',
            $assets_url . '/app.js',
            [ 'wp-i18n' ],
            file_exists( $assets_dir . '/app.js' ) ? (string) filemtime( $assets_dir . '/app.js' ) : $version,
            true
        );

        wp_set_script_translations(
            'zoventic-invoices-admin',
            'zoventic-invoices',
            ZINV_PLUGIN_DIR . 'languages'
        );

        $css_file = $assets_dir . '/app.css';
        if ( file_exists( $css_file ) ) {
            wp_enqueue_style(
                'zoventic-invoices-admin',
                $assets_url . '/app.css',
                [],
                (string) filemtime( $css_file )
            );
        } else {
            wp_register_style( 'zoventic-invoices-admin', false, [], $version );
            wp_enqueue_style( 'zoventic-invoices-admin' );
        }

        wp_add_inline_style(
            'zoventic-invoices-admin',
            '#adminmenuwrap,#adminmenu .wp-submenu-wrap,#adminmenu .wp-submenu{z-index:10000 !important;}'
            . '#zoventic-invoices-app input[type=checkbox]::before,#zoventic-invoices-app input[type=checkbox]:checked::before,#zoventic-invoices-app input[type=checkbox]::after,#zoventic-invoices-app input[type=checkbox]:checked::after{content:""!important;display:none!important;width:0!important;height:0!important;background:none!important;}'
            . '#wpbody-content > .ddi-global-onboarding-widget ~ #zoventic-invoices-app, #wpbody-content > .wrap.ddi-global-onboarding-widget ~ #zoventic-invoices-app{margin-top:-60px!important;}'
            . '.mantine-DatePicker-day[data-today],.mantine-DatePickerInput-day[data-today],.mantine-DateInput-day[data-today],.mantine-Calendar-day[data-today],.mantine-Day-day[data-today],button[data-today],button[data-today="true"],td[data-today],[data-today]{background-color:#3b82f6!important;color:#ffffff!important;font-weight:800!important;border-radius:50%!important;box-shadow:0 0 0 2px #60a5fa!important;}'
            . 'body.toplevel_page_zoventic-invoices .notice,body.toplevel_page_zoventic-invoices .updated,body.toplevel_page_zoventic-invoices .error,body.toplevel_page_zoventic-invoices .update-nag,body.toplevel_page_zoventic-invoices div.updated,body.toplevel_page_zoventic-invoices div.error,body.toplevel_page_zoventic-invoices .is-dismissible,body.toplevel_page_zoventic-invoices #wpbody-content > .notice,body.toplevel_page_zoventic-invoices #wpbody-content > .update-nag,body.toplevel_page_zoventic-invoices #wpbody-content > .updated,body.toplevel_page_zoventic-invoices #wpbody-content > .error,body.zinv-fullscreen-app .notice,body.zinv-fullscreen-app .update-nag,body.zinv-fullscreen-app .updated,body.zinv-fullscreen-app .error,body.zinv-fullscreen-app #wpbody-content > .notice,body.zinv-fullscreen-app #wpbody-content > .update-nag{display:none !important;}'
        );

        $script_data = self::build_script_data();
        wp_localize_script( 'zoventic-invoices-admin', 'zoventicInvoicesData', $script_data );
    }

    /**
     * @return array<string, mixed>
     */
    private static function build_script_data(): array {
        $context = 'admin';
        $settings = self::get_settings();

        $data = [
            'restUrl'            => esc_url_raw( rest_url( 'zoventic-invoices/v1/' ) ),
            'wpMediaUrl'         => esc_url_raw( rest_url( 'wp/v2/media' ) ),
            'nonce'              => wp_create_nonce( 'wp_rest' ),
            'isProActive'        => (bool) apply_filters( 'zoventic_invoices_is_pro_active', false ),
            'onboardingComplete' => true,
            'currency'           => $settings['currency'] ?? 'USD',
            'adminUrl'           => esc_url( admin_url( 'admin.php?page=zoventic-invoices' ) ),
            'upgradeUrl'         => 'https://zoventic.com/invoices/',
        ];

        if ( 'admin' === $context ) {
            $current_user = wp_get_current_user();
            $display_name = (string) $current_user->display_name;
            $initial      = function_exists( 'mb_substr' )
                ? mb_substr( $display_name, 0, 1 )
                : substr( $display_name, 0, 1 );

            $data['currentUser']        = [
                'displayName' => $display_name,
                'email'       => $current_user->user_email,
                'avatarUrl'   => get_avatar_url( $current_user->ID, [ 'size' => 72 ] ),
                'initials'    => strtoupper( $initial ),
            ];
        }

        /** @var array<string, mixed> */
        return apply_filters( 'zoventic_invoices_script_data', $data );
    }

    private static function get_settings(): array {
        $cached = wp_cache_get( 'zinv_assets_settings', 'zoventic-invoices' );
        if ( is_array( $cached ) ) {
            return $cached;
        }

        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT setting_key, setting_value FROM {$wpdb->prefix}zinv_settings WHERE setting_group IN (%s, %s)",
            'general',
            'invoicing'
        ) );

        $settings = [];
        if ( is_array( $rows ) ) {
            foreach ( $rows as $row ) {
                $settings[ $row->setting_key ] = $row->setting_value;
            }
        }

        wp_cache_set( 'zinv_assets_settings', $settings, 'zoventic-invoices', MINUTE_IN_SECONDS * 5 );
        return $settings;
    }
}
