<?php
namespace UniversalDAM;

class Plugin {
    private static $instance = null;
    public $client = null;

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        error_log( '[DAM] Plugin constructor called' );
        $this->init_hooks();
        $this->load_dependencies();
        error_log( '[DAM] Plugin initialization complete' );
    }

    private function init_hooks() {
        add_action('plugins_loaded', [$this, 'load_textdomain']);
        add_action('init', [$this, 'init']);
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        
        register_activation_hook(DAM_PLUGIN_FILE, [$this, 'activate']);
        register_deactivation_hook(DAM_PLUGIN_FILE, [$this, 'deactivate']);
    }

    private function load_dependencies() {
        require_once DAM_PLUGIN_DIR . 'includes/class-dam-client.php';
        $this->client = new DAM_Client();

        // Register REST API routes - REST must be initialized before we can register routes
        // Hook directly into rest_api_init with priority 0 to ensure we run during the action
        add_action('rest_api_init', [$this, 'init_rest_api'], 0);

        require_once DAM_PLUGIN_DIR . 'includes/class-dam-gutenberg.php';
        new DAM_Gutenberg($this->client);

        if (defined('YOOTHEME_VERSION')) {
            require_once DAM_PLUGIN_DIR . 'integrations/class-dam-yootheme.php';
            new DAM_YooTheme($this->client);
        }

        // Load ACF integration after ACF is ready
        add_action(
            'acf/init',
            function () {
                require_once DAM_PLUGIN_DIR . 'integrations/class-dam-acf.php';
                new DAM_ACF( $this->client );
            }
        );

        require_once DAM_PLUGIN_DIR . 'includes/class-dam-usage.php';
        new DAM_Usage($this->client);

        // Load media interceptor to route WP uploads through DAM
        require_once DAM_PLUGIN_DIR . 'includes/class-dam-media-interceptor.php';
        new DAM_Media_Interceptor($this->client);
    }

    public function init() {
        do_action('dam_init');
    }

    public function init_rest_api() {
        // Only initialize REST API once
        static $initialized = false;
        if ($initialized) {
            error_log('[DAM REST] Skipping duplicate init_rest_api call');
            return;
        }
        $initialized = true;

        require_once DAM_PLUGIN_DIR . 'includes/class-dam-rest.php';
        new DAM_REST($this->client);
    }

    public function load_textdomain() {
        load_plugin_textdomain('universal-dam', false, dirname(plugin_basename(DAM_PLUGIN_FILE)) . '/languages');
    }

    public function add_admin_menu() {
        add_menu_page(
            __('DAM Assets', 'universal-dam'),
            __('DAM Assets', 'universal-dam'),
            'upload_files',
            'dam-assets',
            [$this, 'render_admin_app'],
            'dashicons-images-alt2',
            20
        );

        add_submenu_page(
            'dam-assets',
            __('Settings', 'universal-dam'),
            __('Settings', 'universal-dam'),
            'manage_options',
            'dam-settings',
            [$this, 'render_settings_page']
        );
    }

    public function render_admin_app() {
        echo '<div id="dam-admin-app"></div>';
    }

    public function render_settings_page() {
        require_once DAM_PLUGIN_DIR . 'admin/settings.php';
    }

    public function enqueue_admin_assets($hook) {
        // Hook should be 'toplevel_page_dam-assets' or 'dam-assets_page_dam-settings'
        if (strpos($hook, 'dam') === false) {
            return;
        }

        // Only use Vite dev server if explicitly enabled via constant
        // Set DAM_VITE_DEV to true in wp-config.php when developing locally
        $is_dev = defined('DAM_VITE_DEV') && DAM_VITE_DEV;

        if ($is_dev) {
            wp_enqueue_script(
                'dam-vite-client',
                'http://localhost:5173/@vite/client',
                [],
                null,
                true
            );
            wp_add_inline_script('dam-vite-client', 'window.process = { env: { NODE_ENV: "development" } }', 'before');

            wp_enqueue_script(
                'dam-admin-app',
                'http://localhost:5173/src/main.ts',
                ['dam-vite-client'],
                null,
                true
            );
        } else {
            $manifest = $this->get_vite_manifest();
            if ($manifest && isset($manifest['src/main.ts'])) {
                $entry = $manifest['src/main.ts'];

                wp_enqueue_script(
                    'dam-admin-app',
                    DAM_PLUGIN_URL . 'assets/' . $entry['file'],
                    [],
                    DAM_VERSION,
                    true
                );

                if (isset($entry['css'])) {
                    foreach ($entry['css'] as $css_file) {
                        wp_enqueue_style(
                            'dam-admin-css',
                            DAM_PLUGIN_URL . 'assets/' . $css_file,
                            [],
                            DAM_VERSION
                        );
                    }
                }
            } else {
                // Log error if manifest is missing
                error_log('Universal DAM: Vite manifest not found or missing entry. Path: ' . DAM_PLUGIN_DIR . 'assets/.vite/manifest.json');
            }
        }

        wp_localize_script('dam-admin-app', 'damConfig', [
            'apiUrl' => rest_url('dam/v1'),
            'nonce' => wp_create_nonce('wp_rest'),
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'pluginUrl' => DAM_PLUGIN_URL,
            'settings' => $this->get_settings(),
        ]);

        // Add debug output before the main script runs
        wp_add_inline_script(
            'dam-admin-app',
            'console.log("[DAM PHP] damConfig set:", typeof window.damConfig !== "undefined");',
            'before'
        );
    }

    private function get_vite_manifest() {
        $manifest_path = DAM_PLUGIN_DIR . 'assets/.vite/manifest.json';
        if (!file_exists($manifest_path)) {
            return null;
        }
        return json_decode(file_get_contents($manifest_path), true);
    }

    public function get_settings() {
        return get_option('dam_settings', [
            'api_url' => '',
            'api_key' => '',
            'cdn_url' => '',
        ]);
    }

    public function activate() {
        if (!get_option('dam_settings')) {
            add_option('dam_settings', [
                'api_url' => '',
                'api_key' => '',
                'cdn_url' => '',
            ]);
        }

        $upload_dir = wp_upload_dir();
        $dam_dir = $upload_dir['basedir'] . '/dam-cache';
        if (!file_exists($dam_dir)) {
            wp_mkdir_p($dam_dir);
        }

        flush_rewrite_rules();
    }

    public function deactivate() {
        flush_rewrite_rules();
    }
}
