<?php
if (!defined('ABSPATH')) exit;

$server_url = get_option('auctionforge_update_server_url', 'https://wpdeploy.smoothbyteit.dev');
$api_key = get_option('auctionforge_update_api_key', '');
$auto_update = get_option('auctionforge_auto_update', true);
$is_registered = !empty($api_key);
$nonce = wp_create_nonce('auctionforge_admin');
?>
<style>
    .af-upd-wrap { max-width: 900px; margin: 20px auto 40px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    .af-upd-wrap h1 { font-size: 24px; font-weight: 600; margin-bottom: 5px; display: flex; align-items: center; gap: 10px; }
    .af-upd-wrap h1 .dashicons { font-size: 28px; width: 28px; height: 28px; color: #2271b1; }
    .af-upd-wrap .af-upd-subtitle { color: #666; margin-bottom: 24px; font-size: 14px; }

    .af-upd-card { background: #fff; border: 1px solid #ddd; border-radius: 6px; padding: 24px 28px; margin-bottom: 20px; }
    .af-upd-card-header { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid #eee; }
    .af-upd-card-header .dashicons { font-size: 20px; width: 20px; height: 20px; color: #2271b1; }
    .af-upd-card-header h2 { font-size: 16px; font-weight: 600; margin: 0; }

    .af-upd-status { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 4px; font-size: 13px; font-weight: 500; margin-bottom: 16px; }
    .af-upd-status.connected { background: #d4edda; color: #155724; border: 1px solid #a3d9a5; }
    .af-upd-status.disconnected { background: #fff3cd; color: #856404; border: 1px solid #ffc107; }
    .af-upd-status .dashicons { font-size: 16px; width: 16px; height: 16px; }

    .af-upd-field { margin-bottom: 16px; }
    .af-upd-field label { display: block; font-weight: 600; font-size: 13px; color: #333; margin-bottom: 6px; }
    .af-upd-field input[type="url"],
    .af-upd-field input[type="text"] { width: 100%; max-width: 500px; padding: 8px 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
    .af-upd-field input:focus { border-color: #2271b1; box-shadow: 0 0 0 1px #2271b1; outline: none; }
    .af-upd-field .description { color: #888; font-size: 12px; margin-top: 4px; }

    .af-upd-info-table { width: 100%; border-collapse: collapse; font-size: 13px; }
    .af-upd-info-table th { text-align: left; padding: 8px 12px; background: #f7f7f7; border: 1px solid #e5e5e5; font-weight: 600; color: #333; width: 160px; }
    .af-upd-info-table td { padding: 8px 12px; border: 1px solid #e5e5e5; color: #444; }
    .af-upd-info-table code { background: #f0f0f1; padding: 2px 8px; border-radius: 3px; font-size: 12px; }

    .af-upd-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; }
    .af-upd-actions .button { display: inline-flex; align-items: center; gap: 4px; }
    .af-upd-actions .button .dashicons { font-size: 16px; width: 16px; height: 16px; margin-top: 2px; }

    .af-upd-result { margin-top: 16px; padding: 10px 14px; border-radius: 4px; font-size: 13px; display: none; }
    .af-upd-result.success { background: #d4edda; color: #155724; border: 1px solid #a3d9a5; display: block; }
    .af-upd-result.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; display: block; }
    .af-upd-result.info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; display: block; }

    .af-upd-divider { border: 0; border-top: 1px solid #eee; margin: 20px 0; }

    .af-upd-checkbox-row { display: flex; align-items: center; gap: 8px; }
    .af-upd-checkbox-row label { font-weight: 400; font-size: 14px; margin-bottom: 0; }
</style>

<div class="container wrap bt-admin af-upd-wrap">
    <h1>
        <span class="dashicons dashicons-update"></span>
        <?php echo get_admin_page_title(); ?>
    </h1>
    <p class="af-upd-subtitle"><?php _e('Configure automatic updates from the WP Plugin Deployer server.', 'auctionforge'); ?></p>

    <div id="af-upd-notices"></div>

    <!-- Registration -->
    <div class="af-upd-card">
        <div class="af-upd-card-header">
            <span class="dashicons dashicons-admin-network"></span>
            <h2><?php _e('Server Registration', 'auctionforge'); ?></h2>
        </div>

        <?php if ($is_registered): ?>
            <div class="af-upd-status connected">
                <span class="dashicons dashicons-yes-alt"></span>
                <?php _e('Connected — this site is registered with the deployment server.', 'auctionforge'); ?>
            </div>

            <table class="af-upd-info-table">
                <tr>
                    <th><?php _e('Server URL', 'auctionforge'); ?></th>
                    <td><code><?php echo esc_html($server_url); ?></code></td>
                </tr>
                <tr>
                    <th><?php _e('API Key', 'auctionforge'); ?></th>
                    <td><code><?php echo esc_html(substr($api_key, 0, 8) . '••••' . substr($api_key, -4)); ?></code></td>
                </tr>
            </table>

            <div class="af-upd-actions">
                <button type="button" class="button" id="af-clear-registration">
                    <span class="dashicons dashicons-dismiss"></span> <?php _e('Clear Registration', 'auctionforge'); ?>
                </button>
            </div>

        <?php else: ?>
            <div class="af-upd-status disconnected">
                <span class="dashicons dashicons-warning"></span>
                <?php _e('Not registered — connect to a deployment server to receive updates.', 'auctionforge'); ?>
            </div>

            <div class="af-upd-field">
                <label for="af-server-url"><?php _e('Deployment Server URL', 'auctionforge'); ?></label>
                <input type="url" id="af-server-url" value="<?php echo esc_attr($server_url); ?>" placeholder="https://wpdeploy.smoothbyteit.dev" />
            </div>

            <div class="af-upd-actions">
                <button type="button" class="button button-primary" id="af-request-access">
                    <span class="dashicons dashicons-admin-plugins"></span> <?php _e('Register Automatically', 'auctionforge'); ?>
                </button>
            </div>
            <p class="description" style="margin-top:8px;"><?php _e('Registers this site with the server automatically. No master key required.', 'auctionforge'); ?></p>

            <hr class="af-upd-divider" />

            <p style="font-weight:600;font-size:13px;color:#555;margin-bottom:12px;">
                <?php _e('Manual Registration (with Master Key)', 'auctionforge'); ?>
            </p>
            <div class="af-upd-field">
                <label for="af-master-key"><?php _e('Master API Key', 'auctionforge'); ?></label>
                <input type="text" id="af-master-key" placeholder="<?php esc_attr_e('Enter master key...', 'auctionforge'); ?>" />
            </div>

            <div class="af-upd-actions">
                <button type="button" class="button" id="af-register-site">
                    <span class="dashicons dashicons-admin-network"></span> <?php _e('Register with Master Key', 'auctionforge'); ?>
                </button>
            </div>
        <?php endif; ?>
    </div>

    <?php if ($is_registered): ?>
    <!-- Update Settings -->
    <div class="af-upd-card">
        <div class="af-upd-card-header">
            <span class="dashicons dashicons-admin-settings"></span>
            <h2><?php _e('Update Settings', 'auctionforge'); ?></h2>
        </div>

        <div class="af-upd-checkbox-row">
            <input type="checkbox" id="af-auto-update" <?php checked($auto_update); ?> />
            <label for="af-auto-update"><?php _e('Automatically install updates when available', 'auctionforge'); ?></label>
        </div>

        <div class="af-upd-actions">
            <button type="button" class="button button-primary" id="af-save-settings">
                <span class="dashicons dashicons-saved"></span> <?php _e('Save Settings', 'auctionforge'); ?>
            </button>
        </div>
    </div>

    <!-- Fraud Enforcement -->
    <div class="af-upd-card">
        <div class="af-upd-card-header">
            <span class="dashicons dashicons-shield"></span>
            <h2><?php _e('Fraud Enforcement', 'auctionforge'); ?></h2>
        </div>

        <?php $fraud_enforcement = get_option('auctionforge_fraud_enforcement', false); ?>
        <?php $enforcement_synced_at = get_option('auctionforge_fraud_enforcement_synced_at', 'Never'); ?>
        <?php $last_sync_status = get_option('auctionforge_last_tracking_sync_status', 'never'); ?>
        <?php $last_sync_time = get_option('auctionforge_last_tracking_sync', 'Never'); ?>
        <?php $last_sync_count = get_option('auctionforge_last_tracking_sync_count', 0); ?>

        <div class="af-upd-status <?php echo $fraud_enforcement ? 'connected' : 'disconnected'; ?>">
            <span class="dashicons dashicons-<?php echo $fraud_enforcement ? 'shield' : 'visibility'; ?>"></span>
            <?php echo $fraud_enforcement
                ? __('LIVE — Fraud enforcement is active. Flagged users will be blocked.', 'auctionforge')
                : __('DRY RUN — Fraud data is being collected but no users are blocked.', 'auctionforge'); ?>
        </div>

        <p style="color: #666; font-size: 13px; margin-bottom: 16px;">
            <?php _e('Fraud enforcement is controlled by the central deployment server. This setting is synced automatically every 10 minutes. Contact your server administrator to enable or disable enforcement for this site.', 'auctionforge'); ?>
        </p>

        <div class="af-upd-actions">
            <button type="button" class="button" id="af-sync-enforcement">
                <span class="dashicons dashicons-shield"></span> <?php _e('Sync Enforcement Now', 'auctionforge'); ?>
            </button>
            <button type="button" class="button" id="af-sync-tracking">
                <span class="dashicons dashicons-update"></span> <?php _e('Sync Tracking Data Now', 'auctionforge'); ?>
            </button>
        </div>

        <div class="af-upd-result" id="af-enforcement-result"></div>
        <div class="af-upd-result" id="af-fraud-result"></div>

        <hr class="af-upd-divider" />
        <table class="af-upd-info-table">
            <tr>
                <th><?php _e('Enforcement Status', 'auctionforge'); ?></th>
                <td><code style="background: <?php echo $fraud_enforcement ? '#d4edda' : '#fff3cd'; ?>; color: <?php echo $fraud_enforcement ? '#155724' : '#856404'; ?>;"><?php echo $fraud_enforcement ? 'ACTIVE (LIVE)' : 'INACTIVE (DRY RUN)'; ?></code></td>
            </tr>
            <tr>
                <th><?php _e('Enforcement Synced', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html($enforcement_synced_at); ?></code></td>
            </tr>
            <tr>
                <th><?php _e('Tracking Sync Status', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html($last_sync_status); ?></code></td>
            </tr>
            <tr>
                <th><?php _e('Last Tracking Sync', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html($last_sync_time); ?></code></td>
            </tr>
            <tr>
                <th><?php _e('Records Synced (last run)', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html($last_sync_count); ?></code></td>
            </tr>
        </table>
    </div>

    <!-- Actions -->
    <div class="af-upd-card">
        <div class="af-upd-card-header">
            <span class="dashicons dashicons-performance"></span>
            <h2><?php _e('Actions', 'auctionforge'); ?></h2>
        </div>

        <div class="af-upd-actions">
            <button type="button" class="button" id="af-check-updates">
                <span class="dashicons dashicons-update"></span> <?php _e('Check for Updates', 'auctionforge'); ?>
            </button>
            <button type="button" class="button" id="af-report-health">
                <span class="dashicons dashicons-heart"></span> <?php _e('Send Health Report', 'auctionforge'); ?>
            </button>
            <button type="button" class="button" id="af-test-connection">
                <span class="dashicons dashicons-networking"></span> <?php _e('Test Connection', 'auctionforge'); ?>
            </button>
        </div>

        <div class="af-upd-result" id="af-action-result"></div>
    </div>

    <!-- Plugin Info -->
    <div class="af-upd-card">
        <div class="af-upd-card-header">
            <span class="dashicons dashicons-info-outline"></span>
            <h2><?php _e('Plugin Information', 'auctionforge'); ?></h2>
        </div>

        <table class="af-upd-info-table">
            <tr>
                <th><?php _e('Plugin Version', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html(AUCTIONFORGE_VERSION); ?></code></td>
            </tr>
            <tr>
                <th><?php _e('WordPress Version', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html(get_bloginfo('version')); ?></code></td>
            </tr>
            <tr>
                <th><?php _e('PHP Version', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html(PHP_VERSION); ?></code></td>
            </tr>
            <tr>
                <th><?php _e('Plugin Slug', 'auctionforge'); ?></th>
                <td><code><?php echo esc_html(AUCTIONFORGE_PLUGIN_SLUG); ?></code></td>
            </tr>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
jQuery(document).ready(function($) {
    var nonce = '<?php echo esc_js($nonce); ?>';
    var ajaxurl = '<?php echo esc_js(admin_url("admin-ajax.php")); ?>';

    function showNotice(msg, type) {
        var cls = type === 'error' ? 'error' : 'success';
        $('#af-upd-notices').html(
            '<div class="af-upd-result ' + cls + '" style="display:block;margin-bottom:16px;">' +
            '<span class="dashicons dashicons-' + (cls === 'error' ? 'warning' : 'yes') + '"></span> ' + msg +
            '</div>'
        );
        if (cls === 'success') {
            setTimeout(function() { $('#af-upd-notices').fadeOut(400, function() { $(this).html('').show(); }); }, 4000);
        }
    }

    function showActionResult(msg, type) {
        var el = $('#af-action-result');
        el.removeClass('success error info').addClass(type || 'info').html(
            '<span class="dashicons dashicons-' + (type === 'error' ? 'warning' : type === 'success' ? 'yes' : 'info-outline') + '"></span> ' + msg
        ).show();
    }

    // Request automatic access
    $('#af-request-access').on('click', function() {
        var btn = $(this);
        var serverUrl = $('#af-server-url').val();
        if (!serverUrl) { showNotice('Server URL is required', 'error'); return; }
        btn.prop('disabled', true).find('.dashicons').removeClass('dashicons-admin-plugins').addClass('dashicons-update spin');
        $.post(ajaxurl, { action: 'auctionforge_request_access', nonce: nonce, server_url: serverUrl }, function(r) {
            if (r.success) { showNotice(r.data.message, 'success'); setTimeout(function(){ location.reload(); }, 1500); }
            else { showNotice(r.data || 'Registration failed', 'error'); btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-admin-plugins'); }
        });
    });

    // Register with master key
    $('#af-register-site').on('click', function() {
        var btn = $(this);
        var serverUrl = $('#af-server-url').val();
        var masterKey = $('#af-master-key').val();
        if (!serverUrl || !masterKey) { showNotice('Server URL and Master Key are required', 'error'); return; }
        btn.prop('disabled', true).find('.dashicons').removeClass('dashicons-admin-network').addClass('dashicons-update spin');
        $.post(ajaxurl, { action: 'auctionforge_register_site', nonce: nonce, server_url: serverUrl, master_key: masterKey }, function(r) {
            if (r.success) { showNotice(r.data.message, 'success'); setTimeout(function(){ location.reload(); }, 1500); }
            else { showNotice(r.data || 'Registration failed', 'error'); btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-admin-network'); }
        });
    });

    // Clear registration
    $('#af-clear-registration').on('click', function() {
        if (!confirm('<?php esc_attr_e('Are you sure you want to disconnect from the deployment server?', 'auctionforge'); ?>')) return;
        var btn = $(this);
        btn.prop('disabled', true);
        $.post(ajaxurl, { action: 'auctionforge_clear_registration', nonce: nonce }, function(r) {
            if (r.success) { showNotice(r.data.message, 'success'); setTimeout(function(){ location.reload(); }, 1500); }
            else { showNotice(r.data || 'Failed', 'error'); btn.prop('disabled', false); }
        });
    });

    // Save settings
    $('#af-save-settings').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true);
        $.post(ajaxurl, {
            action: 'auctionforge_save_update_settings', nonce: nonce,
            server_url: '<?php echo esc_js($server_url); ?>',
            api_key: '<?php echo esc_js($api_key); ?>',
            auto_update: $('#af-auto-update').is(':checked') ? 1 : 0
        }, function(r) {
            btn.prop('disabled', false);
            if (r.success) showNotice(r.data.message, 'success');
            else showNotice(r.data || 'Failed', 'error');
        });
    });

    // Check for updates
    $('#af-check-updates').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).find('.dashicons').addClass('spin');
        $.post(ajaxurl, { action: 'auctionforge_check_updates_now', nonce: nonce }, function(r) {
            btn.prop('disabled', false).find('.dashicons').removeClass('spin');
            if (r.success) showActionResult(r.data.message, r.data.has_update ? 'success' : 'info');
            else showActionResult(r.data || 'Check failed', 'error');
        });
    });

    // Report health
    $('#af-report-health').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).find('.dashicons').addClass('spin');
        $.post(ajaxurl, { action: 'auctionforge_report_health_now', nonce: nonce }, function(r) {
            btn.prop('disabled', false).find('.dashicons').removeClass('spin');
            if (r.success) showActionResult(r.data.message, 'success');
            else showActionResult(r.data || 'Report failed', 'error');
        });
    });

    // Sync enforcement now
    $('#af-sync-enforcement').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).find('.dashicons').addClass('spin');
        var resultEl = $('#af-enforcement-result');
        resultEl.removeClass('success error info').addClass('info').html('<span class="dashicons dashicons-shield spin"></span> Syncing enforcement status from central server...').show();
        $.post(ajaxurl, { action: 'auctionforge_sync_enforcement_now', nonce: nonce }, function(r) {
            btn.prop('disabled', false).find('.dashicons').removeClass('spin');
            if (r.success) {
                resultEl.removeClass('info').addClass('success').html('<span class="dashicons dashicons-yes"></span> ' + r.data.message);
                setTimeout(function(){ location.reload(); }, 1500);
            } else {
                resultEl.removeClass('info').addClass('error').html('<span class="dashicons dashicons-warning"></span> ' + (r.data || 'Sync failed'));
            }
        });
    });

    // Sync tracking now
    $('#af-sync-tracking').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).find('.dashicons').addClass('spin');
        var resultEl = $('#af-fraud-result');
        resultEl.removeClass('success error info').addClass('info').html('<span class="dashicons dashicons-update spin"></span> Syncing tracking data...').show();
        $.post(ajaxurl, { action: 'auctionforge_sync_tracking_now', nonce: nonce }, function(r) {
            btn.prop('disabled', false).find('.dashicons').removeClass('spin');
            if (r.success) {
                resultEl.removeClass('info').addClass('success').html('<span class="dashicons dashicons-yes"></span> ' + r.data.message);
            } else {
                resultEl.removeClass('info').addClass('error').html('<span class="dashicons dashicons-warning"></span> ' + (r.data || 'Sync failed'));
            }
        });
    });

    // Test connection
    $('#af-test-connection').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).find('.dashicons').addClass('spin');
        $.post(ajaxurl, {
            action: 'auctionforge_test_update_connection', nonce: nonce,
            server_url: '<?php echo esc_js($server_url); ?>',
            api_key: '<?php echo esc_js($api_key); ?>'
        }, function(r) {
            btn.prop('disabled', false).find('.dashicons').removeClass('spin');
            if (r.success) showActionResult('Connected! Server version: ' + r.data.version, 'success');
            else showActionResult(r.data || 'Connection failed', 'error');
        });
    });
});
</script>
<style>
    @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
    .spin { animation: spin 1s linear infinite; }
</style>
