<?php

namespace HvnlyNab\Admin;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

final class Assets
{
    public function __construct()
    {
        add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_scripts_callback']);
        add_action('admin_init', [$this, 'register_cache_settings']);
    }

    /**
     * Register cache settings
     */
    public function register_cache_settings(): void
    {
        register_setting(
            'hvnly_cache_settings',
            'hvnly_cache_enabled',
            [
                'sanitize_callback' => 'absint',
            ]
        );

        register_setting(
            'hvnly_cache_settings',
            'hvnly_cache_ttl',
            [
                'sanitize_callback' => 'absint',
            ]
        );

        register_setting(
            'hvnly_cache_settings',
            'hvnly_cache_compression',
            [
                'sanitize_callback' => 'sanitize_text_field',
            ]
        );

        register_setting(
            'hvnly_cache_settings',
            'hvnly_cache_debug',
            [
                'sanitize_callback' => 'absint',
            ]
        );
    }

    /**
     * Enqueue JS/CSS only on specific admin pages
     */
    public function admin_enqueue_scripts_callback($hook_suffix)
    {
        $allowed_pages = [
            'hvnly_property_page_hvnly_property_settings',
            'hvnly_property_page_hvnly_property_builder',
            // 'hvnly_property_page_hvnly_property_reports_analytics',
            'hvnly_property_page_hvnly_property_cache',
            'hvnly_property_page_hvnly-property-setup',
        ];

        $default_version = defined('HVNLYNAB_VERSION') ? HVNLYNAB_VERSION : '1.0.0';

        wp_enqueue_style(
            'hvnly-admin-fontawesome-all',
            HVNLYNAB_ASSETS_URL . '/admin/css/fontawesome-all.min.css',
            [],
            $default_version
        );

        if ($hook_suffix === 'hvnly_property_page_hvnly-property-setup') {
            $this->enqueue_setup_assets($default_version);
            return;
        }

        if ($hook_suffix === 'hvnly_property_page_hvnly_property_cache') {
            $this->enqueue_cache_assets($default_version);
            $this->enqueue_sticky_sidebar();
            return;
        }

        if (!in_array($hook_suffix, $allowed_pages, true)) {
            return;
        }

        $pages = [
            'hvnly_property_page_hvnly_property_settings' => [
                'handle'   => 'hvlynab-settings-admin',
                'folder'   => 'settings',
                'asset'    => 'settings.asset.php',
                'script'   => 'settings.js',
                'style'    => 'settings.css',
                'localize' => true,
            ],
            'hvnly_property_page_hvnly_property_builder' => [
                'handle'   => 'hvlynab-builder-admin',
                'folder'   => 'builder',
                'asset'    => 'builder.asset.php',
                'script'   => 'builder.js',
                'style'    => 'builder.css',
                'localize' => true,
            ],
            // 'hvnly_property_page_hvnly_property_reports_analytics' => [
            //     'handle'   => 'hvlynab-reports-admin',
            //     'folder'   => 'reports',
            //     'asset'    => 'reports.asset.php',
            //     'script'   => 'reports.js',
            //     'style'    => 'reports.css',
            //     'localize' => true,
            // ],
        ];

        if (isset($pages[$hook_suffix])) {
            $page = $pages[$hook_suffix];
            $this->enqueue_page_assets($page, $default_version);
        }

        $this->enqueue_sticky_sidebar();
    }

    private function enqueue_setup_assets($version): void
    {
        wp_enqueue_style(
            'hvnly-setup-wizard',
            HVNLYNAB_ASSETS_URL . '/admin/css/hvnly-setup-wizard.css',
            [],
            $version
        );

        wp_enqueue_script(
            'hvnly-setup-wizard',
            HVNLYNAB_ASSETS_URL . '/admin/js/hvnly-setup-wizard.js',
            ['jquery', 'wp-util'],
            $version,
            true
        );

        $tab_structure = \HvnlyNab\Admin\Data\TabData::hvnly_metabox_tabs_builder();
        $field_names = $this->extract_field_names($tab_structure);

        wp_localize_script('hvnly-setup-wizard', 'hvnlysetupWizard', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvnly_setup_nonce'),
            'setuped' => get_option('hvnly_demo_properties_setuped', false),
            'setupCount' => get_option('hvnly_demo_properties_count', 0),
            'totalProperties' => wp_count_posts('hvnly_property')->publish ?? 0,
            'strings' => [
                'confirmsetup' => __('Are you sure you want to setup demo properties? This will create sample listings with realistic data.', 'havenlytics'),
                'setuping' => __('setuping properties...', 'havenlytics'),
                'complete' => __('setup complete!', 'havenlytics'),
                'error' => __('An error occurred during setup.', 'havenlytics'),
                'viewProperties' => __('View Properties', 'havenlytics'),
                'setupMore' => __('setup More', 'havenlytics'),
            ],
        ]);
    }

    private function extract_field_names($tabs) {
        $fields = [];
        foreach ($tabs as $tab) {
            if (isset($tab['fields']) && is_array($tab['fields'])) {
                foreach ($tab['fields'] as $field) {
                    if (isset($field['name'])) {
                        $fields[] = $field['name'];
                    }
                }
            }
        }
        return $fields;
    }

    private function enqueue_cache_assets($version): void
    {
        $css_file = HVNLYNAB_ASSETS_URL . '/admin/css/hvnly-admin-cache.css';
        if (file_exists(str_replace(HVNLYNAB_URL, HVNLYNAB_PATH, $css_file))) {
            wp_enqueue_style(
                'hvnly-admin-cache',
                $css_file,
                [],
                $version
            );
        }

        $js_file = HVNLYNAB_ASSETS_URL . '/admin/js/hvnly-admin-cache.js';
        if (file_exists(str_replace(HVNLYNAB_URL, HVNLYNAB_PATH, $js_file))) {
            wp_enqueue_script(
                'hvnly-admin-cache',
                $js_file,
                ['jquery', 'wp-util'],
                $version,
                true
            );

            wp_localize_script('hvnly-admin-cache', 'hvnlyCacheAdmin', [
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvnly_cache_nonce'),
                'clearingText' => __('Clearing cache...', 'havenlytics'),
                'clearedText' => __('Cache cleared successfully!', 'havenlytics'),
                'errorText' => __('Error clearing cache', 'havenlytics')
            ]);
        }
    }

    private function enqueue_page_assets($page, $version): void
    {
        $asset_file = HVNLYNAB_BUILD_PATH . '/' . $page['folder'] . '/' . $page['asset'];
        
        if (!file_exists($asset_file)) {
            // Debug code removed for production - asset file missing silently ignored
            return;
        }

        $main_asset = require $asset_file;

        $js_file = HVNLYNAB_BUILD_URL . '/' . $page['folder'] . '/' . $page['script'];
        wp_enqueue_script(
            $page['handle'],
            $js_file,
            $main_asset['dependencies'] ?? [],
            $main_asset['version'] ?? $version,
            true
        );

        $css_file = HVNLYNAB_BUILD_PATH . '/' . $page['folder'] . '/' . $page['style'];
        if (file_exists($css_file)) {
            wp_enqueue_style(
                $page['handle'],
                HVNLYNAB_BUILD_URL . '/' . $page['folder'] . '/' . $page['style'],
                [],
                $main_asset['version'] ?? $version
            );
        }

        if (!empty($page['localize'])) {
            $current_user = wp_get_current_user();

            wp_localize_script(
                $page['handle'],
                'HavenlyticsData',
                [
                    'hvnlyNabApi' => [
                        'url' => esc_url_raw(rest_url('hvnlynab/v1')),
                        'nonce' => wp_create_nonce('wp_rest')
                    ],
                    'ajax' => [
                        'url' => admin_url('admin-ajax.php'),
                        'nonce' => wp_create_nonce('hvnlyNab_ajax')
                    ],
                    'user' => [
                        'id' => $current_user->ID,
                        'name' => $current_user->display_name,
                        'email' => $current_user->user_email,
                        'caps' => array_keys(array_filter($current_user->allcaps)),
                        'avatar' => get_avatar_url($current_user->ID, ['size' => 36])
                    ],
                    'urls' => [
                        'admin' => admin_url(),
                        'site' => home_url(),
                        'assets' => HVNLYNAB_ASSETS_URL . '/'
                    ],
                    'settings' => [
                        'date_format' => get_option('date_format'),
                        'time_format' => get_option('time_format')
                    ]
                ]
            );
        }
    }

    private function enqueue_sticky_sidebar(): void
    {
        wp_add_inline_style('admin-bar', '
            #adminmenuwrap.hvnly-menu-fixed {
                position: fixed !setupant;
                top: 0;
                left: 0;
                z-index: 9990;
                transition: all 0.3s ease;
            }
        ');

        wp_add_inline_script('jquery-core', "
            jQuery(document).ready(function($) {
                const adminMenuWrap = $('#adminmenuwrap');
                const isHavenlyticsPage = window.location.search.includes('post_type=hvnly_property') || 
                                          window.location.href.includes('page=hvnly');

                if (isHavenlyticsPage && adminMenuWrap.length) {
                    $(window).on('scroll', function() {
                        const scrollTop = $(window).scrollTop();
                        if (scrollTop > 32) {
                            if (!adminMenuWrap.hasClass('hvnly-menu-fixed')) {
                                adminMenuWrap.addClass('hvnly-menu-fixed');
                            }
                        } else {
                            adminMenuWrap.removeClass('hvnly-menu-fixed');
                        }
                    });
                }
            });
        ");
    }
}