<?php
defined('ABSPATH') || exit;

class Termin_Kalender_Manager
{
    private static $instance;
    private $rendered_components = [];
    private static $global_block_instance_counter = 0;

    private function __construct()
    {
    }

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

    public function get_next_block_instance_id()
    {
        return ++self::$global_block_instance_counter;
    }

    public function has_been_rendered($component_name)
    {
        return isset($this->rendered_components[$component_name]);
    }

    public function mark_as_rendered($component_name)
    {
        $this->rendered_components[$component_name] = true;
    }

    /**
     * ZENTRALE FRONTEND-DATEN INJEKTION
     * Registriert ein dummy script und hängt den großen Payload `terminKalenderData`
     * exakt einmal an. Alle Frontend-Module rufen diese Funktion auf statt 
     * eigene `wp_localize_script` aufzurufen.
     */
    public function enqueue_frontend_data()
    {
        if (!wp_script_is('termin_kalender_data_injector', 'enqueued')) {
            wp_register_script('termin_kalender_data_injector', false, [], Termin_Kalender_Plugin::TER_KAL_TK_VERSION, true);
            wp_enqueue_script('termin_kalender_data_injector');

            $data = $this->get_termin_kalender_data();
            wp_localize_script('termin_kalender_data_injector', 'terminKalenderData', $data);
        }
    }

    private $cached_data = null;

    public function get_termin_kalender_data($is_backend = null)
    {
        if ($this->cached_data !== null) {
            return $this->cached_data; // Zweiter Aufruf kostet nichts
        }

        // Automatischer Kontext-Check, falls nichts explizit übergeben wurde
        if ($is_backend === null) {
            $is_backend = is_admin();
        }

        try {
            $dev_mode = defined('TER_KAL_DEV_MODE_ON') ? 'on' : 'off';
            $ter_kal_pro_mode = defined('TERMIN_KALENDER_PRO_ON') ? 'on' : 'off';
            $pro_plugin_url = $ter_kal_pro_mode === 'on' ? Termin_Kalender_PRO_Plugin::$plugin_url : '';

            $kalenderdaten = [];
            $dashicons = [];
            $templates = [];
            $options = get_option('termin_kalender_options', []);

            if ($is_backend) {
                // BACKEND ONLY: Keine Event-Daten laden (werden nicht im DOM gebraucht, Reduziert Serverlast massiv).
                // Dafür Dashicons und Templates laden für Gutenberg Sidebar und Admin Menü.
                $dashicons = $this->get_dashicons();
                $templates = $options['termin_kalender_templates'] ?? [];
            } else {
                // FRONTEND ONLY: Nur die Event-Daten laden. Wir sparen uns hunderte Dashicons und Templates.
                if (class_exists('Termin_Kalender_Event_Repository')) {
                    $kalenderdaten = Termin_Kalender_Event_Repository::get_events();
                } else {
                    $kalenderdaten = json_decode(get_option('termin_kalender_events', '[]'), true);
                }

                if (!is_array($kalenderdaten)) {
                    $kalenderdaten = [];
                }

                $filtered_daten = [];
                foreach ($kalenderdaten as $event) {
                    $event_id = $event['id'] ?? '';
                    $skip = false;
                    
                    if (is_string($event_id)) {
                        foreach (['todo-', 'teammessage-'] as $prefix) {
                            if (str_starts_with($event_id, $prefix)) {
                                $skip = true;
                                break;
                            }
                        }
                    }
                    
                    if ($skip) {
                        continue;
                    }

                    // Entferne private Notizen aus dem Array für die Frontend-Ausgabe
                    if (isset($event['extendedProps']['notes'])) {
                        unset($event['extendedProps']['notes']);
                    }

                    $filtered_daten[] = $event;
                }
                $kalenderdaten = $filtered_daten;
            }

            // Kategorien werden weiterhin global geladen (für PRO JS Fallbacks)
            $categories = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
            $user_language = get_user_locale() ?: get_locale() ?: 'en';
            $ter_kal_lang = substr($user_language, 0, 2);

            $calendar_admin_link = admin_url('admin.php?page=termin-kalender');
            $todo_admin_link = admin_url('admin.php?page=termin_kalender_team_tools&tab=todo');
            $admin_link = admin_url('admin.php?page=termin-kalender');

            $show_welcome = false;
            // Only show welcome screen on backend, if not seen yet
            if ($is_backend && empty($options['tk_welcome_screen_seen'])) {
                $show_welcome = true;
            }

            $terminKalenderData = [
                'termin_kalender_edit' => current_user_can('termin_kalender_edit'),
                'termin_kalender_delete' => current_user_can('termin_kalender_delete'),
                'TER_KAL_DEV_MODE_ON' => $dev_mode,
                'TERMIN_KALENDER_PRO_ON' => $ter_kal_pro_mode,
                'TERMIN_KALENDER_DATEN' => $kalenderdaten,
                'TERMIN_KALENDER_KATEGORIEN' => $categories,
                'TERMIN_KALENDER_ICONS' => $dashicons,
                'TERMIN_KALENDER_TEMPLATES' => $templates,
                'calendar_admin_link' => $calendar_admin_link,
                'todo_admin_link' => $todo_admin_link,
                'admin_link' => $admin_link,
                'ajax_url' => Termin_Kalender_Plugin::$ajax_url,
                'nonce' => wp_create_nonce('termin_kalender_nonce'),
                'TER_KAL_PLUGIN_URL' => Termin_Kalender_Plugin::$plugin_url,
                'TER_KAL_PRO_PLUGIN_URL' => $pro_plugin_url,
                'ter_kal_lang' => $ter_kal_lang,
                'is_user_logged_in' => is_user_logged_in() ? '1' : '0',
                'close_calendar_link' => esc_url(home_url()),
                'calendar_login_link' => esc_url(wp_login_url()),
                'strings' => $this->get_translated_strings(),
                'rest_nonce' => wp_create_nonce('wp_rest'),
                'rest_url' => esc_url_raw(rest_url('termin-kalender/v1/')),
                'show_welcome_screen' => $show_welcome,
            ];

            $this->cached_data = $terminKalenderData;
            return $this->cached_data;
        } catch (Exception $e) {
            if (defined('TER_KAL_DEV_MODE_ON')) {
                // echo "<script>console.log( 'Error loading enqueue Data: ' . $e->getMessage() );</script>";
            }
            return [];
        }
    }

    private function get_dashicons()
    {
        $dashicons = get_option('termin_kalender_dashicons', []);
        if (empty($dashicons)) {
            $dashicons = termin_kalender_get_dashicons_list();
            update_option('termin_kalender_dashicons', $dashicons);
        }

        return $dashicons;
    }

    private function get_translated_strings()
    {
        return [
            'event_title' => __('New Appointment', 'termin-kalender'),
            'start_date' => __('Start Date', 'termin-kalender'),
            'end_date' => __('End Date', 'termin-kalender'),
            'details' => __('Details', 'termin-kalender'),
            'notes' => __('Notes', 'termin-kalender'),
            'help' => __('Help', 'termin-kalender'),
            'category' => __('Category', 'termin-kalender'),
            'new_category' => __('New Category', 'termin-kalender'),
            'save_event' => __('Save Appointment', 'termin-kalender'),
            'save_category' => __('Save Category', 'termin-kalender'),
            'delete_category' => __('Delete Category', 'termin-kalender'),
            'confirm_delete_category' => __('Are you sure you want to delete this category?', 'termin-kalender'),
            'error_saving_event' => __('Error saving Appointment', 'termin-kalender'),
            'error_saving_category' => __('Error saving category', 'termin-kalender'),
            'error_fetching_events' => __('There was an error while fetching events!', 'termin-kalender'),
            'copy_event' => __('Copy Appointment', 'termin-kalender'),
            'error_copying_event' => __('Error copying Appointment.', 'termin-kalender'),
            'delete_event' => __('Delete Appointment', 'termin-kalender'),
            'confirm_delete_event' => __('Delete this Appointment? If recurring, all entries in this series will be permanently removed.', 'termin-kalender'),
            'error_deleting_event' => __('Error deleting Appointment.', 'termin-kalender'),
            'error_deleting_category' => __('Error deleting category', 'termin-kalender'),
            'cancel' => __('Cancel', 'termin-kalender'),
            'close' => __('Close', 'termin-kalender'),
            'event_location' => __('Location: ', 'termin-kalender'),
            'WEEKLY' => __('Weekly ', 'termin-kalender'),
            'MONTHLY' => __('Monthly ', 'termin-kalender'),
            'YEARLY' => __('Annual ', 'termin-kalender'),
            'edit_calendar' => __('Edit Calendar ', 'termin-kalender'),
            'add_todo' => __('To-Do ', 'termin-kalender'),
            'calendar_login' => __('Log in to edit', 'termin-kalender'),
            'read_more' => __('Show More', 'termin-kalender'),
            'description' => __('Description', 'termin-kalender'),
            'location' => __('Location', 'termin-kalender'),
            'organizer' => __('Organizer', 'termin-kalender'),
            'attendees' => __('Attendees', 'termin-kalender'),
            'categories' => __('Categories', 'termin-kalender'),
            'status' => __('Status', 'termin-kalender'),
            'priority' => __('Priority', 'termin-kalender'),
            'recurrence' => __('Recurrence', 'termin-kalender'),
            'alarms' => __('Alarms', 'termin-kalender'),
            'no_data_found' => __('No future appointments found', 'termin-kalender'),
            'invalid_date' => __('Invalid date format. Please use YYYY-MM-DD.', 'termin-kalender'),
            'click_remove' => __('Click to remove', 'termin-kalender'),
            'all_day' => __('All day', 'termin-kalender'),
            'show_preview' => __('Show Preview', 'termin-kalender'),
            'hide_preview' => __('Hide Preview', 'termin-kalender'),
            'copy' => __('Copy', 'termin-kalender'),
            'copied' => __('Copied to clipboard!', 'termin-kalender'),
            'share' => __('Share', 'termin-kalender'),
            'share_options' => __('Share Options', 'termin-kalender'),
            'add_to_calendar' => __('Add to calendar', 'termin-kalender'),
            'more' => __('More', 'termin-kalender'),
            'until' => __('until', 'termin-kalender'),
            'edit' => __('Edit', 'termin-kalender'),
        ];

        return apply_filters('termin_kalender_frontend_strings', $strings);
    }

}