<?php
/*
Plugin Name: mirror_simply
Description: Startet ein Bash-Script zur Erzeugung der index.json uns Übetragung der Webpräsenz mittels rsync auf den Webserver
Version: 1.0
Author: Dieter Lang
*/

// Exit if accessed directly

// Sicherheitscheck
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


//Hinweise beim Start von Generator in simply static in log.datei schreiben
add_action('ss_archive_creation_job_before_start', function() {
    error_log(__file__.' ist aktiv');
    error_log("ABSPATH=".ABSPATH);
    $script_path = plugin_dir_path( dirname( __FILE__)).'indexer.sh';
    error_log("script_path=".$script_path);
    }
);

// Nach Beendegung des Jobs die index.json befüllen
add_action( 'ss_after_cleanup', function(){
    // Fügen Sie hier Ihren Code ein, der vor dem Export laufen soll
    // Zum Beispiel: Cache leeren, spezielle Dateien vorbereiten, Optionen setzen
    error_log('Simply Static Export startet gleich!');

    //$alleKlassen = get_declared_classes();
    //error_log(__file__." Zeile: ".__line__." Liste aller Klassen:".print_r($alleKlassen,true));
    if (!class_exists("My_Mirror_Task")){
	class My_Mirror_Task extends \Simply_Static\Task {
	    // Da Task abstrakt ist, musst du eventuell die Methode 'run' implementieren,
	    // falls diese in der Basisklasse als abstract markiert ist.
	    public function perform() {
		// Logik hier
		$this->add_message("mirror_simply ist betriebsbereit");
		return (true);
	    }

	    public function add_message($message) {
		$this->save_status_message($message);
	    }

	    public function create_index_json(){
		$erg_anzahl = "null";
		$message = __file__." Zeile: ".__line__." Das Plugin mirror simply wurde geladen!";
		error_log($message);
		$this->add_message($message);
		
		$pfad_aktuell = getcwd();
		$message = __file__." Zeile: ".__line__." pfad_aktuell = ".$pfad_aktuell;
		error_log($message);
		$this->add_message($message);

		$script_path = plugin_dir_path( dirname( __FILE__)).'indexer.sh';
		$script_path = __DIR__.'/indexer.sh';
		$message = __file__." Zeile: ".__line__." sript_path = ".$script_path;
		error_log($message);
		$this->add_message($message);
	       

		/*
		error_log("sript_path = ".$script_path);
		foreach (scandir("../") as $file) {
		  if ($file === ".." or $file === ".") continue;

			error_log(__file__." Zeile: ".__line__."$file\n");
		}
		*/

		if (file_exists($script_path)) {
		    $message = __file__." Zeile: ".__line__.": ".$script_path." aufgerufen durch: ".$_SERVER['SCRIPT_NAME'];
		    error_log($message);
		    $this->add_message($message);

		    //exec() bietet bessere Kontrolle
		    $script_output = [];
		    $script_result = -1;
		    //exec($script_path." ./sync.log >&1", $script_output, $script_result);
		    exec($script_path." >&1", $script_output, $script_result);
		    if ($script_result === 0) {
			    $message = __file__." Zeile: ".__line__." Das Bashskript wurde erfolgreich ausgeführt.";
			    error_log($message);
			    $this->add_message($message);
		    }
		    else
		    {
			    $message = __file__." Zeile: ".__line__." Fehler ! Rückgabecode : ".$script_result;
			    error_log($message);
			    $this->add_message($message);
		    }
		    $erg = " Ergebnis der Batchdatei:\n";
		    foreach ($script_output as $zeile =>  $value){
			    $erg .= "[info] ".$value."\n";
			    if (str_contains($value,"Anzahl=")){	
				$erg_anzahl = $value;
			    }
		    }

		    $message = __file__." Zeile: ".__line__." ".$erg;
		    error_log($message);
		    $this->add_message($message);

		}
		else
		{
		    $message = __file__." Zeile: ".__line__." Das Skript ".$script_path." wurde nicht gefunden.";
		    error_log($message);
		    $this->add_message($message);

		}
		return($erg_anzahl);
	    }


	}
    }

    // Jetzt kannst du sie nutzen:
    if (class_exists("My_Mirror_Task")){
	$my_task = new My_Mirror_Task();
    }
    $my_task->add_message(__file__."Zeile ".__line__.": My_Mirror_Task ist bereit");
    $my_erg = $my_task->create_index_json();
    $my_task->add_message("Indizierung beendet. ".$my_erg);


}, 10, 2);

// Eigenes Suchfeld mit Datenbank in index.json
require_once plugin_dir_path(__FILE__) . 'cls-js-search.php';
$search_tool = new JS_Search_Integration();

// Du verweist auf das Objekt ($search_tool) und die Methode darin
add_action('widgets_init', [$search_tool, 'register_search_widget']);
add_action('wp_enqueue_scripts', [$search_tool, 'enqueue_assets']);
add_shortcode('JS_Suche_Widget', [$search_tool, 'render_search_form']);

// Die standard-Suche von Wordpress abschalten
if ( ! class_exists( 'c2c_DisableSearch' ) ) :

class c2c_DisableSearch {

	/**
	 * Returns version of the plugin.
	 *
	 * @since 1.3
	 */
	public static function version() {
		return '2.1.1';
	}

	/**
	 * Prevent instantiation.
	 *
	 * @since 1.6
	 */
	private function __construct() {}

	/**
	 * Prevent unserializing an instance of the class.
	 *
	 * @since 1.6
	 * @since 1.8.3 Changed method visibility from private to public and throw exception if invoked.
	 */
	public function __wakeup() {
		/* translators: %s: Name of plugin class. */
		throw new Error( esc_html( sprintf( __( '%s cannot be unserialized.', 'disable-search' ), __CLASS__ ) ) );
	}

	/**
	 * Initializes the plugin.
	 */
	public static function init() {
		// Register hooks.
		add_action( 'widgets_init',                 array( __CLASS__, 'disable_search_widget' ), 1 );
		if ( ! is_admin() ) {
			add_action( 'parse_query',              array( __CLASS__, 'parse_query' ), 5 );
		}
		add_filter( 'get_search_form',              '__return_empty_string', 999 );

		add_action( 'admin_bar_menu',               array( __CLASS__, 'admin_bar_menu' ), 99999 );

		add_filter( 'disable_wpseo_json_ld_search', '__return_true' );

		// Disable core search block.
		add_action( 'init',                         array( __CLASS__, 'disable_core_search_block' ), 11 );
		add_action( 'enqueue_block_editor_assets',  array( __CLASS__, 'enqueue_block_editor_assets' ) );

	}

	/**
	 * Disables the built-in WP search widget.
	 */
	public static function disable_search_widget() {
		unregister_widget( 'WP_Widget_Search' );
	}

	/**
	 * Unregisters the core/search block (at least for PHP).
	 *
	 * Though this technically works (the block gets unregistered), it doesn't
	 * actually disable the block, which is at least still available via JS and
	 * thus is functionally equivalent to this doing nothing.
	 *
	 * The use of the `'allowed_block_types_all'` filter seems ideal for this
	 * sort of thing, but it has its issues at present (see associated link).
	 *
	 * @link https://github.com/WordPress/gutenberg/issues/12931
	 * @since 2.0
	 */
	public static function disable_core_search_block() {
		if ( function_exists( 'unregister_block_type' ) ) {
			$block = 'core/search';
			if ( WP_Block_Type_Registry::get_instance()->is_registered( $block ) ) {
				unregister_block_type( $block );
			}
		}
	}

	/**
	 * Enqueues block editor assets, notable to disable the search block.
	 *
	 * @since 2.0
	 */
	public static function enqueue_block_editor_assets() {
		wp_enqueue_script( 'disable-search-js', plugins_url( '/assets/js/disable-search.js', __FILE__ ), array( 'wp-blocks', 'wp-dom' ), self::version(), true );
	}

	/**
	 * Unsets all search-related variables in WP_Query object and sets the
	 * request as a 404 if a search was attempted.
	 *
	 * @param WP_Query $obj A query object.
	 */
	public static function parse_query( $obj ) {
		if ( $obj->is_search && $obj->is_main_query() ) {
			unset( $_GET['s'] );
			unset( $_POST['s'] );
			unset( $_REQUEST['s'] );
			unset( $obj->query['s'] );
			$obj->set( 's', '' );
			$obj->is_search = false;
			$obj->set_404();
			status_header( 404 );
			nocache_headers();
		}
	}

	/**
	 * Removes the search item from the admin bar.
	 *
	 * @since 1.6
	 *
	 * @param WP_Admin_Bar $wp_admin_bar The WP admin bar object.
	 */
	public static function admin_bar_menu( $wp_admin_bar ) {
		$wp_admin_bar->remove_menu( 'search' );
	}

} // end c2c_DisableSearch

add_action( 'plugins_loaded', array( 'c2c_DisableSearch', 'init' ) );

endif; // end if !class_exists()


/**
 * Plugin Name: Mirror Simply Code Copy
 * Description: Fügt einen Copy-Button mit anpassbaren Farben hinzu.
 */
/**
 * --- START: COPY-BUTTON & ADMIN-MENÜ FÜR MIRROR_SIMPLY ---
 */

// 1. Einstellungsseite im Admin-Menü (unter Einstellungen) registrieren
add_action('admin_menu', function() {
    add_options_page(
        'Mirror Simply Settings', 
        'Mirror Simply', 
        'manage_options', 
        'mirror_simply_settings', 
        'mirror_simply_settings_page_html'
    );
});

// 2. Einstellungen in der Datenbank registrieren
add_action('admin_init', function() {
    register_setting('ms_copy_group', 'ms_btn_color', array('default' => '#333333'));
    register_setting('ms_copy_group', 'ms_success_color', array('default' => '#2e7d32'));
});

// 3. HTML-Inhalt der Einstellungsseite
function mirror_simply_settings_page_html() {
    ?>
    <div class="wrap">
        <h1>Mirror Simply - Code Copy Einstellungen</h1>
        <form method="post" action="options.php">
            <?php settings_fields('ms_copy_group'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row">Button Textfarbe (Standard)</th>
                    <td><input type="color" name="ms_btn_color" value="<?php echo esc_attr(get_option('ms_btn_color', '#333333')); ?>"></td>
                </tr>
                <tr>
                    <th scope="row">Erfolgsfarbe (Kopiert!)</th>
                    <td><input type="color" name="ms_success_color" value="<?php echo esc_attr(get_option('ms_success_color', '#2e7d32')); ?>"></td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

// 4. FRONTEND: Skripte laden und CSS für Code-Blöcke einfügen
add_action('wp_enqueue_scripts', function() {
    // Nur in Beiträgen/Seiten mit einem Gutenberg Code-Block laden
    if ( (is_singular('post') || is_singular('page')) && has_block('core/code') ) {
        
        // JavaScript laden (Pfad: mirror_simply/js/copy-button.js)
        wp_enqueue_script(
            'ms-copy-js', 
            plugins_url('copy-button.js', __FILE__), 
            array(), 
            '1.0.6', 
            true
        );

        // Farben aus Admin-Optionen laden
        $btn_color = get_option('ms_btn_color', '#333333');
        $success_color = get_option('ms_success_color', '#2e7d32');

        // Dynamisches CSS für den Copy-Button
        $custom_css = "
            .wp-block-code { position: relative !important; }
            .code-copy-button {
                position: absolute !important; 
                top: 10px !important; 
                right: 10px !important;
                display: flex !important; 
                align-items: center !important;
                background-color: #ffffff !important; 
                border: 1px solid {$btn_color} !important; 
                color: {$btn_color} !important;
                border-radius: 4px !important; 
                padding: 6px 12px !important;
                font-size: 13px !important; 
                cursor: pointer !important; 
                z-index: 10 !important;
                transition: all 0.2s ease-in-out !important;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
                line-height: 1 !important;
            }
            .code-copy-button:hover {
                background-color: {$btn_color} !important;
                color: #ffffff !important;
            }
            .code-copy-button.is-copied {
                color: {$success_color} !important;
                border-color: {$success_color} !important;
                background-color: {$success_color}1a !important; 
                transform: scale(1.05) !important;
            }
            .code-copy-button svg { margin-right: 6px !important; flex-shrink: 0 !important; stroke: currentColor !important; }
        ";
        
        wp_add_inline_style('wp-block-library', $custom_css);
    }
});
