<?php

namespace Flyerimage\Core\Init;

use Flyerimage\Core\Util\Helper;

/**
 * Assets handlers class
 */
class Assets
{
    /**
     * First frontend script handle to attach inline data
     * @var string|null
     */
    private $frontend_primary_handle = null;

    /**
     * Initialize the class
     */
    function __construct()
    {
        if (is_admin()) {
            $home = 'flyer-image';
            $slug = Helper::get_param_value_from_get("page", "");
            if (in_array($slug, [
                $home, $home."-reports"
            ])) {
                add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
            }
        }
        else {
            add_action('wp_enqueue_scripts', [$this, 'enqueue_web_assets']);
            add_action('wp_footer', [$this, 'wp_footer_frontend']);
        }
    }

    /**
     * Reqister admin the assets
     * 
     * @return void
     */
    public function enqueue_admin_assets()
    {
        $scripts = [];
        $main_handle = null;
        $main_file = null;
        // Detect Angular main bundle
        $main_candidates = glob( FLYER_IMAGE_PUBLIC_PATH . '/flyer-image-web/main*.js' );
        if ( ! empty( $main_candidates ) ) {
            $main_file = $main_candidates[0];
            $main_url  = FLYER_IMAGE_PUBLIC_URL . '/flyer-image-web/' . basename( $main_file );
            $main_handle = 'flyerimage-app';
            wp_register_script(
                $main_handle,
                $main_url,
                [],
                filemtime( $main_file ),
                true
            );
            wp_enqueue_script( $main_handle );
            wp_localize_script($main_handle, 'FlyerImage', [
                'apiBase' => rest_url('flyer_image_v9622105412/v1'),
            ]);
        }
        // Register remaining JS assets (excluding the main bundle already handled)
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/flyer-image-web/*.js' );
        if (count($files) > 0){
            foreach ($files as $file_path) {
                if ( $file_path === $main_file ) { continue; }
                $file_name = basename($file_path);
                $handle = 'flyerimage-' . str_replace('.', '_', $file_name) . time();
                $scripts[$handle] = [
                    'src'       => FLYER_IMAGE_PUBLIC_URL . '/flyer-image-web/' . $file_name,
                    'version'   => filemtime($file_path),
                    'deps'      => [],
                    'in_footer' => true
                ];
            }
        }
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/static/*.js' );
        if (count($files) > 0){
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                $handle = 'flyerimage-static-' . str_replace('.', '_', $file_name) . time();
                $scripts[$handle] = [
                    'src'       => FLYER_IMAGE_PUBLIC_URL . '/static/' . $file_name,
                    'version'   => filemtime($file_path),
                    'deps'      => [],
                    'in_footer' => true
                ];
            }
        }
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/scripts/*.js' );
        if (count($files) > 0){
            $hasFlyer = false;
            foreach ($files as $file) {
                if (basename($file) === 'flyer.js') {
                    $hasFlyer = true;
                    break;
                }
            }
            if ($hasFlyer) {
                $files = array_filter($files, function ($file) {
                    return basename($file) !== 'flyermf.js';
                });
            }
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                // Skip api_url.js as we'll handle API URL via inline script
                if ($file_name === 'api_url.js') {
                    continue;
                }
                $handle = 'flyerimage-extra-' . str_replace('.', '_', $file_name) . time();
                $scripts[$handle] = [
                    'src'       => FLYER_IMAGE_PUBLIC_URL . '/scripts/' . $file_name,
                    'version'   => filemtime($file_path),
                    'deps'      => [],
                    'in_footer' => true
                ];
            }
        }
        // Register and enqueue the auxiliary scripts
        foreach ($scripts as $handle => &$script) {
            $deps = isset($script['deps']) ? $script['deps'] : false;
            $in_footer = isset($script['in_footer']) ? $script['in_footer'] : false;
            $script["registered"] = wp_register_script(
                $handle,
                $script['src'],
                $deps,
                $script['version'],
                $in_footer
            ) ? 1 : 0;
            wp_enqueue_script($handle);
        }
        $styles = [];
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/flyer-image-web/*.css' );
        if (count($files) > 0){
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                $styles[str_replace(".", "_", $file_name).time()] = [
                    'src'     => FLYER_IMAGE_PUBLIC_URL . '/flyer-image-web/' . $file_name,
                    'version' => filemtime($file_path)
                ];
            }
        }
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/static/*.css' );
        if (count($files) > 0){
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                $styles[str_replace(".", "_", $file_name).time()] = [
                    'src'     => FLYER_IMAGE_PUBLIC_URL . '/static/' . $file_name,
                    'version' => filemtime($file_path)
                ];
            }
        }
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/scripts/*.css' );
        if (count($files) > 0){
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                $styles[str_replace(".", "_", $file_name).time()] = [
                    'src'     => FLYER_IMAGE_PUBLIC_URL . '/scripts/' . $file_name,
                    'version' => filemtime($file_path)
                ];
            }
        }
        foreach ($styles as $handle => &$style) {
            $deps = isset($style['deps']) ? $style['deps'] : false;
            wp_register_style(
                $handle,
                $style['src'],
                $deps,
                $style['version']
            );
            wp_enqueue_style($handle);
        }

        // Localize only the main app bundle if present
        if ( $main_handle ) {
            $script_name = isset($_SERVER['SCRIPT_NAME']) ? sanitize_text_field( wp_unslash( $_SERVER['SCRIPT_NAME'] ) ) : '';
            $wpapi_data = array(
                'apiUrl'       => esc_url_raw( rest_url( FLYER_IMAGE_WP_PLUGIN_API_BASE_V252202251 ) ),
                'siteUrl'      => esc_url_raw( get_site_url() ),
                'pluginUrl'    => esc_url_raw( FLYER_IMAGE_URL ),
                'adminPageUrl' => esc_url_raw( FLYER_IMAGE_ADMIN_BASE_URL ),
                'scriptName'   => $script_name,
                'nonce'        => wp_create_nonce('wp_rest'),
            );
            wp_localize_script( $main_handle, 'FLYERI_WPAPI', $wpapi_data );
            // Expose quick-access window variables before the bundle executes
            wp_add_inline_script( $main_handle,
                'if(typeof FLYERI_WPAPI!=="undefined"){window.FLYER_IMAGE_API_URL=FLYERI_WPAPI.apiUrl;window.FLYER_IMAGE_SITE_URL=FLYERI_WPAPI.siteUrl;window.FLYER_IMAGE_PLUGIN_URL=FLYERI_WPAPI.pluginUrl;window.FLYER_IMAGE_ADMIN_PAGE_URL=FLYERI_WPAPI.adminPageUrl;window.FLYER_IMAGE_SCRIPT_NAME=FLYERI_WPAPI.scriptName;}',
                'before'
            );
        }
    }

    /**
     * Reqister web the assets
     *
     * @return void
     */
    public function enqueue_web_assets() {
       $scripts = [];
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/scripts/*.js' );
        if (count($files) > 0){
            $hasFlyer = false;
            foreach ($files as $file) {
                if (basename($file) === 'flyer.js') {
                    $hasFlyer = true;
                    break;
                }
            }
            if ($hasFlyer) {
                $files = array_filter($files, function ($file) {
                    return basename($file) !== 'flyermf.js';
                });
            }
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                $scripts[str_replace(".", "_", $file_name).time()] = [
                    'src'       => FLYER_IMAGE_PUBLIC_URL . '/scripts/' . $file_name,
                    'version'   => filemtime($file_path),
                    'deps'      => [ 'jquery' ],
                    'in_footer' => true
                ];
            }
        }
        foreach ($scripts as $handle => &$script) {
            $deps = isset($script['deps']) ? $script['deps'] : false;
            $in_footer = isset($script['in_footer']) ? $script['in_footer'] : false;
            $script["registered"] = wp_register_script(
                $handle,
                $script['src'],
                $deps,
                $script['version'],
                $in_footer
            ) ? 1 : 0;
            wp_enqueue_script($handle);
            wp_localize_script($handle, 'FlyerImage', [
                'apiBase' => rest_url('flyer_image_v9622105412/v1'),
            ]);
            if ($this->frontend_primary_handle === null) {
                $this->frontend_primary_handle = $handle;
            }
        }

        $styles = [];
        $files = glob( FLYER_IMAGE_PUBLIC_PATH . '/scripts/*.css' );
        if (count($files) > 0){
            foreach ($files as $file_path) {
                $file_name = basename($file_path);
                $styles[str_replace(".", "_", $file_name).time()] = [
                    'src'     => FLYER_IMAGE_PUBLIC_URL . '/scripts/' . $file_name,
                    'version' => filemtime($file_path)
                ];
            }
        }
        foreach ($styles as $handle => &$style) {
            $deps = isset($style['deps']) ? $style['deps'] : false;
            wp_register_style(
                $handle,
                $style['src'],
                $deps,
                $style['version']
            );
            wp_enqueue_style($handle);
        }
    }

    public function wp_footer_frontend() {
        $post = get_post();
        $post_id = empty( $post ) ? "" : $post->ID;
        $categories = wp_get_post_terms($post_id, 'category');
        $cat_ids = [];
        foreach ($categories as $c) {
            $cat_ids[] = (int) $c->term_id;
        }
        $cat_string = implode(',', $cat_ids);

        // Determine handle to attach inline data
        $target_handle = $this->frontend_primary_handle ?: 'jquery';
        if ($target_handle === 'jquery') {
            wp_enqueue_script('jquery');
        }
        $inline = 'window.FLYER_IMAGE_VISITING_POST_ID=' . (int) $post_id . ';' .
                  'window.FLYER_IMAGE_VISITING_CATEGORY_ID="' . \esc_js($cat_string) . '";';
        wp_add_inline_script($target_handle, $inline, 'before');
    }
}
