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

/**
 * Performs the cleanup and data migration for older versions.
 */
function termin_kalender_cleanup_old_versions()
{
    try {
        //----------------------------------------------------------
//throw new Exception( 'Forced test error' );  // test only
//----------------------------------------------------------
// correct wrongly generated i18n files which scramble shown language
/*$languages_dir = WP_CONTENT_DIR . '/languages/plugins/';
$plugin_slug = 'termin-kalender';
$bundled_locales = ['de', 'fr', 'en'];
// Patterns to match auto-generated files
$patterns = array(
    $languages_dir . $plugin_slug . '-*.json',
    $languages_dir . $plugin_slug . '-*.mo',
    $languages_dir . $plugin_slug . '-*.po',
    $languages_dir . $plugin_slug . '-*.php',
);
foreach ($patterns as $pattern) {
    $files = glob($pattern);
    if ($files) {
        foreach ($files as $file) {
            // Extract locale from filename (e.g., termin-kalender-de_DE.json -> de_DE)
            $filename = basename($file);
            if (preg_match('/' . preg_quote($plugin_slug) . '-([^-]+)\./', $filename, $matches)) {
                $locale = $matches[1];
                $locale_prefix = substr($locale, 0, 2);

                // Only delete files for bundled languages (de, fr, en and their variants)
                if (in_array($locale_prefix, $bundled_locales)) {
                    if (is_writable($file)) {
                        @unlink($file);
                    }
                }
            }
        }
    }
}*/

        //----------------------------------------------------------
        global $wpdb;
        // Cleanup old version options.
        delete_option('ter_kal_checkbox_values');
        delete_option('ter_kal_timed_event_duration');
        delete_option('ter_kal_termin_basisfelder');
        delete_option('ter_kal_dashicon_list');
        delete_option('ter_kal_dashicons');
        delete_option('ter_kal_lang');
        delete_option('ter_kal_selected_lable');
        delete_option('ter_kal_timed_event_duration');
        unregister_setting('ter_kal_options_group', 'ter_kal_benutzer');
        unregister_setting('ter_kal_kategorien_group', 'ter_kal_kategorien');
        remove_filter('allowed_options', 'ter_kal_allowed_options');
        remove_filter('whitelist_options', 'ter_kal_allowed_options');
        // Clean up old single options (legacy cleanup)
        delete_option('termin_kalender_version');
        delete_option('termin_kalender_first_run');
        //----------------------------------------------------------------------
        // nov 25 ------------------------------------------------------
        $options = get_option('termin_kalender_options', []);
        if (!isset($options['_migrated'])) {
            $old_keys = [
                'termin_kalender_feed_enabled',
                'termin_kalender_google_api_key',
                'termin_kalender_google_kalender_id',
                'termin_kalender_google_admin_calendar'
            ];
            foreach ($old_keys as $key) {
                $value = get_option($key);
                if ($value !== false) {
                    $options[$key] = $value;
                    //delete_option($key); in 1.2.2 pro
                    //'termin_kalender_version',
                    //'termin_kalender_first_run',
                    //'init_termin_kalender_update',
                    //'termin_kalender_rating_notice_dismissed',
                    //'termin_kalender_install_date',
                    //'termin_kalender_language',
                }
            }
            $options['_migrated'] = true;
            update_option('termin_kalender_options', $options);
        }
        //------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
/*
Nach dem update entfernen - vorher nur wenn sicher nicht mehr benötigt für update!
DB          ter_kal_termin_felder           Bei PRO update übernehmen und löschen
option      ter_kal_benutzer                Bei PRO update übernehmen und löschen
option      ter_kal_reservation_email       Bei PRO update übernehmen und löschen
option      ter_kal_event_list_category     ? prüfen
option      ter_kal_termin_zusatzfelder     Bei PRO update übernehmen und löschen
*/
        //-------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
// cleanup version 1.1x erkennbar an option ter_kal_formularfelder
// 	ter_kal_kategorie  ter_kal_kalender_daten
        if (get_option('ter_kal_formularfelder') !== false) {  // there is most probably a version 1.1

            $existing_kategorien = get_option('ter_kal_kategorie');
            $new_kategorien = [];
            if (defined('TER_KAL_DEV_MODE_ON')) {
                //error_log( 'Termin Kalender Cleanup: 1.1 detected, will update now.' );
            }
            if ($existing_kategorien) {
                foreach ($existing_kategorien as $entry) {
                    $new_kategorien[] = [
                        'categoryID' => (string) uniqid(),
                        'label' => $entry['label'],
                        'backgroundColor' => $entry['backgroundColor'],
                        'textColor' => $entry['textColor'],
                        'icon' => 'dashicons-' . $entry['icon'],
                    ];
                }
                update_option('termin_kalender_kategorien', json_encode($new_kategorien), false);
                delete_option('ter_kal_kategorie');
            }

            // Zusatzfelder mit einbeziehen: ------------------------------------------------
//$ter_kal_termin_zusatzfelder_option = get_option('ter_kal_termin_zusatzfelder');
//if (!empty($ter_kal_termin_zusatzfelder_option)) {
// 'feld_name' => 'list_image', 'feld_name' => 'zusatz_url'
//  Ort varchar(128), Teilnehmer varchar(128),  notiz_journal varchar(1024), list_image varchar(128),  zusatz_url varchar(128),
//}
//-------------------------------------------------------------------------------
            $existing_events = get_option('ter_kal_kalender_daten');
            if ($existing_events) {
                $new_events = [];
                $existing_kategorien = json_decode(get_option('termin_kalender_kategorien', '[]'), true);
                foreach ($existing_events as $event) {
                    if ($existing_kategorien) {
                        $matchingKategorie = array_filter(
                            $existing_kategorien,
                            function ($kategorie) use ($event) {
                                return isset($kategorie['label']) && $kategorie['label'] === $event['extendedProps']['Kategorie'];
                            }
                        );
                        $firstMatchIKategorie = reset($matchingKategorie);
                        $categoryID = isset($firstMatchIKategorie['categoryID']) ? $firstMatchIKategorie['categoryID'] : '';
                        $backgroundColor = isset($firstMatchIKategorie['backgroundColor']) ? $firstMatchIKategorie['backgroundColor'] : '';
                        $textColor = isset($firstMatchIKategorie['textColor']) ? $firstMatchIKategorie['textColor'] : '';
                    } else {
                        $Kategorie_name = 'New';
                        $icon = 'plus';
                        $backgroundColor = '#FF0000';
                        $textColor = '#FFFFFF';
                    }
                    if (defined('TER_KAL_DEV_MODE_ON')) {
                        //error_log( $event['extendedProps']['Kategorie'] );
                    }
                    ///----------------------------------------------------------------
/*$details_mit_zusatzfeld = $event['extendedProps']['Beschreibung'].' TEST: ';
if (!empty($ter_kal_termin_zusatzfelder_option)) {

    foreach ( $details_mit_zusatzfeld as $zusatzfeld ) {
        $zusatzfeld_key =  $zusatzfeld['feld_key'];
        $details_mit_zusatzfeld .=  '<hr>'. $event[$zusatzfeld_key]  ;
    }
}*/
                    ///----------------------------------------------------------------
                    $new_events[] = [
                        'id' => (string) $event['id'],
                        'title' => $event['title'],
                        'start' => $event['start'],
                        'end' => $event['end'],
                        'backgroundColor' => $backgroundColor,
                        'textColor' => $textColor,
                        'extendedProps' => [
                            'details' => $details_mit_zusatzfeld,
                            'notes' => esc_html(wp_strip_all_tags($event['extendedProps']['Notizen'])),
                            'category' => [
                                'categoryID' => $categoryID,
                                'backgroundColor' => $backgroundColor,
                                'textColor' => $textColor,
                                'label' => $event['extendedProps']['Kategorie'],
                                'icon' => 'dashicons-' . $event['extendedProps']['icon'],
                            ]
                        ]
                    ];
                }
                update_option('termin_kalender_events', json_encode($new_events), false);
                delete_option('ter_kal_kalender_daten');
            }
            delete_option('ter_kal_formularfelder'); // if all update done, we can delete formularfelder
            //update_option( 'termin_kalender_first_run', 'OK' );
            //---------------------
            if (defined('TER_KAL_DEV_MODE_ON')) {
                //error_log( 'Termin Kalender Cleanup: Update from 1.1 to 1.2 done.' );
                //echo "<script>console.log(  'Termin Kalender Cleanup: Update from 1.1 to 1.2 done.' );</script>";
            }
            return;    // All done
            //---------------------
        } else { // end cleanup version version 1.1
            if (defined('TER_KAL_DEV_MODE_ON')) {
                //error_log( 'Termin Kalender Cleanup: No version 1.1 found, looking for older versions.' );
            }
        }
        //--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
// 0.98    0.98.9.4 letzt 0.98 version
//   DB:  ter_kal_termin_felder  ter_kal_termin_kalender  ter_kal_termin_kategorien
// ter_kal_timed_event_duration  ter_kal_benutzer
// _transient_ter_kal_lang  _transient_ter_kal_dashicon_list  _transient_ter_kal_caching_plugins
//--------------------------------------------------------------------------------------------------------------------
// 0.99   DB ter_kal_termin_kategorien zu options migrieren !

        //   DB:  ter_kal_termin_felder  ter_kal_termin_kalender  ter_kal_termin_kategorien
// ter_kal_timed_event_duration
//--------------------------------------------------------------------------------------------------------------------
// 0.99.47 letzte 0.99 version, hat nur noch
//   DB:   ter_kal_termin_kalender
//--------------------------------------------------------------------------------------------------------------------
// 0.99.47 to 1.00.04 mit
//   DB:   ter_kal_termin_kalender
// ter_kal_termin_basisfelder  ter_kal_termin_zusatzfelder
// ter_kal_kategorien  ter_kal_dashicon_list
// _transient_ter_kal_plugin_ran _transient_ter_kal_caching_plugins _transient_ter_kal_lang
//--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
//  if table ter_kal_termin_felder still exist, transfer it to option ter_kal_termin_zusatzfelder
//  ter_kal_termin_zusatzfelder will be used to transfer zusatzfelder data from old table ter_kal_termin_kalender and can afterwards be deleted also
        $table_name = esc_sql($wpdb->prefix . 'ter_kal_termin_felder');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $table_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
        if ($table_exists && $table_count) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $db_data = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A);
            if (!empty($db_data)) {
                //  'feld_basis' => $item['feld_basis'] entfernt
                $options = array_filter(array_map(function ($item) {
                    return [
                        'feld_key' => $item['feld_key'],
                        'feld_name' => $item['feld_name'],
                        'feld_art' => $item['feld_art'],
                        'feld_zeigen' => $item['feld_zeigen']
                    ];
                }, $db_data), function ($item) {
                    return $item['feld_basis'] != 1;
                });
                foreach ($options as $option) {
                    $ter_kal_termin_zusatzfelder_option[$option['feld_key']] = $option;
                }
                update_option('ter_kal_termin_zusatzfelder', $ter_kal_termin_zusatzfelder_option);
            }
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DROP TABLE IF EXISTS $table_name");

            // Cleanup duplicate keys or names

            $option = get_option('ter_kal_termin_zusatzfelder');
            if (is_array($option)) {
                $unique_keys = [];
                $unique_names = [];
                foreach ($option as $key => $value) {
                    if (isset($value['feld_key']) && isset($value['feld_name'])) {
                        if (in_array($value['feld_key'], $unique_keys) || in_array($value['feld_name'], $unique_names)) {
                            unset($option[$key]);
                        } else {
                            $unique_keys[] = $value['feld_key'];
                            $unique_names[] = $value['feld_name'];
                        }
                    }
                }
                update_option('ter_kal_termin_zusatzfelder', $option);
            }
        }
        //--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
        $existing_kategorien = get_option('ter_kal_kategorien'); // option kategorien (mit kategorie_id ) war vor kategorie
        $new_kategorien = [];
        if (defined('TER_KAL_DEV_MODE_ON')) {
            //error_log( 'Termin Kalender Cleanup: vor version 1 detected, will update now.' );
        }
        if ($existing_kategorien) {
            foreach ($existing_kategorien as $entry) {
                $new_kategorien[] = [
                    'categoryID' => (string) $entry['kategorie_id'],
                    'label' => $entry['kategorie'],
                    'backgroundColor' => $entry['backgroundColor'],
                    'textColor' => $entry['textColor'],
                    'icon' => 'dashicons-' . $entry['icon'],
                ];
            }
            update_option('termin_kalender_kategorien', json_encode($new_kategorien), false);
            delete_option('ter_kal_kategorien');
        }
        //--------------------------------------------------------------------------------------------------------------------
// Wenn Kategorien DB ter_kal_termin_kategorien noch existiert, diese zuerst zu optionen migrieren:
        $old_table = $wpdb->prefix . 'ter_kal_termin_kategorien';
        $old_table_safe = esc_sql($old_table);
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$old_table_safe'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $count = $wpdb->get_var("SELECT COUNT(*) FROM $old_table_safe");
        if ($table_exists && $count) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $db_data = $wpdb->get_results("SELECT kategorie_id, kategorie, backgroundColor, textColor, icon FROM $old_table_safe", ARRAY_A);
            if (!empty($db_data)) {
                $options_array = array_map(function ($item) {
                    return [
                        'categoryID' => (string) $item['kategorie_id'],
                        'label' => $item['kategorie'],
                        'backgroundColor' => $item['backgroundColor'],
                        'textColor' => $item['textColor'],
                        'icon' => 'dashicons-' . $item['icon']
                    ];
                }, $db_data);

                if (!empty($options_array)) {
                    update_option('termin_kalender_kategorien', json_encode($options_array), false);
                }
            }
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DROP TABLE IF EXISTS $old_table_safe");
        }
        //--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
// Cleanup old version with database table ter_kal_termin_kalender, before 1.1.

        $old_table = $wpdb->prefix . 'ter_kal_termin_kalender';
        $old_table_safe = esc_sql($old_table);
        // Zusatzfelder mit einbeziehen: ------------------------------------------------
        $ter_kal_termin_zusatzfelder_option = get_option('ter_kal_termin_zusatzfelder');
        // Retrieve existing events from the old table.  eventuell alle felder holen
        $existing_events = [];
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$old_table_safe'");
        if ($table_exists) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $existing_events = $wpdb->get_results("SELECT * FROM $old_table_safe");  // erweitern alle felder
        }
        if (!empty($existing_events)) {
            // Backup existing calendar data.
            update_option('ter_kal_kalender_daten_backup', $existing_events);  // andere alte tabellen auch backup erstellen
            // Fetch and update category data.
            $existing_kategorien = json_decode(get_option('termin_kalender_kategorien', '[]'), true); // kategorien optionen sind bereits aktualisiert
            $new_events = [];
            foreach ($existing_events as $event) {
                if ($existing_kategorien) {
                    $matchingKategorie = array_filter(
                        $existing_kategorien,
                        function ($kategorie) use ($event) {
                            return isset($kategorie['categoryID']) && (string) $kategorie['categoryID'] == (string) $event->kategorie_id;
                        }
                    );
                    $firstMatchIKategorie = reset($matchingKategorie);
                    $categoryID = isset($firstMatchIKategorie['kategorie_id']) ? (string) $firstMatchIKategorie['kategorie_id'] : '';
                    $Kategorie_name = isset($firstMatchIKategorie['label']) ? $firstMatchIKategorie['label'] : '';
                    $icon = isset($firstMatchIKategorie['icon']) ? $firstMatchIKategorie['icon'] : '';
                    $backgroundColor = isset($firstMatchIKategorie['backgroundColor']) ? $firstMatchIKategorie['backgroundColor'] : '';
                    $textColor = isset($firstMatchIKategorie['textColor']) ? $firstMatchIKategorie['textColor'] : '';
                } else {
                    $categoryID = (string) uniqid();
                    $Kategorie_name = 'New';
                    $icon = 'plus';
                    $backgroundColor = '#FF0000';
                    $textColor = '#FFFFFF';
                }
                ///----------------------------------------------------------------
                $details_mit_zusatzfeld = htmlspecialchars($event->Beschreibung, ENT_QUOTES, 'UTF-8');
                $notizen = esc_html(wp_strip_all_tags($event->Notizen ?? ''));
                $teilnehmer = esc_html($event->Teilnehmer ?? '');
                $notiz_journal = esc_html(wp_strip_all_tags($event->notiz_journal ?? ''));
                if (!empty($ter_kal_termin_zusatzfelder_option)) {
                    foreach ($ter_kal_termin_zusatzfelder_option as $zusatzfeld) {
                        $zusatzfeld_key = $zusatzfeld['feld_key'];
                        $zusatzfeld_name = $zusatzfeld['feld_name'];
                        $zusatzfeld_art = $zusatzfeld['feld_art'];
                        switch ($zusatzfeld_key) {
                            case 'list_image':
                                $details_mit_zusatzfeld .= '<img src="' . esc_url($event->list_image) . '" style="max-width:100%; height:auto;" class="wp-block-image">';
                                break;
                            case 'zusatz_url':
                                $details_mit_zusatzfeld .= '<a href="' . esc_url($event->zusatz_url) . '" target="_blank">' . esc_url($event->zusatz_url) . '</a>';
                                break;
                            default:
                                $details_mit_zusatzfeld .= '<hr>' . $zusatzfeld_name . ': ' . esc_html($event->$zusatzfeld_key);
                                break;
                        }
                    }
                }
                ///----------------------------------------------------------------
                $new_events[] = [
                    'id' => (string) $event->id,
                    'groupId' => (string) $event->id,
                    'title' => $event->title,
                    'start' => $event->start,
                    'end' => $event->end,
                    'backgroundColor' => $backgroundColor,
                    'textColor' => $textColor,
                    'extendedProps' => [
                        'details' => $details_mit_zusatzfeld,
                        'notes' => $notizen . '. --- Participants: ' . $teilnehmer . '. --- ' . $notiz_journal,
                        'location' => $event->Ort ?? '',
                        'category' => [
                            'categoryID' => $categoryID,
                            'backgroundColor' => $backgroundColor,
                            'textColor' => $textColor,
                            'label' => $Kategorie_name,
                            'icon' => $icon,
                        ]
                    ]
                ];
            }

            // Update options with the new events and categories.
            if (!empty($new_events)) {
                update_option('termin_kalender_events', json_encode($new_events), false);
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                $wpdb->query("DROP TABLE IF EXISTS $old_table_safe");
                // ter_kal_termin_felder/ ter_kal_termin_zusatzfelder und Feldinhalte sind übernommen, alte zusatzfelder jetzt auch löschen
                delete_option('ter_kal_termin_zusatzfelder');
            }

        } // end if database table exist
//--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------
        // Set first-run and migration flags.
        //update_option( 'termin_kalender_first_run', 'OK' );
        //error_log( 'Termin Kalender Cleanup: First run database cleanup completed.' );
        if (defined('TER_KAL_DEV_MODE_ON')) {
            //echo "<script>console.log( 'Termin Kalender Cleanup: First run database cleanup completed.' );</script>";
        }
        /**
         * Display admin notice for calendar cleanup completion
         */
        add_action('admin_notices', function () {
            ?>
            <div class="notice notice-success is-dismissible">
                <p><?php esc_html_e('Termin-Kalender cleanup: Old versions removed and updated to newest version successfully.', 'termin-kalender'); ?>
                </p>
            </div>
            <?php
        }, 1);

    } catch (Exception $e) {

        add_action('admin_notices', function () use ($e) {
            ?>
            <div class="notice notice-error is-dismissible">
                <p>
                    <?php esc_html_e('Termin-Kalender cleanup failed: Unable to update to newest version.', 'termin-kalender'); ?>
                    <br>
                    <strong><?php echo esc_html($e->getMessage()); ?></strong>
                </p>
            </div>
            <?php
        }, 1);
        //error_log( 'Termin Kalender Cleanup Exception: ' . $e->getMessage() );
        if (defined('TER_KAL_DEV_MODE_ON')) {
            //echo "<script>console.log( 'Termin Kalender Cleanup Exception: ' . $e->getMessage() );</script>";
        }
        // Ensure that the error doesn't block the rest of your plugin.
        //update_option( 'termin_kalender_first_run', 'OK' );
    }

    //-----------------------------------------------------------------------------

} // end cleanup_old_termin_kalender_versions
//-----------------------------------------------------------------------------

