<?php
/**
 * Plugin Name: Termin-Kalender
 * Plugin URI: https://termin-kalender.pro
 * Description: Termin-Kalender is your easy monthly planner. This calendar app provides a clear, monthly overview to keep you organized.
 * Version: 1.3.3
 * Requires at least: 6.0
 * Requires PHP: 8.0
 * Author: beat.k
 * License: GPL2+
 * Text Domain: termin-kalender
 * Domain Path: /languages/
 *
 */

defined('ABSPATH') || exit;

//------------------------------------------------
/*
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details: https://www.gnu.org/licenses/.
Limitation of Liability
By using this software, you acknowledge and agree that the authors, developers, and copyright holders shall not be held liable for any damages, claims, or liabilities arising out of or in connection with the use of this software, including its integration into commercial products or applications. You assume all responsibility for ensuring compliance with applicable laws, regulations, and standards in such use cases.
 */
//------------------------------------------------
class Termin_Kalender_Plugin
{
    // Define the plugin constants
    const TER_KAL_TK_VERSION = '1.3.3';
    const TER_KAL_SHORTCODES = ['termin-kalender-calendar', 'my-termin-kalender', 'termin-kalender-simple-list', 'termin-kalender-pro-list', 'termin-kalender-fullpage', 'termin-kalender-pro-reservation', 'termin-kalender-pro-ical', 'termin-kalender-pro-todo', 'termin-kalender-calendar-editable', 'termin-kalender-pro-teammessage', 'ter_kal_editable_frontend'];
    const TER_KAL_BLOCKS = ['termin-kalender/simplelist', 'termin-kalender/kalender-block', 'termin-kalender/list-pro', 'termin-kalender/reservation-pro', 'termin-kalender/ical-block', 'termin-kalender/todo-list', 'termin-kalender/post-meta-header'];
    const LOCALE_MAP = [
        'de' => 'de_DE',
        'fr' => 'fr_FR',
        'en' => 'en_US'
    ];
    // Define a static property for allowed admin page hook suffixes.
    public static $ter_kal_admin_pages_hook_suffixes = [];
    public static $plugin_url;
    public static $plugin_dir_path;
    public static $ajax_url;
    protected $manager;
    protected $block_list;
    //-------------------------------------------------------------------------------------------------
    public function __construct()
    {
        self::$ajax_url = admin_url('admin-ajax.php');
        self::$plugin_url = plugin_dir_url(__FILE__);
        self::$plugin_dir_path = plugin_dir_path(__FILE__);
        // actions
        add_action('init', [$this, 'load_textdomain']);
        add_action('init', [$this, 'init_termin_kalender_update']);
        add_action('admin_enqueue_scripts', [$this, 'ter_kal_enqueue_admin_assets']);
        // filters
        // require
        require_once plugin_dir_path(__FILE__) . 'includes/dashicons.php';
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-functions.php';
        new Termin_Kalender_Functions();
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-event-repository.php';
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-rest-api.php';
        new Termin_Kalender_REST_API();
        require_once plugin_dir_path(__FILE__) . 'classes/class_termin_kalender_manager.php';
        $this->manager = Termin_Kalender_Manager::get_instance();
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-admin-page.php';
        new Termin_Kalender_Admin_Page();
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-page-overview.php';
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-admin-menu.php';
        Termin_Kalender_Admin_Menu::init();
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-magic-pages.php';
        new Termin_Kalender_Magic_Pages();
        require_once plugin_dir_path(__FILE__) . 'includes/admin_page_initial_setup_rest_api.php';
        require_once plugin_dir_path(__FILE__) . 'includes/admin_page_initial_setup.php'; // 14
        //--------------------------------------------------------------------------------
        require_once plugin_dir_path(__FILE__) . 'includes/admin_page_block_calendar.php'; // 16
        require_once plugin_dir_path(__FILE__) . 'includes/admin_page_block_simple_list.php'; // 18
        if (!defined('TERMIN_KALENDER_PRO_ON')) {
            require_once plugin_dir_path(__FILE__) . 'includes/admin_page_PRO_info.php'; // 90
        }
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-block-list.php';
        $this->block_list = Termin_Kalender_Block_List::get_instance();
        require_once plugin_dir_path(__FILE__) . 'includes/plugin_rating_request.php';
    }
    //-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
    //-------------------------------------------------------------------------------------------------
    public function load_textdomain()
    {
        // Engage JIT JS filter
        add_filter('load_script_translation_file', [$this, 'map_script_translations'], 10, 3);

        // Engage JIT PHP filters
        // Covers lightning fast PHP .l10n.php loading introduced in WP 6.5
        add_filter('load_translation_file', [$this, 'force_local_translation'], 10, 2);
        // Fallback for WP 6.0 to 6.4 (since the baseline requirement is WP 6.0)
        add_filter('load_textdomain_mofile', [$this, 'force_local_translation'], 10, 2);

        // Trigger the standard WP process internally, the filters above will intercept it natively
        /* NOTE FOR REPO REVIEWERS:
         * We intentionally use load_plugin_textdomain() to bundle and serve local translation files 
         * (de_DE, en_US, fr_FR) directly with the plugin. This guarantees 
         * terminology consistency without relying entirely on external GlotPress community syncs. 
         */
        // phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound
        load_plugin_textdomain('termin-kalender', false, dirname(plugin_basename(__FILE__)) . '/languages/');
    }
    //-------------------------------------------------------------------------------------------------
    public function force_local_translation($file, $domain)
    {
        if ('termin-kalender' !== $domain) {
            return $file;
        }

        $locale = determine_locale();
        $prefix = substr($locale, 0, 2);

        // English: skip loading entirely to use original source texts
        if ('en' === $prefix) {
            return false;
        }

        // Only evaluate local files for DE and FR, skipping disk checks for other languages
        if (!in_array($prefix, ['de', 'fr'], true)) {
            return $file;
        }

        $main_locale = self::LOCALE_MAP[$prefix] ?? $locale;
        $languages_dir = plugin_dir_path(__FILE__) . 'languages/';

        // Check for WP 6.5+ lightning-fast PHP translation file
        $local_l10n = $languages_dir . 'termin-kalender-' . $main_locale . '.l10n.php';
        if (is_file($local_l10n)) {
            return $local_l10n; // Force our local file, ignoring global wp-content/languages
        }

        // Fallback to older MO file format for WP 6.0 - 6.4 users
        $local_mo = $languages_dir . 'termin-kalender-' . $main_locale . '.mo';
        if (is_file($local_mo)) {
            return $local_mo;
        }

        return $file;
    }
    //-------------------------------------------------------------------------------------------------
    public function map_script_translations($file, $handle, $domain)
    {
        // Don't process empty files or different domains
        if ('termin-kalender' !== $domain || empty($file)) {
            return $file;
        }

        $locale = determine_locale();
        $prefix = substr($locale, 0, 2);

        // English: return false to use native JS texts via wp.i18n.__ fallback without file loads
        if ('en' === $prefix) {
            return false;
        }

        // Skip optimizing if language is not supported locally
        if (!in_array($prefix, ['de', 'fr'], true)) {
            return $file;
        }

        $main_locale = self::LOCALE_MAP[$prefix] ?? $locale;

        // Extract filename from the generated string
        $filename = basename($file);

        if ($main_locale !== $locale) {
            $filename = str_replace('-' . $locale . '-', '-' . $main_locale . '-', $filename);
        }

        $local_file = plugin_dir_path(__FILE__) . 'languages/' . $filename;

        // Force return local JSON to completely bypass WordPress Repo fallbacks, ONLY if it exists natively
        if (is_file($local_file)) {
            return $local_file;
        }

        return $file;
    }
    //-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
    public function ter_kal_enqueue_admin_assets($hook)
    {
        //-------------------------------------------------------------------------
        if (class_exists('Termin_Kalender_PRO_Plugin')) {
            $pro_version = Termin_Kalender_PRO_Plugin::TER_KAL_PRO_TK_VERSION;
            if ($pro_version && version_compare($pro_version, '1.2.3.9', '<')) {
                deactivate_plugins('termin-kalender-pro/termin-kalender-pro.php', true);
                add_action('admin_notices', function () use ($pro_version) {
                    echo '<div class="notice notice-warning"><p>';
                    echo '<strong>Termin-Kalender PRO ' . esc_html($pro_version) . ': </strong>';
                    echo esc_html__('You are using an outdated version. Please update both plugins.', 'termin-kalender');
                    echo '</p></div>';
                });
            }
        }
        //-------------------------------------------------------------------------
        //-------------------------------------------------------------------------
        wp_enqueue_script('termin_kalender_namespace', Termin_Kalender_Plugin::$plugin_url . 'js/termin_kalender_namespace.js', ['jquery'], Termin_Kalender_Plugin::TER_KAL_TK_VERSION, true);
        //-------------------------------------------------------------------------
        // enqueue wenn frontend seite oder post edit
        //$screen = get_current_screen();
        // moved inside toplevel_page_termin-kalender
        //-------------------------------------------------------------------------
        $is_free_admin = in_array($hook, Termin_Kalender_Plugin::$ter_kal_admin_pages_hook_suffixes, true);
        //------------------------------------------------------------------------------------------------
        if (!$is_free_admin) {
            return;
        }
        //-------------------------------------------------------------------------
        // brauchen wir nur für die admin seiten
        //-------------------------------------------------------------------------
        require_once plugin_dir_path(__FILE__) . 'includes/enqueue_jquery_base.php';
        //-------------------------------------------------------------------------
        wp_enqueue_script('fullcalendar_js', self::$plugin_url . 'dist/index.global.min.js', ['jquery', 'moment'], self::TER_KAL_TK_VERSION, true);
        wp_enqueue_script('fullcalendar_locales', self::$plugin_url . 'dist/locales-all.global.min.js', ['fullcalendar_js'], self::TER_KAL_TK_VERSION, true);
        wp_enqueue_script('rrule_js', self::$plugin_url . 'dist/rrule.js', [], self::TER_KAL_TK_VERSION, true);  // keep for downgrade
        wp_register_script('terminkalender_fullcalendar-rrule', self::$plugin_url . 'dist/@fullcalendar/rrule/index.global.min.js', ['rrule_js'], self::TER_KAL_TK_VERSION, true);  // keep for downgrade
        wp_enqueue_script('termin_kalender_common', Termin_Kalender_Plugin::$plugin_url . 'js/common.js', ['termin_kalender_namespace', 'jquery', 'fullcalendar_js', 'fullcalendar_locales', 'rrule_js', 'terminkalender_fullcalendar-rrule'], Termin_Kalender_Plugin::TER_KAL_TK_VERSION, true);
        wp_enqueue_script('termin_kalender_common_admin', Termin_Kalender_Plugin::$plugin_url . 'js/common_admin.js', ['termin_kalender_namespace', 'jquery'], Termin_Kalender_Plugin::TER_KAL_TK_VERSION, true);
        //-------------------------------------------------------------------------
        wp_enqueue_style('termin_kalender', self::$plugin_url . 'css/termin_kalender.css', [], self::TER_KAL_TK_VERSION, 'all');
        wp_enqueue_style('termin_kalender_admin', self::$plugin_url . 'css/termin_kalender_admin.css', [], self::TER_KAL_TK_VERSION, 'all');
        //-------------------------------------------------------------------------

        //-------------------------------------------------------------------------
        if ($hook == 'toplevel_page_termin-kalender') {
            $terminKalenderData = $this->manager->get_termin_kalender_data(true);

            wp_enqueue_style('termin_kalender_ui_dialog', Termin_Kalender_Plugin::$plugin_url . 'css/termin_kalender_ui_dialog.css', ['termin_kalender'], Termin_Kalender_Plugin::TER_KAL_TK_VERSION, 'all');
            wp_enqueue_style('terminkalender_calendar_css', Termin_Kalender_Plugin::$plugin_url . 'css/termin_kalender_calendar.css', ['termin_kalender'], Termin_Kalender_Plugin::TER_KAL_TK_VERSION, 'all');
            wp_enqueue_style('flatpickr', self::$plugin_url . 'dist/flatpickr/flatpickr.min.css', [], self::TER_KAL_TK_VERSION, 'all');
            wp_enqueue_style('flatpickr-theme', self::$plugin_url . 'dist/flatpickr/themes/light.css', ['flatpickr'], self::TER_KAL_TK_VERSION, 'all');
            wp_enqueue_style('termin_kalender_flatpickr', self::$plugin_url . 'css/termin_kalender_flatpickr.css', ['flatpickr-theme'], self::TER_KAL_TK_VERSION, 'all');
            wp_enqueue_script('flatpickr', self::$plugin_url . 'dist/flatpickr/flatpickr.min.js', [], '4.6.13', true);
            $lang = $terminKalenderData['ter_kal_lang'];
            if ($lang !== 'en') {
                $locale_file = self::$plugin_url . 'dist/flatpickr/l10n/' . $lang . '.js';
                wp_enqueue_script('flatpickr-locale', $locale_file, ['termin_kalender_namespace', 'flatpickr'], '4.6.13', true);
            }
            //-------------------------------------------------------------------------
            wp_enqueue_script('termin_kalender_api', self::$plugin_url . 'js/termin-kalender-api.js', ['termin_kalender_namespace'], self::TER_KAL_TK_VERSION, true);
            wp_enqueue_script('termin_kalender_dialogs', self::$plugin_url . 'js/termin-kalender-dialogs.js', ['termin_kalender_api', 'termin_kalender_namespace', 'jquery', 'jquery-ui-dialog'], self::TER_KAL_TK_VERSION, true);
            wp_enqueue_script('termin_kalender_calendar', self::$plugin_url . 'js/calendar.js', ['termin_kalender_api', 'termin_kalender_dialogs', 'termin_kalender_namespace', 'fullcalendar_js', 'fullcalendar_locales', 'rrule_js', 'terminkalender_fullcalendar-rrule', 'flatpickr', 'termin_kalender_common'], self::TER_KAL_TK_VERSION, true);
            //error_log(print_r($terminKalenderData, true));
            wp_localize_script('termin_kalender_calendar', 'terminKalenderData', $terminKalenderData);
            //////
            wp_set_script_translations('termin_kalender_calendar', 'termin-kalender', self::$plugin_dir_path . 'languages');
            //////
            // nicht fuer frontend:
            wp_enqueue_script('google_calendar', self::$plugin_url . 'dist/@fullcalendar/google-calendar/index.global.min.js', ['jquery'], self::TER_KAL_TK_VERSION, true); // keep for downgrade
            wp_enqueue_script('termin_kalender_format_buttons', self::$plugin_url . 'js/termin_kalender_format_buttons.js', ['termin_kalender_namespace'], self::TER_KAL_TK_VERSION, true);
            wp_set_script_translations('termin_kalender_format_buttons', 'termin-kalender', self::$plugin_dir_path . 'languages');
        }
        //------------------------------------------------------------------
    }
    //------------------------------------------------------------------

    public static function activate()
    {

        $options = get_option('termin_kalender_options', array());
        $options['termin_kalender_version'] = self::TER_KAL_TK_VERSION;
        update_option('termin_kalender_options', $options);

        // Attempt table creation immediately so the fallback flag is set
        // correctly before first_run() writes any demo data.
        require_once plugin_dir_path(__FILE__) . 'classes/class-termin-kalender-event-repository.php';
        Termin_Kalender_Event_Repository::create_table();

        require_once plugin_dir_path(__FILE__) . 'includes/first_run_cleanup_old_versions.php';
        termin_kalender_cleanup_old_versions();
        require_once plugin_dir_path(__FILE__) . 'includes/dashicons.php';
        require_once plugin_dir_path(__FILE__) . 'includes/first_run.php';
        termin_kalender_first_run();
    }

    // to run cleanup logic also at plugin update.
    public static function init_termin_kalender_update()
    {
        // ----------------------------------------------------
        // Auto-Migration to DB Table without requiring reactivation
        // ----------------------------------------------------
        if (class_exists('Termin_Kalender_Event_Repository') && get_option('termin_kalender_events') !== false) {
            Termin_Kalender_Event_Repository::migrate_from_option();
        }

        $options = get_option('termin_kalender_options', array());
        $stored_version = isset($options['termin_kalender_version']) ? $options['termin_kalender_version'] : '0';
        // Run cleanup if version mismatch (new install or update)
        if (version_compare($stored_version, self::TER_KAL_TK_VERSION, '<')) {
            require_once plugin_dir_path(__FILE__) . 'includes/first_run_cleanup_old_versions.php';
            termin_kalender_cleanup_old_versions();
            // Keep rewrite flushing limited to actual upgrades.
            flush_rewrite_rules();
            $options['termin_kalender_version'] = self::TER_KAL_TK_VERSION;
            update_option('termin_kalender_options', $options);
        }
    }

    /**
     * Plugin deactivation hook callback.
         Auto data-backup, cleanup, DB deletion?  IF PRO: ter_kal_backup_selected_tables()
         Ask if DB entries should be deleted.
         Remove options
     */
    public static function deactivate()
    {
        flush_rewrite_rules();
    }

    public static function uninstall()
    {
        // Delete here with user confirmation
        delete_option('termin_kalender_options');
        remove_role('termin_kalender_user');
        remove_role('termin_kalender_manager');
        remove_role('termin_kalender_team');
        $editor = get_role('editor');  // keep admin
        if ($editor) {
            foreach (['edit', 'delete'] as $action) {
                $editor->remove_cap("termin_kalender_{$action}");
            }
        }
    }

}
// Register activation and deactivation hooks.
register_activation_hook(__FILE__, ['Termin_Kalender_Plugin', 'activate']);
register_deactivation_hook(__FILE__, ['Termin_Kalender_Plugin', 'deactivate']);
register_uninstall_hook(__FILE__, ['Termin_Kalender_Plugin', 'uninstall']);
// ----------------------------
function termin_kalender_load_plugin()
{
    new Termin_Kalender_Plugin();
    if (function_exists('wp_register_data_request_type')) {
        wp_register_data_request_type('termin-kalender', [
            'supports_consent' => true,
            'categories' => ['functional'],
        ]);
    }
}
add_action('plugins_loaded', 'termin_kalender_load_plugin', 10);
// ----------------------------
