<?php
/**
 * Plugin Name: PocketBooking Pro - Manage Appointments on the Go
 * Description: PocketBooking Pro is a modern but simple appointment booking plugin for appointment scheduling with employee management, opening hours administration, and email notifications. Ideal for hair salons, wellness studios, and other service businesses.
 * Version: 1.4.0
 * Author: Maxim Ristow / maksim85
 * Author URI: https://mobile-refuel.de
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: simple-appointment-booking
 */

// Sicherheitsmaßnahme: Direkten Zugriff verhindern
if (!defined('ABSPATH')) {
    exit;
}

// Fallback-Trial-Dauer, falls Server nicht erreichbar oder keine Dauer liefert.
define('SIMPBOOK_DEFAULT_FALLBACK_TRIAL_DURATION_SECONDS', 7 * 24 * 60 * 60); // 7 Tage als Notfall-Fallback
define('SIMPBOOK_PLUGIN_TEXT_DOMAIN', 'simple-appointment-booking'); // Textdomain für Übersetzungen
define('SIMPBOOK_VERSION', '1.4.0'); // Plugin-Version für Asset-Cache-Busting
define('SIMPBOOK_PLUGIN_SLUG', 'simple-appointment-booking'); // Plugin-Slug für Lizenzserver
define('SIMPBOOK_PLUGIN_DIR', plugin_dir_path(__FILE__)); // Plugin-Verzeichnis
define('SIMPBOOK_PLUGIN_URL', plugin_dir_url(__FILE__)); // Plugin-URL

// === INCLUDES ===
require_once plugin_dir_path(__FILE__) . 'includes/helpers.php';
require_once plugin_dir_path(__FILE__) . 'includes/admin-settings.php';
require_once plugin_dir_path(__FILE__) . 'includes/admin-license.php';
require_once plugin_dir_path(__FILE__) . 'includes/class-simpbook-db-reservierungen.php';

// PWA Klassen
require_once plugin_dir_path(__FILE__) . 'includes/class-simpbook-pwa-auth.php';
require_once plugin_dir_path(__FILE__) . 'includes/class-simpbook-pwa-controller.php';

// Update-System
require_once plugin_dir_path(__FILE__) . 'includes/class-simpbook-plugin-updater.php';

// === PLUGIN INITIALISIERUNG ===

// Update-System initialisieren
if (class_exists('SIMPBOOK_Plugin_Updater')) {
    $simpbook_updater = new SIMPBOOK_Plugin_Updater(
        __FILE__,
        SIMPBOOK_PLUGIN_SLUG, // Plugin-Slug für Lizenzserver (konsistent mit Lizenz-System)
        SIMPBOOK_VERSION // Aktuelle Version aus Konstante
    );
}

// Instanziiere die Klasse sofort, damit alle Hooks registriert werden
$simpbook_db_reservierungen_instanz_global = new simpbook_DB_Reservierungen();
if (!isset($GLOBALS['simpbook_db_reservierungen'])) {
    $GLOBALS['simpbook_db_reservierungen'] = $simpbook_db_reservierungen_instanz_global;
}

// === AKTIVIERUNGS-/DEAKTIVIERUNGS-HOOKS ===

register_activation_hook(__FILE__, array('simpbook_DB_Reservierungen', 'plugin_aktivieren_static'));
register_activation_hook(__FILE__, 'simpbook_schedule_reminder_emails');
register_activation_hook(__FILE__, 'simpbook_pwa_activation');
register_deactivation_hook(__FILE__, 'simpbook_unschedule_reminder_emails');

/**
 * Einmalige DB-Migration: Tabelle 'reservierungen' → 'buchungen' umbenennen.
 * Läuft nur einmal (gespeichert als Option). Wird bei jedem admin_init geprüft.
 */
function simpbook_migrate_table_rename() {
    if ( get_option( 'simpbook_migration_table_rename_done' ) ) {
        return;
    }
    global $wpdb;
    $old_table = $wpdb->prefix . 'reservierungen';
    $new_table = $wpdb->prefix . 'buchungen';

    // Alte Tabelle existiert und neue noch nicht → umbenennen
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $old_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $old_table ) ) === $old_table;
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $new_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $new_table ) ) === $new_table;

    if ( $old_exists && ! $new_exists ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query( "RENAME TABLE `{$old_table}` TO `{$new_table}`" );
    }

    update_option( 'simpbook_migration_table_rename_done', '1' );
}
add_action( 'admin_init', 'simpbook_migrate_table_rename' );

/**
 * Einmalige DB-Migration: buchungsoption_id-Spalte zur buchungen-Tabelle hinzufügen.
 * Läuft nur einmal (gespeichert als Option).
 */
function simpbook_migrate_buchungsoption_id_column() {
    if ( get_option( 'simpbook_migration_buchungsoption_id_done' ) ) {
        return;
    }
    global $wpdb;
    $tabellen_name = $wpdb->prefix . 'buchungen';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $columns = $wpdb->get_col( $wpdb->prepare( 'DESCRIBE %i', $tabellen_name ) );
    if ( ! in_array( 'buchungsoption_id', $columns, true ) ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN buchungsoption_id mediumint(9) NULL DEFAULT NULL', $tabellen_name ) );
    }
    update_option( 'simpbook_migration_buchungsoption_id_done', '1' );
}
add_action( 'admin_init', 'simpbook_migrate_buchungsoption_id_column' );

/**
 * Einmalige DB-Migration: custom_fields-Spalte zur buchungen-Tabelle hinzufügen.
 * Läuft nur einmal (gespeichert als Option).
 */
function simpbook_migrate_custom_fields_column() {
    if ( get_option( 'simpbook_migration_custom_fields_done' ) ) {
        return;
    }
    global $wpdb;
    $tabellen_name = $wpdb->prefix . 'buchungen';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tabellen_name ) ) !== $tabellen_name ) {
        return; // Tabelle existiert noch nicht
    }
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $columns = $wpdb->get_col( $wpdb->prepare( 'DESCRIBE %i', $tabellen_name ) );
    if ( ! in_array( 'custom_fields', $columns, true ) ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD COLUMN custom_fields text NULL AFTER nachricht', $tabellen_name ) );
    }
    update_option( 'simpbook_migration_custom_fields_done', '1' );
}
add_action( 'admin_init', 'simpbook_migrate_custom_fields_column' );

/**
 * PWA Aktivierungs-Hook
 * Registriert Rewrite-Rules für Manifest und Service Worker
 * Erstellt Subscriptions-Tabelle für Push-Benachrichtigungen
 * Generiert VAPID-Schlüssel für Push-Benachrichtigungen
 */
function simpbook_pwa_activation() {
    // PWA Controller Klasse explizit laden falls noch nicht geladen
    if (!class_exists('Simpbook_PWA_Controller')) {
        require_once plugin_dir_path(__FILE__) . 'includes/class-simpbook-pwa-controller.php';
    }
    
    // PWA Controller initialisieren
    if (class_exists('Simpbook_PWA_Controller')) {
        $pwa = Simpbook_PWA_Controller::get_instance();
        $pwa->register_rewrite_rules();
        
        // ⭐ Subscriptions-Tabelle für Push-Benachrichtigungen erstellen
        $pwa->create_subscriptions_table();
        
        // ⭐ VAPID-Schlüssel automatisch generieren wenn sie fehlen
        $existing_public = get_option('simpbook_pwa_vapid_public_key', '');
        $existing_private = get_option('simpbook_pwa_vapid_private_key', '');
        
        if (empty($existing_public) || empty($existing_private)) {
            $keys = $pwa->generate_vapid_keys();
            
            if ($keys && isset($keys['public']) && isset($keys['private'])) {
                update_option('simpbook_pwa_vapid_public_key', $keys['public']);
                update_option('simpbook_pwa_vapid_private_key', $keys['private']);
                
                // Push-Benachrichtigungen standardmäßig aktivieren wenn Schlüssel generiert wurden
                update_option('simpbook_pwa_push_enabled', '1');
            }
        }
    }
    // Rewrite-Rules flushen
    flush_rewrite_rules();
}
