<?php
/*
 Plugin Name: nnax Frontend User Files
 Plugin URI:  https://www.nnax.de
 Description: Frontend file manager with user-specific files and sharing.
 Version:     1.0.6
 Author:      L.Renning - nnax IT-Lösungen
 Author URI:  https://www.nnax.de/
 License:     GPL-2.0-or-later
 License URI: https://www.gnu.org/licenses/gpl-2.0.html
 Requires at least: 6.0
 Requires PHP: 7.4
 Text Domain: nnax-frontend-user-files
 Domain Path: /languages
 *
 * @package NNAXFUF_Plugin
 */

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

/**
 * Main Plugin Class
 */
class NNAXFUF_Plugin
{
    const VERSION = '1.0.6';
    const SHOP_DOMAIN = 'https://www.expertonaut.de';

    /** @var NNAXFUF_Plugin */
    private static $instance = null;

    /** @var string */
    private $version = self::VERSION;
    /** @var string */
    private $rewrite_version = '6';

    /** @var string */
    private $plugin_dir;

    /** @var string */
    private $plugin_url;

    // Custom Post Types
    const CPT = 'nnaxfuf_user_file';
    const CPT_FOLDER = 'nnaxfuf_folder';

    // Metafelder
    const META_OWNER = '_nnaxfuf_owner_id';
    const META_FILEURL = '_nnaxfuf_file_url';
    const META_SHARED = '_nnaxfuf_shared_with';
    const META_SHARE_RULES = '_nnaxfuf_share_rules';
    const DOWNLOAD_VAR = 'nnaxfuf_download';
    const META_FILEPATH = '_nnaxfuf_file_path';

    // Einstellungen
    const OPTION_SETTINGS = 'nnaxfuf_settings';

    // Download-Endpoint
    const DOWNLOAD_ENDPOINT = 'nnaxfuf-download';

    // Ordnernavigation
    const FOLDER_VAR = 'nnaxfuf_folder';

    // Papierkorb
    const VIEW_VAR = 'nnaxfuf_view';

    // Listenfilter
    const FILTER_VAR = 'nnaxfuf_filter';

    // Paginierung
    const PAGED_VAR = 'nnaxfuf_paged';

    // Suche
    const SEARCH_VAR = 'nnaxfuf_s';

    // Dateityp-Filter
    const TYPE_VAR = 'nnaxfuf_type';

    // Sortierung
    const SORT_VAR = 'nnaxfuf_sort';
    const ORDER_VAR = 'nnaxfuf_order';

    // Listenansicht (Pagination an/aus)
    const SHOW_VAR = 'nnaxfuf_show';

    /**
     * Instance
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {
        $this->plugin_dir = plugin_dir_path(__FILE__);
        $this->plugin_url = plugin_dir_url(__FILE__);

        $this->define_constants();
        $this->includes();
        $this->init_components();
        add_action( 'init', array( $this, 'track_rewrite_notice_state' ), 99 );
        add_action( 'admin_init', array( $this, 'handle_rewrite_notice_actions' ) );
        add_action( 'admin_notices', array( $this, 'render_rewrite_notice' ) );

        // Activation / Deactivation
        register_activation_hook(__FILE__, array(__CLASS__, 'activate'));
        register_deactivation_hook(__FILE__, array(__CLASS__, 'deactivate'));
    }

    private function define_constants()
    {
        if (!defined('NNAXFUF_PLUGIN_PATH'))
            define('NNAXFUF_PLUGIN_PATH', $this->plugin_dir);
        if (!defined('NNAXFUF_PLUGIN_URL'))
            define('NNAXFUF_PLUGIN_URL', $this->plugin_url);
        if (!defined('NNAXFUF_PLUGIN_VERSION'))
            define('NNAXFUF_PLUGIN_VERSION', self::VERSION);
        if (!defined('NNAXFUF_SHOP_DOMAIN'))
            define('NNAXFUF_SHOP_DOMAIN', self::SHOP_DOMAIN);
        if (!defined('NNAXFUF_PLUGIN_BASENAME'))
            define('NNAXFUF_PLUGIN_BASENAME', plugin_basename(__FILE__));
    }

    private function includes()
    {
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-helpers.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-license-manager.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-cpt.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-assets.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-handlers.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-ajax.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-shortcode.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-settings.php';
        require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-meta-boxes.php';
    }

    private function init_components()
    {
        new NNAXFUF_License_Manager();
        new NNAXFUF_CPT();
        $assets = new NNAXFUF_Assets($this->version);
        $handlers = new NNAXFUF_Handlers();
        new NNAXFUF_AJAX();
        new NNAXFUF_Shortcode($handlers);
        new NNAXFUF_Settings( null, $assets );
        new NNAXFUF_Meta_Boxes();
    }

    public static function activate()
    {
        // CPT muss registriert sein, bevor flush_rewrite_rules
        $cpt = new NNAXFUF_CPT();
        $cpt->register_cpt();
        
        // Tabellen erstellen
        NNAXFUF_Helpers::setup_activity_table();

        flush_rewrite_rules();
        update_option( 'nnaxfuf_rewrite_rules_version', '6', false );
        update_option( 'nnaxfuf_needs_permalink_save', '1', false );
        delete_option( 'nnaxfuf_rewrite_notice_dismissed_for' );
        NNAXFUF_License_Manager::schedule_cron();
    }

    public static function deactivate()
    {
        flush_rewrite_rules();
        NNAXFUF_License_Manager::unschedule_cron();
    }

    public function track_rewrite_notice_state() {
        $option_key = 'nnaxfuf_rewrite_rules_version';
        $stored     = (string) get_option( $option_key, '' );

        if ( $stored !== $this->rewrite_version ) {
            update_option( $option_key, $this->rewrite_version, false );
            update_option( 'nnaxfuf_needs_permalink_save', '1', false );
            delete_option( 'nnaxfuf_rewrite_notice_dismissed_for' );
        }

        if ( $this->has_required_rewrite_rules() ) {
            update_option( 'nnaxfuf_needs_permalink_save', '0', false );
            delete_option( 'nnaxfuf_rewrite_notice_dismissed_for' );
        }
    }

    private function has_required_rewrite_rules() {
        $rules = get_option( 'rewrite_rules' );
        if ( ! is_array( $rules ) || empty( $rules ) ) {
            return false;
        }

        $rule_keys = implode( "\n", array_keys( $rules ) );
        $has_download = strpos( $rule_keys, '^' . self::DOWNLOAD_ENDPOINT . '/([0-9]+)' ) !== false;
        $has_zip      = strpos( $rule_keys, '^' . self::DOWNLOAD_ENDPOINT . '/zip/([^/]+)' ) !== false;
        $has_manager  = ( strpos( $rule_keys, '/nnaxfuf(?:/view/(trash))?' ) !== false )
            || ( strpos( $rule_keys, '^nnaxfuf(?:/view/(trash))?' ) !== false );

        return $has_download && $has_zip && $has_manager;
    }

    public function handle_rewrite_notice_actions() {
        if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
            return;
        }

        if ( empty( $_GET['nnaxfuf_dismiss_rewrite_notice'] ) ) {
            return;
        }

        check_admin_referer( 'nnaxfuf_dismiss_rewrite_notice' );

        update_option( 'nnaxfuf_rewrite_notice_dismissed_for', $this->rewrite_version, false );

        $redirect_url = remove_query_arg(
            array(
                'nnaxfuf_dismiss_rewrite_notice',
                '_wpnonce',
            )
        );
        wp_safe_redirect( $redirect_url );
        exit;
    }

    public function render_rewrite_notice() {
        if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $needs_save = get_option( 'nnaxfuf_needs_permalink_save', '0' ) === '1';
        if ( ! $needs_save ) {
            return;
        }

        $dismissed_for = (string) get_option( 'nnaxfuf_rewrite_notice_dismissed_for', '' );
        if ( $dismissed_for === $this->rewrite_version ) {
            return;
        }

        $permalink_url = admin_url( 'options-permalink.php' );
        $dismiss_url   = wp_nonce_url(
            add_query_arg( 'nnaxfuf_dismiss_rewrite_notice', '1' ),
            'nnaxfuf_dismiss_rewrite_notice'
        );

        echo '<div class="notice notice-warning">';
        echo '<p><strong>' . esc_html__( 'nnax Frontend User Files', 'nnax-frontend-user-files' ) . ':</strong> ';
        echo esc_html__( 'Please save your permalinks once so the new frontend URLs work correctly.', 'nnax-frontend-user-files' ) . '</p>';
        echo '<p><a class="button button-primary" href="' . esc_url( $permalink_url ) . '">' . esc_html__( 'Open Permalink Settings', 'nnax-frontend-user-files' ) . '</a> ';
        echo '<a class="button" href="' . esc_url( $dismiss_url ) . '">' . esc_html__( 'Dismiss for now', 'nnax-frontend-user-files' ) . '</a></p>';
        echo '</div>';
    }

}

NNAXFUF_Plugin::get_instance();
