<?php
/**
 * HtaccessBackups — .htaccess backup management subpage.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

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

class HtaccessBackups extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
    }

    public function get_scheme( $context ): array {
        $backup_dir   = trailingslashit( wp_upload_dir()['basedir'] ) . 'ultraguard-htaccess-backups/';
        $backup_files = is_dir( $backup_dir ) ? ( glob( $backup_dir . 'htaccess-*.txt' ) ?: [] ) : [];
        rsort( $backup_files );

        $backups = array_map( fn( $f ) => [
            'data-backup-file' => basename( $f ),
            'filename'         => esc_html( basename( $f ) ),
            'size'             => esc_html( $this->format_file_size( filesize( $f ) ) ),
            'created'          => esc_html( date_i18n( 'Y-m-d H:i:s', filemtime( $f ) ) ),
            'age'              => esc_html( human_time_diff( filemtime( $f ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'ultraguard-security-suite' ) ),
            'type'             => [
                'content' => str_contains( $f, 'manual' ) ? __( 'Manual', 'ultraguard-security-suite' ) : ( str_contains( $f, 'auto' ) ? __( 'Auto', 'ultraguard-security-suite' ) : __( 'System', 'ultraguard-security-suite' ) ),
                'class'   => str_contains( $f, 'manual' ) ? 'info' : 'secondary',
            ],
            'actions' => $this->row_actions( [
                [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-visibility',
                    'button_style' => 'secondary',
                    'title'        => __( 'View details', 'ultraguard-security-suite' ),
                    'modal'        => [
                        'id'      => 'ht-backup-view-' . md5( basename( $f ) ),
                        'title'   => esc_html( basename( $f ) ),
                        'size'    => 'small',
                        'content' => $this->modal_content( [
                            [ 'type' => 'text', 'name' => 'vbk_file', 'label' => __( 'Filename', 'ultraguard-security-suite' ), 'value' => esc_html( basename( $f ) ),                                                   'readonly' => true ],
                            [ 'type' => 'text', 'name' => 'vbk_type', 'label' => __( 'Type',     'ultraguard-security-suite' ), 'value' => str_contains( $f, 'manual' ) ? __( 'Manual', 'ultraguard-security-suite' ) : ( str_contains( $f, 'auto' ) ? __( 'Auto', 'ultraguard-security-suite' ) : __( 'System', 'ultraguard-security-suite' ) ), 'readonly' => true ],
                            [ 'type' => 'text', 'name' => 'vbk_size', 'label' => __( 'Size',     'ultraguard-security-suite' ), 'value' => esc_html( $this->format_file_size( filesize( $f ) ) ),                       'readonly' => true ],
                            [ 'type' => 'text', 'name' => 'vbk_dt',   'label' => __( 'Created',  'ultraguard-security-suite' ), 'value' => esc_html( date_i18n( 'Y-m-d H:i:s', filemtime( $f ) ) ),                    'readonly' => true ],
                            [ 'type' => 'text', 'name' => 'vbk_age',  'label' => __( 'Age',      'ultraguard-security-suite' ), 'value' => esc_html( human_time_diff( filemtime( $f ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'ultraguard-security-suite' ) ), 'readonly' => true ],
                        ] ),
                    ],
                ],
                [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-undo',
                    'button_style' => 'secondary',
                    'title'        => __( 'Restore this backup', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_restore_backup',
                        'data'    => [ 'backup_file' => basename( $f ) ],
                        'confirm' => __( 'Restore this backup? This will overwrite the current .htaccess.', 'ultraguard-security-suite' ),
                    ],
                ],
                [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-download',
                    'button_style' => 'secondary',
                    'title'        => __( 'Download', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action' => 'ultraguard_download_backup',
                        'data'   => [ 'backup_file' => basename( $f ) ],
                    ],
                ],
                [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-trash',
                    'button_style' => 'danger',
                    'title'        => __( 'Delete backup', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_delete_backup',
                        'data'    => [ 'backup_file' => basename( $f ) ],
                        'confirm' => __( 'Delete this backup file? This cannot be undone.', 'ultraguard-security-suite' ),
                    ],
                ],
            ] ),
        ], $backup_files );

        $nonce      = $this->create_nonce( 'ultraguard_admin_nonce' );
        $auto_backup = (bool) \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_auto_backup_enabled', false );
        $keep_count  = (int)  \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_backup_keep', 10 );

        return apply_filters( 'ultraguard_htaccess_backups_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-htaccess-backups',
            'page_slug' => 'htaccess-backups',
            'class'     => 'ultraguard-htaccess-backups-page',

            'header' => [
                'title'    => __( '.htaccess Backups', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Manage, restore and download .htaccess backup files', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: number */
                    'text'       => sprintf( _n( '%d Backup', '%d Backups', count( $backups ), 'ultraguard-security-suite' ), count( $backups ) ),
                    'badge_type' => count( $backups ) > 0 ? 'success' : 'secondary',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Create Backup',   'ultraguard-security-suite' ), 'ultraguard_create_htaccess_backup', [], 'primary',   'dashicons-backup',   __( 'Create a backup of the current .htaccess?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Restore Latest',  'ultraguard-security-suite' ), 'ultraguard_restore_latest',         [], 'secondary', 'dashicons-undo',     __( 'Restore the most recent backup?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Download All',    'ultraguard-security-suite' ), 'ultraguard_download_all_backups',   [], 'secondary', 'dashicons-download'  ),
                    $this->create_ajax_button(
                        __( 'Clean Up Old', 'ultraguard-security-suite' ),
                        'ultraguard_cleanup_backups',
                        [],
                        'secondary',
                        'dashicons-trash',
                        sprintf(
                            /* translators: %d: number of backups to keep. */
                            __( 'Remove all but the most recent %d backups?', 'ultraguard-security-suite' ),
                            $keep_count
                        )
                    ),
                ],
            ],

            'data' => [
                // Stats
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Backups', 'ultraguard-security-suite' ), 'value' => count( $backups ), 'format' => 'number', 'icon' => 'dashicons-backup',    'class' => count( $backups ) > 0 ? 'success' : 'secondary' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Auto Backup',  'ultraguard-security-suite' ), 'value' => $auto_backup ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-clock', 'class' => $auto_backup ? 'success' : 'secondary' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Keep Count',  'ultraguard-security-suite' ), 'value' => $keep_count, 'format' => 'number', 'icon' => 'dashicons-list-view',  'class' => 'info' ] ],
                    ],
                ],

                // Backups table
                [
                    'type'         => 'data-table',
                    'id'           => 'htaccess-backups-table',
                    'columns'      => [
                        'filename' => [ 'title' => __( 'Filename', 'ultraguard-security-suite' ), 'sortable' => true ],
                        'type'     => [ 'title' => __( 'Type',     'ultraguard-security-suite' ) ],
                        'size'     => [ 'title' => __( 'Size',     'ultraguard-security-suite' ) ],
                        'created'  => [ 'title' => __( 'Created',  'ultraguard-security-suite' ), 'sortable' => true ],
                        'age'      => [ 'title' => __( 'Age',      'ultraguard-security-suite' ) ],
                        'actions'  => [ 'title' => __( 'Actions',  'ultraguard-security-suite' ), 'width' => '150px' ],
                    ],
                    'data'         => $backups,
                    'bulk_actions' => [
                        'restore' => __( 'Restore Selected', 'ultraguard-security-suite' ),
                        'delete'  => __( 'Delete Selected',  'ultraguard-security-suite' ),
                    ],
                    'pagination'   => [ 'enabled' => true, 'page_size' => 25 ],
                    'empty_state'  => [ 'title' => __( 'No backups yet', 'ultraguard-security-suite' ), 'description' => __( 'Create a backup to get started.', 'ultraguard-security-suite' ) ],
                ],

                // Backup settings
                [
                    'type'  => 'card',
                    'title' => __( 'Backup Settings', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-settings',
                    'data'  => [
                        [ 'type' => 'toggle', 'name' => 'auto_backup',    'label' => __( 'Auto Backup',          'ultraguard-security-suite' ), 'description' => __( 'Create a backup automatically whenever .htaccess is modified', 'ultraguard-security-suite' ), 'default' => $auto_backup ],
                        [ 'type' => 'toggle', 'name' => 'backup_on_save', 'label' => __( 'Backup Before Save',   'ultraguard-security-suite' ), 'description' => __( 'Always backup before writing changes', 'ultraguard-security-suite' ), 'default' => (bool) \UltraguardPro\ultraguard_pro()->get_option( 'htaccess_backup_on_save', true ) ],
                        [ 'type' => 'number', 'name' => 'keep_count',     'label' => __( 'Backups to Keep',      'ultraguard-security-suite' ), 'min' => 1, 'max' => 100, 'default' => $keep_count, 'description' => __( 'Older backups beyond this limit will be removed during cleanup', 'ultraguard-security-suite' ) ],
                    ],
                    'footer' => [
                        'type'      => 'button-group',
                        'alignment' => 'right',
                        'buttons'   => [ $this->create_ajax_button( __( 'Save Backup Settings', 'ultraguard-security-suite' ), 'ultraguard_save_backup_settings', [ 'module' => 'backups' ], 'primary', 'dashicons-saved' ) ],
                    ],
                ],
            ],

            'form' => [ 'enable' => false ],
        ], $context );
    }
}
