slotmachine

<?php
/**
 * Didaktische Slotmachine – Code Snippets Version
 * Drei konfigurierbare Walzen mit eigenen Begriffen, einzeln aktivierbar.
 * Speichert Ziehungen in der Datenbank.
 */

if ( ! class_exists( 'Didaktische_Slotmachine' ) ) {

    class Didaktische_Slotmachine {

        const VERSION = '0.3';
        const TABLE   = 'didaktische_slotmachine_log';
        const OPTION  = 'dsm_walzen';

        private static $installed = false;

        public function __construct() {
            add_shortcode( 'didaktische_slotmachine', array( $this, 'render_shortcode' ) );
            add_action( 'admin_menu', array( $this, 'admin_menu' ) );
            add_action( 'admin_post_dsm_save_settings', array( $this, 'admin_post_save_settings' ) );
            add_action( 'admin_post_dsm_export', array( $this, 'admin_post_export' ) );
            add_action( 'wp_ajax_dsm_save', array( $this, 'ajax_save' ) );
            add_action( 'wp_ajax_nopriv_dsm_save', array( $this, 'ajax_save' ) );

            // Datenbanktabelle und Standardoptionen sicherstellen
            add_action( 'admin_init', array( $this, 'maybe_install' ) );
            add_action( 'init', array( $this, 'maybe_install' ) );
        }

        public function maybe_install() {
            if ( self::$installed ) return;
            self::$installed = true;

            global $wpdb;
            $table_name = $wpdb->prefix . self::TABLE;
            $charset_collate = $wpdb->get_charset_collate();

            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

            $sql = "CREATE TABLE $table_name (
                id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                term1 VARCHAR(255) NOT NULL DEFAULT '',
                term2 VARCHAR(255) NOT NULL DEFAULT '',
                term3 VARCHAR(255) NOT NULL DEFAULT '',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY  (id)
            ) $charset_collate;";

            dbDelta( $sql );

            if ( get_option( self::OPTION ) === false ) {
                $default_walzen = array(
                    1 => array(
                        'active' => 1,
                        'terms'  => array( 'Dreiklang', 'Quintenzirkel', 'Dissonanz', 'Kadenz' ),
                    ),
                    2 => array(
                        'active' => 1,
                        'terms'  => array( 'Tritonus', 'Synkope', 'Septakkord', 'Konsonanz' ),
                    ),
                    3 => array(
                        'active' => 1,
                        'terms'  => array( 'Takt', 'Intervall', 'Modulation', 'Terz' ),
                    ),
                );
                add_option( self::OPTION, $default_walzen );
            }
        }

        private function get_walzen() {
            $options = get_option( self::OPTION, array() );
            foreach ( array( 1, 2, 3 ) as $id ) {
                if ( ! isset( $options[ $id ] ) || ! is_array( $options[ $id ] ) ) {
                    $options[ $id ] = array( 'active' => 0, 'terms' => array() );
                }
            }
            return $options;
        }

        public function render_shortcode() {
            $this->maybe_install();

            $walzen = $this->get_walzen();
            $active_walzen = array();
            foreach ( $walzen as $id => $data ) {
                if ( ! empty( $data['active'] ) && ! empty( $data['terms'] ) && is_array( $data['terms'] ) ) {
                    $active_walzen[ $id ] = $data['terms'];
                }
            }

            if ( empty( $active_walzen ) ) {
                return '<p><strong>Slotmachine:</strong> Keine aktiven Walzen konfiguriert. Bitte im Admin-Bereich Begriffe hinterlegen.</p>';
            }

            $nonce     = wp_create_nonce( 'dsm_nonce' );
            $ajax_url  = admin_url( 'admin-ajax.php' );
            $json_data = wp_json_encode( $active_walzen );

            ob_start();
            ?>
            <style>
                .dsm-slotmachine { text-align: center; margin: 20px auto; max-width: 700px; }
                .dsm-reels { display: flex; justify-content: center; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
                .dsm-reel { width: 140px; height: 80px; overflow: hidden; border: 2px solid #333; border-radius: 8px; background: #fff; }
                .dsm-strip { display: flex; flex-direction: column; }
                .dsm-item { height: 80px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; font-weight: 600; padding: 0 8px; box-sizing: border-box; }
                .dsm-result { font-size: 1.3rem; margin: 15px 0; min-height: 2rem; }
                .dsm-button { padding: 10px 20px; font-size: 1.1rem; cursor: pointer; }
                .dsm-button:disabled { opacity: .6; cursor: not-allowed; }
                .dsm-status { margin-top: 10px; font-size: .9rem; color: #666; }
                @media (prefers-reduced-motion: reduce) {
                    .dsm-strip { transition: none !important; }
                }
            </style>

            <div class="dsm-slotmachine">
                <div class="dsm-reels">
                    <?php foreach ( $active_walzen as $id => $terms ) : ?>
                        <div class="dsm-reel" data-walze="<?php echo esc_attr( $id ); ?>">
                            <div class="dsm-strip"></div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="dsm-result" aria-live="polite"></div>
                <button class="dsm-button">Ziehen</button>
                <div class="dsm-status"></div>
            </div>

            <script>
            (function() {
                var activeWalzen = <?php echo $json_data; ?>;
                var dsmAjax = {
                    url: <?php echo wp_json_encode( $ajax_url ); ?>,
                    nonce: <?php echo wp_json_encode( $nonce ); ?>
                };

                var reels = document.querySelectorAll('.dsm-reel');
                var button = document.querySelector('.dsm-button');
                var result = document.querySelector('.dsm-result');
                var status = document.querySelector('.dsm-status');

                function buildStrips() {
                    reels.forEach(function(reel) {
                        var walzeId = parseInt( reel.getAttribute('data-walze') );
                        var terms = activeWalzen[walzeId];
                        var strip = reel.querySelector('.dsm-strip');
                        var html = '';
                        terms.forEach(function(term) {
                            var item = document.createElement('div');
                            item.className = 'dsm-item';
                            item.textContent = term;
                            strip.appendChild(item);
                        });
                    });
                }

                function shuffle(array) {
                    var a = array.slice();
                    for (var i = a.length - 1; i > 0; i--) {
                        var j = Math.floor(Math.random() * (i + 1));
                        var tmp = a[i]; a[i] = a[j]; a[j] = tmp;
                    }
                    return a;
                }

                function spinReel(reel, targetIndex, callback) {
                    var strip = reel.querySelector('.dsm-strip');
                    var itemHeight = strip.querySelector('.dsm-item').offsetHeight;
                    strip.style.transition = 'transform 1.2s cubic-bezier(0.15, 0.85, 0.35, 1)';
                    strip.style.transform = 'translateY(' + (-targetIndex * itemHeight) + 'px)';
                    setTimeout(callback, 1300);
                }

                function saveResult(selected) {
                    var params = new URLSearchParams();
                    params.append('action', 'dsm_save');
                    params.append('nonce', dsmAjax.nonce);
                    params.append('terms', JSON.stringify(selected));

                    fetch(dsmAjax.url, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                        body: params.toString()
                    })
                    .then(function(response) { return response.json(); })
                    .then(function(data) {
                        if (data.success) {
                            status.textContent = 'Ergebnis gespeichert.';
                        } else {
                            status.textContent = 'Speichern fehlgeschlagen.';
                        }
                    })
                    .catch(function() {
                        status.textContent = 'Speichern fehlgeschlagen.';
                    })
                    .finally(function() {
                        button.disabled = false;
                    });
                }

                function spin() {
                    if (button.disabled) return;
                    button.disabled = true;
                    result.textContent = '';
                    status.textContent = 'Ziehe...';

                    var chosen = {};
                    var selected = [ '', '', '' ];
                    var finished = 0;

                    reels.forEach(function(reel) {
                        var walzeId = parseInt( reel.getAttribute('data-walze') );
                        var terms = activeWalzen[walzeId];
                        var randomIndex = Math.floor(Math.random() * terms.length);
                        var term = terms[randomIndex];
                        chosen[walzeId] = { term: term, index: randomIndex };
                        selected[walzeId - 1] = term;

                        spinReel(reel, randomIndex, function() {
                            finished++;
                            if (finished === reels.length) {
                                result.textContent = selected.filter(Boolean).join(' | ');
                                status.textContent = 'Speichere...';
                                saveResult(selected);
                            }
                        });
                    });
                }

                buildStrips();
                button.addEventListener('click', spin);
            })();
            </script>
            <?php
            return ob_get_clean();
        }

        public function ajax_save() {
            check_ajax_referer( 'dsm_nonce', 'nonce' );

            if ( ! isset( $_POST['terms'] ) ) {
                wp_send_json_error( 'Keine Daten.' );
            }

            $terms = json_decode( wp_unslash( $_POST['terms'] ), true );
            if ( ! is_array( $terms ) || count( $terms ) !== 3 ) {
                wp_send_json_error( 'Ungültiges Format.' );
            }

            $term1 = sanitize_text_field( $terms[0] );
            $term2 = sanitize_text_field( $terms[1] );
            $term3 = sanitize_text_field( $terms[2] );

            global $wpdb;
            $table_name = $wpdb->prefix . self::TABLE;

            $wpdb->insert(
                $table_name,
                array(
                    'term1' => $term1,
                    'term2' => $term2,
                    'term3' => $term3,
                ),
                array( '%s', '%s', '%s' )
            );

            if ( $wpdb->last_error ) {
                wp_send_json_error( 'Datenbankfehler.' );
            }

            wp_send_json_success();
        }

        public function admin_menu() {
            add_menu_page(
                'Slotmachine Log',
                'Slotmachine',
                'manage_options',
                'dsm-log',
                array( $this, 'render_admin_page' ),
                'dashicons-randomize',
                30
            );

            add_submenu_page(
                'dsm-log',
                'Slotmachine Einstellungen',
                'Einstellungen',
                'manage_options',
                'dsm-settings',
                array( $this, 'render_settings_page' )
            );
        }

        public function render_settings_page() {
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( 'Keine Berechtigung.' );
            }

            $walzen = $this->get_walzen();

            echo '<div class="wrap">';
            echo '<h1>Slotmachine Einstellungen</h1>';
            echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';
            echo '<input type="hidden" name="action" value="dsm_save_settings">';
            wp_nonce_field( 'dsm_save_settings' );

            for ( $id = 1; $id <= 3; $id++ ) {
                $data = $walzen[ $id ];
                $active_checked = ! empty( $data['active'] ) ? 'checked' : '';
                $terms_text = implode( "\n", $data['terms'] );

                echo '<h2>Walze ' . esc_html( $id ) . '</h2>';
                echo '<label><input type="checkbox" name="dsm_walzen[' . $id . '][active]" value="1" ' . $active_checked . '> Aktiv</label>';
                echo '<p>Begriffe (einer pro Zeile):</p>';
                echo '<textarea name="dsm_walzen[' . $id . '][terms]" rows="6" cols="60" style="width:100%; max-width:500px;">' . esc_textarea( $terms_text ) . '</textarea>';
                echo '<hr>';
            }

            submit_button( 'Einstellungen speichern' );
            echo '</form>';
            echo '</div>';
        }

        public function admin_post_save_settings() {
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( 'Keine Berechtigung.' );
            }

            check_admin_referer( 'dsm_save_settings' );

            $raw = isset( $_POST['dsm_walzen'] ) ? (array) $_POST['dsm_walzen'] : array();
            $new_options = array();

            foreach ( array( 1, 2, 3 ) as $id ) {
                $data = isset( $raw[ $id ] ) ? $raw[ $id ] : array();

                $active = isset( $data['active'] ) ? 1 : 0;
                $terms_text = isset( $data['terms'] ) ? $data['terms'] : '';

                $terms = preg_split( '/\r\n|\r|\n/', $terms_text );
                $terms = array_map( 'trim', $terms );
                $terms = array_filter( $terms, 'strlen' );
                $terms = array_values( array_map( 'sanitize_text_field', $terms ) );

                $new_options[ $id ] = array(
                    'active' => $active,
                    'terms'  => $terms,
                );
            }

            update_option( self::OPTION, $new_options );

            wp_safe_redirect( admin_url( 'admin.php?page=dsm-settings&updated=1' ) );
            exit;
        }

        public function render_admin_page() {
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( 'Keine Berechtigung.' );
            }

            global $wpdb;
            $table_name = $wpdb->prefix . self::TABLE;
            $entries = $wpdb->get_results( "SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 100" );

            echo '<div class="wrap">';
            echo '<h1>Slotmachine Log</h1>';
            echo '<a href="' . esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=dsm_export' ), 'dsm_export' ) ) . '" class="button">Als CSV exportieren</a>';
            echo '<table class="widefat striped">';
            echo '<thead><tr><th>ID</th><th>Walze 1</th><th>Walze 2</th><th>Walze 3</th><th>Zeitpunkt</th></tr></thead><tbody>';

            if ( $entries ) {
                foreach ( $entries as $entry ) {
                    echo '<tr>';
                    echo '<td>' . esc_html( $entry->id ) . '</td>';
                    echo '<td>' . esc_html( $entry->term1 ) . '</td>';
                    echo '<td>' . esc_html( $entry->term2 ) . '</td>';
                    echo '<td>' . esc_html( $entry->term3 ) . '</td>';
                    echo '<td>' . esc_html( $entry->created_at ) . '</td>';
                    echo '</tr>';
                }
            } else {
                echo '<tr><td colspan="5">Noch keine Ziehungen gespeichert.</td></tr>';
            }

            echo '</tbody></table></div>';
        }

        public function admin_post_export() {
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( 'Keine Berechtigung.' );
            }

            check_admin_referer( 'dsm_export' );

            global $wpdb;
            $table_name = $wpdb->prefix . self::TABLE;
            $entries = $wpdb->get_results( "SELECT * FROM $table_name ORDER BY created_at DESC" );

            header( 'Content-Type: text/csv; charset=utf-8' );
            header( 'Content-Disposition: attachment; filename=slotmachine-log.csv' );

            $output = fopen( 'php://output', 'w' );
            fputcsv( $output, array( 'ID', 'Walze 1', 'Walze 2', 'Walze 3', 'Zeitpunkt' ) );

            if ( $entries ) {
                foreach ( $entries as $entry ) {
                    fputcsv( $output, array( $entry->id, $entry->term1, $entry->term2, $entry->term3, $entry->created_at ) );
                }
            }

            fclose( $output );
            exit;
        }
    }

    new Didaktische_Slotmachine();
}