<?php

namespace MovieEngine\Admin;

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

class Admin {

    private $plugin_name;
    private $version;

    public function __construct() {
        $this->plugin_name = 'movie-engine-admin';
        $this->version     = MOVIE_ENGINE_VERSION;

        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('admin_head', [$this, 'silence_jquery_migrate']);
        add_action('admin_init', [$this, 'setup_required_pages']);
        add_action('wp_ajax_movie_engine_purge_cache', [$this, 'ajax_purge_cache']);

        // Initialize Import/Export Handler
        require_once MOVIE_ENGINE_PATH . 'includes/Admin/ImportExport/ImportExportHandler.php';
        new \MovieEngine\Admin\ImportExport\ImportExportHandler();

        // Initialize Theme Installer AJAX
        require_once MOVIE_ENGINE_PATH . 'includes/Admin/Ajax/ThemeInstaller.php';
        new \MovieEngine\Admin\Ajax\ThemeInstaller();
    }

    public function silence_jquery_migrate() {
        echo '<script type="text/javascript">window.jQuery && (window.jQuery.migrateMute = true);</script>';
    }

    /**
     * AJAX handler to purge all cache
     */
    public function ajax_purge_cache() {
        check_ajax_referer('movie_engine_purge_cache', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'cine-movie-engine')]);
        }

        \MovieEngine\Core\Cache::purge_all();

        \MovieEngine\Core\Cache::update_custom_css();

        wp_send_json_success(['message' => esc_html__('Cache purged successfully!', 'cine-movie-engine')]);
    }

    /**
     * Ensure all required pages are created (one-time check)
     */
    public function setup_required_pages() {
        if (!current_user_can('manage_options') || get_option('movie_engine_page_cleanup_v1')) {
            return;
        }

        \MovieEngine\Core\PageSetup::create_pages();
        update_option('movie_engine_page_cleanup_v1', time());
    }

    public function enqueue_styles() {
        wp_enqueue_style('font-awesome', MOVIE_ENGINE_URL . 'assets/fonts/fontawesome.min.css', [], $this->version);
        wp_enqueue_style($this->plugin_name, MOVIE_ENGINE_URL . 'assets/css/admin/movie-engine-admin.min.css', array('font-awesome'), $this->version, 'all');
    }

    public function enqueue_scripts() {
        wp_enqueue_script('chart-js', MOVIE_ENGINE_URL . 'assets/js/vendor/chart.umd.js', [], '4.4.1', true);
        wp_enqueue_script($this->plugin_name, MOVIE_ENGINE_URL . 'assets/js/admin/movie-engine-admin.min.js', array('jquery', 'chart-js'), $this->version, true);
        wp_localize_script($this->plugin_name, 'movieEngineAdmin', apply_filters('movie_engine_admin_data', array(
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'nonce'    => wp_create_nonce('movie-engine-admin-nonce'),
            'tmdb_nonce' => wp_create_nonce('movie_engine_tmdb_search'),
            'tmdb_import_nonce' => wp_create_nonce('movie_engine_tmdb_import'),
            'email_nonce' => wp_create_nonce('movie_engine_email_nonce'),
            'i18n'  => [
                'enter_search_term' => esc_html__('Please enter a search term', 'cine-movie-engine'),
                'searching' => esc_html__('Searching...', 'cine-movie-engine'),
                'no_results' => esc_html__('No results found.', 'cine-movie-engine'),
                'search_failed' => esc_html__('Search failed. Please try again.', 'cine-movie-engine'),
                'import' => esc_html__('Import', 'cine-movie-engine'),
                'importing' => esc_html__('Importing...', 'cine-movie-engine'),
                'import_success' => esc_html__('Import successful! The page will reload.', 'cine-movie-engine'),
                'import_failed' => esc_html__('Import failed:', 'cine-movie-engine'),
                'import_failed_retry' => esc_html__('Import failed. Please try again.', 'cine-movie-engine'),
                'server_name_placeholder' => esc_html__('e.g. Server 1', 'cine-movie-engine'),
                'server_url_placeholder' => esc_html__('https://example.com/embed/{tmdb_id}', 'cine-movie-engine'),
                'template_hints' => sprintf(
                    /* translators: %1$s: list of available template tags */
                    esc_html__('Use %1$s', 'cine-movie-engine'),
                    '<code>{imdb_id}</code>, <code>{tmdb_id}</code>, <code>{season}</code>, <code>{episode}</code>'
                ),
                'all_content' => esc_html__('All Content', 'cine-movie-engine'),
                'movies_only' => esc_html__('Movies Only', 'cine-movie-engine'),
                'tv_only' => esc_html__('TV Only', 'cine-movie-engine'),
                'confirm_remove_server' => esc_html__('Are you sure you want to remove this server?', 'cine-movie-engine'),
                'confirm_update_status'   => esc_html__('Are you sure? This will update the status.', 'cine-movie-engine'),
                'prompt_rejection'        => esc_html__('Please provide a reason for rejection:', 'cine-movie-engine'),
                'action_not_supported'    => esc_html__('Action not supported yet.', 'cine-movie-engine'),
                'error_unknown'           => esc_html__('Unknown error occurred.', 'cine-movie-engine'),
            ]
        )));
        wp_enqueue_script('movie-engine-admin-preload', MOVIE_ENGINE_URL . 'assets/js/admin/theme-preload.min.js', array(), $this->version, false);
    }
}
