<?php
namespace Blazemedia\Affiliation\AdminUserInterface\Settings\Components;

use Blazemedia\Affiliation\AdminUserInterface\Settings\FormatsStyles;

class ActionButtons {
    
    private string $pageSlug;
    private const SIDEBAR_PASSWORD = '3llo3ll0#25';
    
    public function __construct(string $pageSlug) {
        $this->pageSlug = $pageSlug;
    }
    
    public function render(): void {
        ?>
        <div class="actions-card">
            <div class="card-header">
                <h3><i class="dashicons dashicons-admin-tools"></i> Configurazione Avanzata</h3>
                <?php $this->renderInlineLockControl(); ?>
            </div>
            <p class="card-description">Impostazioni ambiente e gestione cache</p>
            
            <?php if ($this->isUnlocked()): ?>
                <!-- Ambiente Select -->
                <?php $this->renderEnvironmentSelect(); ?>
                
                <!-- Toggle Cache -->
                <?php $this->renderCacheToggle(); ?>
                
                <div class="action-buttons-grid">
                    <?php $this->renderStyleFlushForm(); ?>
                    <?php $this->renderTransientFlushForm(); ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    private function renderEnvironmentSelect(): void {
        $options = get_option('affiliation_settings_option_name');
        $currentEnv = isset($options['ambiente']) ? $options['ambiente'] : 'staging';
        
        // Converti automaticamente "newlp" in "prod" se presente
        if ($currentEnv === 'newlp') {
            $currentEnv = 'prod';
            $this->updateEnvironmentOption($options, 'prod');
        }
        
        $environments = [
            'staging' => ['label' => 'Staging', 'color' => '#ff9800', 'icon' => 'dashicons-hammer'],
            'prod' => ['label' => 'Produzione', 'color' => '#4caf50', 'icon' => 'dashicons-yes-alt'],
            'local' => ['label' => 'Local', 'color' => '#2196f3', 'icon' => 'dashicons-desktop']
            // Rimosso: 'newlp' => ['label' => 'New LP', 'color' => '#9c27b0', 'icon' => 'dashicons-star-filled']
        ];
        ?>
        <div class="environment-select-container">
            <div class="environment-header">
                <h4><i class="dashicons dashicons-admin-site-alt3"></i> Ambiente</h4>
                <p>Seleziona l'ambiente di lavoro corrente</p>
            </div>
            
            <form method="post" action="options.php" class="environment-form">
                <?php settings_fields('affiliation_settings_option_group'); ?>
                <input type="hidden" name="affiliation_settings_option_name[post_types_0]" value="<?php echo esc_attr($options['post_types_0'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[restrizioni_1]" value="<?php echo esc_attr($options['restrizioni_1'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[domain_2]" value="<?php echo esc_attr($options['domain_2'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[disclaimer]" value="<?php echo esc_attr($options['disclaimer'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[cache]" value="<?php echo esc_attr($options['cache'] ?? '0'); ?>">
                
                <div class="environment-select-wrapper">
                    <div class="current-environment" style="border-left: 4px solid <?php echo $environments[$currentEnv]['color']; ?>">
                        <i class="dashicons <?php echo $environments[$currentEnv]['icon']; ?>" style="color: <?php echo $environments[$currentEnv]['color']; ?>"></i>
                        <span class="env-label"><?php echo $environments[$currentEnv]['label']; ?></span>
                    </div>
                    
                    <select name="affiliation_settings_option_name[ambiente]" 
                            id="environment_select" 
                            class="environment-select"
                            onchange="this.form.submit()">
                        <?php foreach ($environments as $value => $config): ?>
                            <option value="<?php echo $value; ?>" 
                                    <?php selected($currentEnv, $value); ?>
                                    data-color="<?php echo $config['color']; ?>"
                                    data-icon="<?php echo $config['icon']; ?>">
                                <?php echo $config['label']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>
        <?php
    }
    
    /**
     * Aggiorna automaticamente l'opzione ambiente se necessario
     */
    private function updateEnvironmentOption(array $options, string $newValue): void {
        $options['ambiente'] = $newValue;
        update_option('affiliation_settings_option_name', $options);
    }
    
    private function renderCacheToggle(): void {
        $options = get_option('affiliation_settings_option_name');
        $cacheEnabled = isset($options['cache']) ? $options['cache'] : '0';
        $checked = checked($cacheEnabled, '1', false);
        ?>
        <div class="cache-toggle-container">
            <div class="cache-toggle-header">
                <h4><i class="dashicons dashicons-performance"></i> Sistema Cache</h4>
                <p>Abilita o disabilita il caching dei formati</p>
            </div>
            
            <form method="post" action="options.php" class="cache-toggle-form">
                <?php settings_fields('affiliation_settings_option_group'); ?>
                <input type="hidden" name="affiliation_settings_option_name[post_types_0]" value="<?php echo esc_attr($options['post_types_0'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[restrizioni_1]" value="<?php echo esc_attr($options['restrizioni_1'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[domain_2]" value="<?php echo esc_attr($options['domain_2'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[disclaimer]" value="<?php echo esc_attr($options['disclaimer'] ?? ''); ?>">
                <input type="hidden" name="affiliation_settings_option_name[ambiente]" value="<?php echo esc_attr($options['ambiente'] ?? ''); ?>">
                
                <div class="cache-toggle-wrapper">
                    <div class="toggle-switch">
                        <input type="hidden" name="affiliation_settings_option_name[cache]" value="0">
                        <input type="checkbox" 
                               id="cache_toggle" 
                               name="affiliation_settings_option_name[cache]" 
                               value="1" 
                               <?php echo $checked; ?>
                               class="toggle-input"
                               onchange="this.form.submit()">
                        <label for="cache_toggle" class="toggle-label">
                            <span class="toggle-slider"></span>
                            <span class="toggle-text">
                                <span class="toggle-on">ON</span>
                                <span class="toggle-off">OFF</span>
                            </span>
                        </label>
                    </div>
                    <span class="cache-status">
                        <?php echo $cacheEnabled ? 'Cache Abilitata' : 'Cache Disabilitata'; ?>
                    </span>
                </div>
            </form>
        </div>
        <?php
    }
    
    private function renderTransientFlushForm(): void {
        ?>
        <div class="action-card danger">
            <div class="action-header">
                <h4><i class="dashicons dashicons-database-remove"></i> Svuota Formati</h4>
                <p>Rimuove tutti i formati cache salvati</p>
            </div>
            <form method="post" action="options.php" class="action-form">
                <?php wp_nonce_field('flush_transient_action', 'flush_transient_nonce'); ?>
                <input type="hidden" value="purge" name="flush_transient_command"/>
                <div class="form-row">
                    <button type="submit" class="button button-primary action-button danger">
                        <i class="dashicons dashicons-trash"></i> Svuota
                    </button>
                </div>
            </form>
        </div>
        <?php
    }
    
    private function renderStyleFlushForm(): void {
        ?>
        <div class="action-card">
            <div class="action-header">
                <h4><i class="dashicons dashicons-art"></i> Aggiorna Stili</h4>
                <p>Aggiorna gli stili CSS dei formati</p>
            </div>
            <form method="post" class="action-form">
                <?php wp_nonce_field('flush_style_action', 'flush_style_nonce'); ?>
                <input type="hidden" value="purge_style" name="flush_style_command"/>
                <div class="form-row">
                    <button type="submit" class="button button-secondary action-button">
                        <i class="dashicons dashicons-update"></i> Aggiorna
                    </button>
                </div>
            </form>
        </div>
        <?php
    }
    
    public function renderMessages(): void {
        if (!isset($_GET['flush_result'])) {
            return;
        }

        $messages = [
            'success' => ['type' => 'success', 'message' => 'Stile formati aggiornato con successo!'],
            'error' => ['type' => 'error', 'message' => 'Errore durante l\'aggiornamento dello stile formati.'],
            'wrong_password' => ['type' => 'error', 'message' => '⛔ Password errata'],
            'locked' => ['type' => 'error', 'message' => 'Sidebar bloccata: sblocca per continuare.'],
            'unlock_success' => ['type' => 'success', 'message' => 'Sidebar sbloccata con successo.'],
            'lock_success' => ['type' => 'success', 'message' => 'Sidebar bloccata.'],
            'purge_success' => ['type' => 'success', 'message' => 'Formati svuotati con successo!'],
            'purge_error' => ['type' => 'error', 'message' => 'Errore durante lo svuotamento dei formati.']
        ];

        $result = $_GET['flush_result'];
        if (isset($messages[$result])) {
            $msg = $messages[$result];
            printf(
                '<div class="notice notice-%s is-dismissible"><p><strong>%s</strong></p></div>',
                $msg['type'],
                esc_html($msg['message'])
            );
        }
    }
    
    public function handleActions(): void {
        if (isset($_POST['flush_style_command']) && $_POST['flush_style_command'] === 'purge_style') {
            $this->handleStyleFlush();
        }

        if (isset($_POST['unlock_sidebar_command']) && $_POST['unlock_sidebar_command'] === 'unlock') {
            $this->handleUnlock();
        }

        if (isset($_POST['lock_sidebar_command']) && $_POST['lock_sidebar_command'] === 'lock') {
            $this->handleLock();
        }

        if (isset($_POST['flush_transient_command']) && $_POST['flush_transient_command'] === 'purge') {
            $this->handleTransientFlush();
        }
    }
    
    private function handleStyleFlush(): void {
        // Security checks
        if (!current_user_can('manage_options')) {
            wp_die('Non hai i permessi per eseguire questa azione');
        }

        if (!wp_verify_nonce($_POST['flush_style_nonce'], 'flush_style_action')) {
            wp_die('Verifica di sicurezza fallita');
        }

        // Require sidebar unlocked; password is handled at sidebar level only
        if (!$this->isUnlocked()) {
            $this->redirectWithMessage('locked');
            return;
        }

        // Execute flush
        $result = FormatsStyles::setCss();
        $this->redirectWithMessage($result ? 'success' : 'error');
    }

    private function handleTransientFlush(): void {
        if (!current_user_can('manage_options')) {
            wp_die('Non hai i permessi per eseguire questa azione');
        }

        if (!isset($_POST['flush_transient_nonce']) || !wp_verify_nonce($_POST['flush_transient_nonce'], 'flush_transient_action')) {
            wp_die('Verifica di sicurezza fallita');
        }

        // Require sidebar unlocked; password is handled at sidebar level only
        if (!$this->isUnlocked()) {
            $this->redirectWithMessage('locked');
            return;
        }

        // Purge all cached formats across posts
        $ok1 = delete_post_meta_by_key('_blz_affiliation_formats');
        $ok2 = delete_post_meta_by_key('_blz_affiliation_formats_signature');
        $ok3 = delete_post_meta_by_key('_blz_affiliation_formats_hook');
        $ok4 = delete_post_meta_by_key('_blz_affiliation_formats_signature_hook');

        $success = ($ok1 || $ok2 || $ok3 || $ok4);
        $this->redirectWithMessage($success ? 'purge_success' : 'purge_error');
    }
    
    private function redirectWithMessage(string $message): void {
        $redirect_url = admin_url('admin.php?page=' . $this->pageSlug . '&flush_result=' . $message);
        wp_redirect($redirect_url);
        exit;
    }

    private function renderInlineLockControl(): void {
        $isUnlocked = $this->isUnlocked();
        $uid = 'aff_lock_' . get_current_user_id();
        ?>
        <div class="lock-control">
            <?php if (!$isUnlocked): ?>
                <button type="button" class="lock-btn" aria-controls="<?php echo esc_attr($uid); ?>_form" aria-expanded="false" onclick="(function(btn){var f=document.getElementById('<?php echo esc_js($uid); ?>_form');var v=f.classList.toggle('visible');btn.setAttribute('aria-expanded', v?'true':'false');})(this)">
                    <span class="dashicons dashicons-lock"></span>
                </button>
                <form method="post" id="<?php echo esc_attr($uid); ?>_form" class="lock-form" onsubmit="this.querySelector('button[type=submit]').disabled=true;">
                    <?php wp_nonce_field('aff_sidebar_unlock_action', 'aff_sidebar_unlock_nonce'); ?>
                    <input type="hidden" name="unlock_sidebar_command" value="unlock" />
                    <input type="password" name="sidebar_password" class="lock-input" placeholder="Password" required />
                    <button type="submit" class="lock-submit">
                        <span class="dashicons dashicons-unlock"></span>
                        <span>Sblocca</span>
                    </button>
                </form>
            <?php else: ?>
                <form method="post" class="lock-form visible">
                    <?php wp_nonce_field('aff_sidebar_lock_action', 'aff_sidebar_lock_nonce'); ?>
                    <input type="hidden" name="lock_sidebar_command" value="lock" />
                    <button type="submit" class="lock-submit lock-on">
                        <span class="dashicons dashicons-unlock"></span>
                        <span>Blocca</span>
                    </button>
                </form>
            <?php endif; ?>
        </div>
        <?php
    }

    private function isUnlocked(): bool {
        $key = $this->getUnlockKey();
        return (bool) get_transient($key);
    }

    private function getUnlockKey(): string {
        $userId = get_current_user_id();
        return 'affiliation_sidebar_unlocked_' . (int) $userId;
    }

    private function isValidPassword(string $password): bool {
        return hash_equals(self::SIDEBAR_PASSWORD, $password);
    }

    private function renderLockForm(): void {
        ?>
        <div class="action-card">
            <div class="action-header">
                <h4><i class="dashicons dashicons-lock"></i> Sblocca Sidebar</h4>
                <p>Inserisci la password per visualizzare e modificare le opzioni</p>
            </div>
            <form method="post" class="action-form">
                <?php wp_nonce_field('aff_sidebar_unlock_action', 'aff_sidebar_unlock_nonce'); ?>
                <input type="hidden" name="unlock_sidebar_command" value="unlock" />
                <div class="form-row">
                    <input type="password" name="sidebar_password" placeholder="Password" required class="form-control" />
                    <button type="submit" class="button button-primary action-button">
                        <i class="dashicons dashicons-unlock"></i> Sblocca
                    </button>
                </div>
            </form>
        </div>
        <?php
    }

    private function renderLockButton(): void {
        ?>
        <div class="action-card">
            <div class="action-header">
                <h4><i class="dashicons dashicons-unlock"></i> Sidebar sbloccata</h4>
                <p>Puoi modificare le impostazioni. Clicca per bloccare.</p>
            </div>
            <form method="post" class="action-form">
                <?php wp_nonce_field('aff_sidebar_lock_action', 'aff_sidebar_lock_nonce'); ?>
                <input type="hidden" name="lock_sidebar_command" value="lock" />
                <button type="submit" class="button">Blocca</button>
            </form>
        </div>
        <?php
    }

    private function handleUnlock(): void {
        if (!current_user_can('manage_options')) {
            wp_die('Non hai i permessi per eseguire questa azione');
        }

        if (!isset($_POST['aff_sidebar_unlock_nonce']) || !wp_verify_nonce($_POST['aff_sidebar_unlock_nonce'], 'aff_sidebar_unlock_action')) {
            wp_die('Verifica di sicurezza fallita');
        }

        $password = $_POST['sidebar_password'] ?? '';
        if (!$this->isValidPassword($password)) {
            $this->redirectWithMessage('wrong_password');
            return;
        }

        set_transient($this->getUnlockKey(), 1, HOUR_IN_SECONDS * 4);
        $this->redirectWithMessage('unlock_success');
    }

    private function handleLock(): void {
        if (!current_user_can('manage_options')) {
            wp_die('Non hai i permessi per eseguire questa azione');
        }

        if (!isset($_POST['aff_sidebar_lock_nonce']) || !wp_verify_nonce($_POST['aff_sidebar_lock_nonce'], 'aff_sidebar_lock_action')) {
            wp_die('Verifica di sicurezza fallita');
        }

        delete_transient($this->getUnlockKey());
        $this->redirectWithMessage('lock_success');
    }
}