<?php
/**
 * Protected Forms Table Template - Edge-to-Edge Light Dashboard
 * 
 * This template displays the protected forms dashboard with edge-to-edge light UI
 * Sections are divided by lines, not cards
 */

if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

// CSS и JS се зареждат автоматично от formshield.php

$options = form_shield()->get_options();
$forms_data = FormShieldForms::get_forms();

// Flatten the forms array for counting
$forms = array();
$protected_forms = array();

if (isset($forms_data['scanner'])) {
    $forms[] = $forms_data['scanner'];
    $protected_forms[] = $forms_data['scanner']; // Scanner is always protected
}

if (isset($forms_data['comments']) && is_array($forms_data['comments'])) {
    foreach ($forms_data['comments'] as $comment_form) {
        $forms[] = $comment_form;
        $protected_forms[] = $comment_form; // Comments are always protected
    }
}

if (isset($forms_data['plugins']) && is_array($forms_data['plugins'])) {
    foreach ($forms_data['plugins'] as $plugin_form) {
        $forms[] = $plugin_form;
        if (isset($plugin_form['enabled']) && $plugin_form['enabled'] == 1) {
            $protected_forms[] = $plugin_form;
        }
    }
}

// Вземи последните атаки
$blocked_attempts = isset($options['blocked_attempts']) ? intval($options['blocked_attempts']) : 0;
$last_attack = isset($options['last_attack']) ? $options['last_attack'] : '';
$attack_types = isset($options['attack_types']) ? $options['attack_types'] : array(
    'spam' => 0,
    'bot' => 0,
    'injection' => 0,
    'other' => 0
);

// Изчисли процента на защита - показва колко форми са защитени
$protection_percentage = count($forms) > 0 ? round((count($protected_forms) / count($forms)) * 100) : 0;

// ajaxConfig is already localized in formshield.php
?>

<div class="plugin-dashboard">
    <div class="dashboard-header">
        <h1><?php esc_html_e('Protected Forms — Dashboard', 'formshield'); ?></h1>
        <p class="subtitle"><?php esc_html_e('Monitor all protected forms on your site in real-time. Here you can view protection summary, latest scans, and detailed information for each form.', 'formshield'); ?></p>
    </div>
    
    <div class="dashboard-grid">
        <div class="dashboard-section">
            <h2>Protection Summary</h2>
            <div class="progress-container">
                <div class="progress-bar"><span style="width:<?php echo esc_attr($protection_percentage); ?>%"></span></div>
                <div class="progress-value"><?php echo esc_html($protection_percentage); ?>% <span class="small"><?php esc_html_e('Attack Protection', 'formshield'); ?></span></div>
                    </div>
            <div class="stats-meta">
                <span><?php echo esc_html(count($forms)); ?> Total Form<?php echo count($forms) !== 1 ? 's' : ''; ?></span>
                <span><?php echo esc_html(count($protected_forms)); ?> Protected</span>
                </div>
                                </div>

        <div class="dashboard-section">
            <h2>Analytics Overview</h2>
            <div class="analytics">
                <div><label>Forms Protected</label><strong><?php echo esc_html(count($protected_forms)); ?></strong></div>
                <div><label>Attacks Blocked</label><strong><?php echo esc_html($blocked_attempts); ?></strong></div>
                <div><label>Protection Rate</label><strong><?php echo esc_html($protection_percentage); ?>%</strong></div>
                <div><label>Uptime</label><strong><?php echo esc_html(FormShieldForms::get_uptime_percentage()); ?>%</strong></div>
                            </div>
                                </div>
        
        <div class="dashboard-section">
            <h2>Form Detection</h2>
            <div class="button-stack">
                <button class="btn-secondary" id="rescan-forms-btn"><?php esc_html_e('🔄 Rescan All Forms', 'formshield'); ?></button>
                <p class="note"><?php esc_html_e('Use this tool to refresh the protected forms list.', 'formshield'); ?></p>
                
                <?php
                $options = get_option('formshield_options', array());
                $last_scan_time = isset($options['last_scan_time']) ? $options['last_scan_time'] : '';
                $last_scan_timestamp = isset($options['last_scan_timestamp']) ? $options['last_scan_timestamp'] : '';
                ?>
                
                <div class="last-scan-info">
                    <label>Последно търсене:</label>
                    <?php if ($last_scan_time): ?>
                        <span class="last-scan-time">
                            <?php echo esc_html(date_i18n('d.m.Y H:i', $last_scan_timestamp ?: strtotime($last_scan_time))); ?>
                            </span>
                            <?php else: ?>
                        <span class="last-scan-time"><?php esc_html_e('Не е сканирано', 'formshield'); ?></span>
                            <?php endif; ?>
        </div>

                <div id="scan-results" style="display: none;">
                    <div class="scan-status"><?php esc_html_e('Ready to scan', 'formshield'); ?></div>
                    <div class="scan-details"><?php esc_html_e('Click rescan button to start', 'formshield'); ?></div>
                </div>
            </div>
        </div>

        <div class="dashboard-section protected-forms full-span">
            <h2></h2>
            <?php if (!empty($forms)): ?>
                <!-- Секция 1: Скенер -->
                <?php if (isset($forms_data['scanner'])): ?>
                <div class="forms-section">
                    <h3 class="section-title"><?php esc_html_e('🔍 Система за сканиране', 'formshield'); ?></h3>
                    <div class="scanner-info">
                        <div class="scanner-status-large"><?php esc_html_e('🔍 Always Active', 'formshield'); ?></div>
                        <div class="scanner-description">
                            <p><strong><?php esc_html_e('Скенер на сайта', 'formshield'); ?></strong> - <?php esc_html_e('Автоматична защитна система', 'formshield'); ?></p>
                            <p><?php esc_html_e('Работи 24/7 за защита на всички форми на сайта. Не се нуждае от ръчно управление.', 'formshield'); ?></p>
                    </div>
                    </div>
                    </div>
                <?php endif; ?>
                
                <!-- Секция 2: Коментари -->
                <?php if (isset($forms_data['comments']) && !empty($forms_data['comments'])): ?>
                <div class="forms-section">
                    <h3 class="section-title"><?php esc_html_e('💬 Коментари (винаги защитени)', 'formshield'); ?></h3>
                    <table class="forms-table">
                        <thead>
                            <tr>
                                <th>Status</th>
                                <th>Form Name</th>
                                <th>Type</th>
                                <th>Blocked Attempts</th>
                                <th>Activity</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($forms_data['comments'] as $form): ?>
                            <tr>
                                <td>
                                    <div class="formshield-toggle-wrapper">
                                        <span class="comments-status"><?php esc_html_e('💬 Always Protected', 'formshield'); ?></span>
                                    </div>
                                </td>
                                <td><?php echo esc_html($form['name']); ?></td>
                                <td><span class="tag"><?php echo esc_html($form['type']); ?></span></td>
                                <td><?php echo esc_html(isset($form['blocked_attempts']) ? $form['blocked_attempts'] : 0); ?></td>
                                <td>
                                    <div class="activity-info">
                                        <span class="activity-text"><?php echo esc_html(isset($form['activity']) ? $form['activity'] : __('No activity', 'formshield')); ?></span>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
                
                <!-- Секция 3: Плъгини и форми - ВИНАГИ ВИДИМА -->
                <div class="forms-section">
                    <div class="section-header">
                        <h3 class="section-title"><?php esc_html_e('🔌 Плъгини и форми за защита', 'formshield'); ?></h3>
                        <div class="auto-save-indicator">
                            <span class="auto-save-text"><?php esc_html_e('Auto-save enabled', 'formshield'); ?></span>
                            <span class="auto-save-icon">💾</span>
                        </div>
                    </div>
                    <?php if (isset($forms_data['plugins']) && !empty($forms_data['plugins'])): ?>
                        <table class="forms-table">
                            <thead>
                                <tr>
                                    <th>Enabled</th>
                                    <th>Form Name</th>
                                    <th>Type</th>
                                    <th>Blocked Attempts</th>
                                    <th>Activity</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($forms_data['plugins'] as $form): ?>
                                <tr>
                                    <td>
                                        <div class="formshield-toggle-wrapper">
                                            <label class="switch">
                                                <input type="checkbox" 
                                                       class="formshield-toggle" 
                                                       data-form-id="<?php echo esc_attr($form['id']); ?>" 
                                                       <?php checked(isset($form['enabled']) && $form['enabled'] == 1, true); ?>>
                                                <span class="slider"></span>
                                            </label>
                                            <span class="toggle-status <?php echo (isset($form['enabled']) && $form['enabled'] == 1) ? 'enabled' : 'disabled'; ?>">
                                                <?php echo (isset($form['enabled']) && $form['enabled'] == 1) ? 'Enabled' : 'Disabled'; ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td><?php echo esc_html($form['name']); ?></td>
                                    <td><span class="tag"><?php echo esc_html($form['type']); ?></span></td>
                                    <td><?php echo esc_html(isset($form['blocked_attempts']) ? $form['blocked_attempts'] : 0); ?></td>
                                    <td>
                                        <div class="activity-info">
                                            <span class="activity-text"><?php echo esc_html(isset($form['activity']) ? $form['activity'] : __('No activity', 'formshield')); ?></span>
                                            <button type="button" class="formshield-stats-btn" data-form-id="<?php echo esc_attr($form['id']); ?>" title="<?php esc_html_e('View Form Statistics', 'formshield'); ?>">
                                                <span class="activity-icon">📊</span>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <!-- Съобщение когато няма форми -->
                        <div class="no-forms-message">
                            <div class="no-forms-icon">🔍</div>
                            <h4><?php esc_html_e('Няма открити форми', 'formshield'); ?></h4>
                            <p><?php esc_html_e('В момента няма открити форми от плъгини за защита. Използвайте бутона "Rescan All Forms" по-горе, за да сканирате сайта за нови форми.', 'formshield'); ?></p>
                            <div class="no-forms-actions">
                                <button class="btn btn-primary" onclick="document.getElementById('rescan-forms-btn').click()">
                                    <?php esc_html_e('🔄 Сканирай за форми', 'formshield'); ?>
                                </button>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                <?php else: ?>
                <div style="text-align: center; padding: 40px 20px; color: var(--muted);">
                    <p>No forms detected yet. Use the scan tools above to find forms on your site.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>


            </div>

<!-- Form Details Popup -->
<div id="form-details-popup" class="popup-overlay" style="display: none;">
    <div class="popup-content">
        <div class="popup-header">
            <h3 id="popup-form-name"><?php esc_html_e('Form Details', 'formshield'); ?></h3>
            <button type="button" class="popup-close" onclick="closeFormDetailsPopup()">&times;</button>
        </div>
        <div class="popup-body">
            <div class="form-details-grid">
                <div class="detail-item">
                    <label>Form ID:</label>
                    <span id="popup-form-id">-</span>
                </div>
                <div class="detail-item">
                    <label><?php esc_html_e('Type:', 'formshield'); ?></label>
                    <span id="popup-form-type">-</span>
            </div>
            
                <div class="detail-item">
                    <label><?php esc_html_e('Status:', 'formshield'); ?></label>
                    <span id="popup-form-status">-</span>
            </div>
                <div class="detail-item">
                    <label><?php esc_html_e('Blocked Attempts:', 'formshield'); ?></label>
                    <span id="popup-blocked-attempts">-</span>
                </div>
                <div class="detail-item">
                    <label><?php esc_html_e('Last Activity:', 'formshield'); ?></label>
                    <span id="popup-last-activity">-</span>
                </div>
                </div>
            <div class="popup-actions">
                <button type="button" class="btn btn-secondary" onclick="viewFormLogs()"><?php esc_html_e('View Logs', 'formshield'); ?></button>
                <button type="button" class="btn btn-secondary" onclick="exportFormData()"><?php esc_html_e('Export Data', 'formshield'); ?></button>
            </div>
        </div>
    </div>
</div>

<?php
// Enqueue admin styles and scripts with high priority to override main CSS
wp_enqueue_style( 'formshield-admin-override', plugins_url( 'css/admin.css', dirname(__FILE__) ), array('formshield-admin'), FORMSHIELD_VERSION . '.' . time() );
wp_enqueue_script( 'formshield-admin-forms-table', plugins_url( 'js/protected-forms-table.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION . '.' . time(), true );

// Localize script with AJAX data
wp_localize_script( 'formshield-admin-forms-table', 'ajaxConfig', array(
    'url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('formshield_protection'),
    'saveToggleNonce' => wp_create_nonce('formshield_save_toggle_changes'),
    'rescanNonce' => wp_create_nonce('formsh_rescan_forms')
) );
?>


