<?php
/**
 * HtaccessModule — .htaccess management, security rules, backups.
 *
 * 6 admin pages: Dashboard, Security Rules, Backups, Security Events, Custom Rules, Settings.
 * No DB tables of its own (uses firewall security_logs for events).
 * All AJAX is handled by HtaccessAjax.
 *
 * @package UltraguardPro\modules\htaccess
 */

namespace UltraguardPro\modules\htaccess;

use UltraguardPro\modules\core\AbstractModule;

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

class HtaccessModule extends AbstractModule {

    /** This module requires a Pro license — gates is_enabled() in AbstractModule. */
    protected function requires_pro(): bool { return false; }

    public function get_id(): string { return 'htaccess'; }

    public function boot(): void {
        // 1. Register DB schema (change-log table).
        $db_tables = $this->plugin->modules->get_db_tables();
        if ( $db_tables ) {
            $db_tables->register_schema( new schema\HtaccessSchema() );
        }

        // 2. All AJAX handled by dedicated class.
        ( new ajax\HtaccessAjax( $this->plugin ) )->register();

        // 3. Register htaccess data into the dashboard registry.
        ( new HtaccessDashboardContributor( $this->plugin ) )->register();

        // 4. Admin pages.
        add_action( 'ultraguard_register_admin_pages', [ $this, 'register_pages' ], 40, 1 );

        // 5. Auto-backup on .htaccess update.
        add_action( 'ultraguard_htaccess_updated', [ $this, 'maybe_auto_backup' ] );

        // 6. Integrity check hook — lets external callers verify the file.
        add_filter( 'ultraguard_htaccess_verify_integrity', function () {
            $db     = $this->plugin->modules->get_db_tables();
            $table  = $db ? $db->get_table( 'htaccess_change_log' ) : null;
            return $table ? $table->verify_integrity() : null;
        } );

        do_action( 'ultraguard_pro/htaccess/booted', $this );
    }

    // ── Admin pages ────────────────────────────────────────────────────────────

    public function register_pages( $admin ): void {
        $admin->register_page( [
            'id'              => 'htaccess',
            'page_title'      => __( '.htaccess Manager', 'ultraguard-security-suite' ),
            'menu_title'      => __( '.htaccess', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ pages\HtaccessDashboard::class, $this->plugin ],
            'is_parent'       => true,
            'priority'        => 15,
            'group'           => 'Protection',
            'icon'            => 'dashicons-media-code',
        ] );

        $subpages = [
            [ 'id' => 'htaccess-security-rules',  'title' => __( 'Security Rules',    'ultraguard-security-suite' ), 'menu' => __( 'Security Rules',  'ultraguard-security-suite' ), 'class' => pages\HtaccessSecurityRules::class,  'p' => 16, 'icon' => 'dashicons-shield-alt'   ],
            [ 'id' => 'htaccess-backups',          'title' => __( '.htaccess Backups', 'ultraguard-security-suite' ), 'menu' => __( 'Backups',         'ultraguard-security-suite' ), 'class' => pages\HtaccessBackups::class,        'p' => 17, 'icon' => 'dashicons-backup'        ],
            [ 'id' => 'htaccess-security-events',  'title' => __( 'Security Events',   'ultraguard-security-suite' ), 'menu' => __( 'Security Events', 'ultraguard-security-suite' ), 'class' => pages\HtaccessSecurityEvents::class, 'p' => 18, 'icon' => 'dashicons-flag'          ],
            [ 'id' => 'htaccess-custom-rules',     'title' => __( 'Custom Rules',      'ultraguard-security-suite' ), 'menu' => __( 'Custom Rules',    'ultraguard-security-suite' ), 'class' => pages\HtaccessCustomRules::class,    'p' => 19, 'icon' => 'dashicons-editor-code'   ],
            [ 'id' => 'htaccess-change-log',       'title' => __( 'Change Log',        'ultraguard-security-suite' ), 'menu' => __( 'Change Log',      'ultraguard-security-suite' ), 'class' => pages\HtaccessChangeLog::class,      'p' => 20, 'icon' => 'dashicons-list-view'     ],
            [ 'id' => 'htaccess-settings',         'title' => __( '.htaccess Settings','ultraguard-security-suite' ), 'menu' => __( 'Settings',        'ultraguard-security-suite' ), 'class' => pages\HtaccessSettings::class,       'p' => 21, 'icon' => 'dashicons-admin-settings' ],
        ];

        foreach ( $subpages as $p ) {
            $admin->register_page( [
                'id'              => $p['id'],
                'page_title'      => $p['title'],
                'menu_title'      => $p['menu'],
                'capability'      => 'manage_options',
                'scheme_callback' => [ $p['class'], $this->plugin ],
                'parent_id'       => 'htaccess',
                'priority'        => $p['p'],
            'group'           => 'Protection',
                'icon'            => $p['icon'],
            ] );
        }
    }

    // ── Hooks ──────────────────────────────────────────────────────────────────

    public function maybe_auto_backup(): void {
        if ( \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_auto_backup_enabled', false ) ) {
            $path     = ABSPATH . '.htaccess';
            $dir      = trailingslashit( wp_upload_dir()['basedir'] ) . 'ultraguard-htaccess-backups/';
            wp_mkdir_p( $dir );
            $dest     = $dir . 'htaccess-auto-' . gmdate( 'Y-m-d-His' ) . '.txt';
            if ( file_exists( $path ) ) { @copy( $path, $dest ); }
        }
    }
}
