<?php
/**
 * Neue, performante Modul-Klasse für RegisterKey (Liste & Anlegen kombiniert, Pagination, Filter)
 */
class Trainingssystem_Plugin_Module_Register_Key_V2 {
    public function __construct() {}

    /**
     * Kombinierter Shortcode-Handler für RegisterKey-Liste und/oder Formular
     * @param array $atts
     * @return string
     */
    public function registerkeyV2($atts = []) {
        // Grundberechtigung prüfen
        if(!Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey")) {
            $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }

        $atts = shortcode_atts([
            'mode' => 'both', // 'list', 'add', 'both'
            'titel' => 'Freischaltcodes', // Überschrift für die Seite
        ], $atts);
        // GET-Parameter für Pagination und Filter
        $atts['scope'] = isset($_GET['scope']) ? $_GET['scope'] : 'all';
        $atts['perpage'] = isset($_GET['perpage']) ? $_GET['perpage'] : 25;
        $atts['rkpage'] = isset($_GET['rkpage']) ? $_GET['rkpage'] : 1;
        if (isset($_GET['search'])) $atts['search'] = $_GET['search'];
        if (isset($_GET['column'])) $atts['column'] = $_GET['column'];

        // ZENTRAL: Alle Daten einmal laden und wiederverwenden
        $shared_data = $this->loadSharedData();

        $output = '';
        $show_list = in_array($atts['mode'], ['list', 'both']);
        $show_add = in_array($atts['mode'], ['add', 'both']);

        if ($show_add) {
            $output .= $this->renderAddForm($shared_data, $atts);
        }
        if ($show_add && $show_list) {
            $output .= '<hr style="margin: 50px 0; border: none; border-top: 2px solid #dee2e6;">'; // Sichtbare Trennung zwischen Add und List
        }
        if ($show_list) {
            $output .= $this->renderList($atts, $shared_data);
        }
        return $output;
    }

    /**
     * Lädt alle Daten zentral, die sowohl für Liste als auch Formular benötigt werden
     */
    private function loadSharedData() {
        // Berechtigungen zentral prüfen
        $berechtigung = Trainingssystem_Plugin_Module_Berechtigung::getInstance();
        $has_registerkeyall = $berechtigung->accessAllowed("registerkeyall");
        $has_registerkeyown = $berechtigung->accessAllowed("registerkeyown");
        $has_vorlagenall = $berechtigung->accessAllowed("vorlagenall");
        $has_vorlagenown = $berechtigung->accessAllowed("vorlagenown");
        $has_companymgrall = $berechtigung->accessAllowed("companymgrall");
        $has_companymgrown = $berechtigung->accessAllowed("companymgrown");

        // Vorlagen-Daten laden
        $vorlagen = [];
        if($has_vorlagenall) {
            $vorlagen = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUser();
        } elseif ($has_vorlagenown) {
            $vorlagen = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUser();
        }

        // Companies-Daten laden (nur für Formular-Dropdowns)
        $companies = [];
        if($has_companymgrall) {
            $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(false, false, false);
        } elseif ($has_companymgrown) {
            $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getMyCompanies(get_current_user_id());
        }

        // Settings laden
        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

        return [
            'vorlagen' => $vorlagen,
            'companies' => $companies,
            'settings' => $settings,
            'berechtigungen' => [
                'registerkeyall' => $has_registerkeyall,
                'registerkeyown' => $has_registerkeyown,
                'vorlagenall' => $has_vorlagenall,
                'vorlagenown' => $has_vorlagenown,
                'companymgrall' => $has_companymgrall,
                'companymgrown' => $has_companymgrown,
            ]
        ];
    }



    /**
     * Rendert die paginierte RegisterKey-Liste
     */
    private function renderList($atts, $shared_data) {
        $dao = new Trainingssystem_Plugin_Database_Registerkey_Daoimpl_V2();
        // Seitenlimit-Auswahl
        $arrayAllLimits = [25, 50, 100, 'Alle'];
        $perpage = isset($atts['perpage']) ? $atts['perpage'] : 25;
        if ($perpage === 'Alle' || $perpage === 'all') {
            $perpage = 1000000; // sehr hoher Wert für "Alle"
            $perpage_for_template = 'all';
        } else {
            $perpage = (int)$perpage;
            if (!in_array($perpage, [25, 50, 100])) {
                $perpage = 25;
            }
            $perpage_for_template = $perpage;
        }
        $rkpage = max(1, intval($atts['rkpage']));
        $offset = ($rkpage - 1) * $perpage;
        
        // Scope-Logik basierend auf bereits geladenen Berechtigungen
        $has_registerkeyall = $shared_data['berechtigungen']['registerkeyall'];
        $has_registerkeyown = $shared_data['berechtigungen']['registerkeyown'];
        
        // Wenn nur registerkeyown, dann immer nur "meine" anzeigen
        if ($has_registerkeyown && !$has_registerkeyall) {
            $onlymine = true;
            $show_scope_switch = false;
        } else {
            // Wenn registerkeyall, dann Switch anzeigen und scope-Parameter berücksichtigen
            $onlymine = ($atts['scope'] === 'my');
            $show_scope_switch = true;
        }
        
        // Suchparameter verarbeiten
        $search = isset($atts['search']) ? sanitize_text_field($atts['search']) : '';
        $column = isset($atts['column']) ? sanitize_text_field($atts['column']) : 'all';
        
        // Validierung der Suchspalte
        $valid_columns = ['all', 'code', 'vorlagen', 'count_code', 'company_name', 'companygroup_name', 'studygroup_id', 'create_date'];
        if (!in_array($column, $valid_columns)) {
            $column = 'all';
        }
        
        $total = $dao->countAll($onlymine, $search, $column);
        $data = $dao->getPaginated($perpage, $offset, $onlymine, $search, $column);
        $heading = $atts['titel'];
        $maxpages = max(1, ceil($total / $perpage));
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        
        // Verwende bereits geladene Daten
        $vorlagen = $shared_data['vorlagen'];
        $settings = $shared_data['settings'];
        
        // Aktuelle URL und Query-Parameter für Pagination/Filter-Links
        $base_url = get_permalink() ?: get_site_url();
        $current_params = $_GET;
        // Diese Werte werden im Template überschrieben
        $current_params['scope'] = $onlymine ? 'my' : $atts['scope'];
        $current_params['perpage'] = $perpage_for_template;
        $current_params['rkpage'] = $rkpage;
        
        // Suchparameter hinzufügen
        if (!empty($search)) {
            $current_params['search'] = $search;
            $current_params['column'] = $column;
        } else {
            unset($current_params['search']);
            unset($current_params['column']);
        }

        $output = '<style>
</style>';
        $output .= $twig->render('user-register-key/register-key-table-v2.html', [
            'data' => $data,
            'perpage' => $perpage_for_template,
            'rkpage' => $rkpage,
            'maxpages' => $maxpages,
            'scope' => $onlymine ? 'my' : $atts['scope'],
            'show_scope_switch' => $show_scope_switch,
            'total' => $total,
            'heading' => $heading,
            'vorlagen' => $vorlagen,
            'settings' => $settings,
            'base_url' => $base_url,
            'current_params' => $current_params,
            'search' => $search,
            'column' => $column,
        ]);
        
        return $output;
    }

    /**
     * Rendert das Formular zum Anlegen eines neuen RegisterKeys
     */
    private function renderAddForm($shared_data, $atts = []) {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        $heading = isset($atts['titel']) ? $atts['titel'] : 'Freischaltcodes';

        ob_start();

        $nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG.'submitregkey';
        $noncefield = 'regkey';

        // Verwende bereits geladene Daten
        $vorlagen = $shared_data['vorlagen'];
        $companies = $shared_data['companies'];

        echo $twig->render('user-register-key/register-key-new.html', [
            'submitnonce'   =>  wp_nonce_field($nonceaction,$noncefield,true,false),
            'vorlagen'      =>  $vorlagen,
            'companies'     =>  $companies,
            'heading'       =>  $heading,
        ] );

        return ob_get_clean();
    }
} 