<?php
/**
 * Cloudflare Management Page
 * 
 * @package Utility_Server_CDN
 * @since 1.0.5
 */

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

// Get Cloudflare handler
global $uscdn_cloudflare;

// Get current settings
$zone_id = get_option('uscdn_cf_zone_id', '');
$api_token = get_option('uscdn_cf_api_token', '');
$is_configured = !empty($zone_id) && !empty($api_token);

// Save settings if form submitted
if (isset($_POST['uscdn_cf_save_credentials']) && check_admin_referer('uscdn-cf-credentials')) {
    update_option('uscdn_cf_zone_id', sanitize_text_field($_POST['uscdn_cf_zone_id']));
    update_option('uscdn_cf_api_token', sanitize_text_field($_POST['uscdn_cf_api_token']));
    echo '<div class="notice notice-success"><p>Cloudflare credentials saved successfully!</p></div>';
    $is_configured = true;
}

// Include branding
require_once plugin_dir_path(__FILE__) . 'branding.php';
?>

<div class="wrap uscdn-admin">
    <div class="uscdn-content">
        
        <!-- API Configuration Section -->
        <div class="uscdn-section">
            <h2>🔐 Cloudflare API Configuration</h2>
            <p class="description">Configure your Cloudflare Zone ID and API Token to enable cache management features.</p>
            
            <form method="post" action="">
                <?php wp_nonce_field('uscdn-cf-credentials'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="uscdn_cf_zone_id">Zone ID</label>
                        </th>
                        <td>
                            <input type="text" 
                                   id="uscdn_cf_zone_id" 
                                   name="uscdn_cf_zone_id" 
                                   value="<?php echo esc_attr($zone_id); ?>" 
                                   class="regular-text"
                                   placeholder="e.g., 5b0e5a3484511eb5bf0c1178a41eb611">
                            <p class="description">
                                Find your Zone ID in Cloudflare Dashboard → Overview (right sidebar)
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="uscdn_cf_api_token">API Token</label>
                        </th>
                        <td>
                            <input type="password" 
                                   id="uscdn_cf_api_token" 
                                   name="uscdn_cf_api_token" 
                                   value="<?php echo esc_attr($api_token); ?>" 
                                   class="regular-text"
                                   placeholder="Your Cloudflare API Token">
                            <p class="description">
                                Create an API Token at Cloudflare Dashboard → My Profile → API Tokens<br>
                                Required permissions: <strong>Zone.Cache Purge, Zone.Settings</strong>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <button type="submit" name="uscdn_cf_save_credentials" class="button button-primary">
                        Save Credentials
                    </button>
                    <?php if ($is_configured): ?>
                    <button type="button" id="uscdn-cf-test-connection" class="button">
                        Test Connection
                    </button>
                    <?php endif; ?>
                </p>
            </form>
        </div>
        
        <?php if ($is_configured): ?>
        
        <!-- Quick Actions -->
        <div class="uscdn-section">
            <h2>⚡ Quick Actions</h2>
            <p class="description">Instant cache management and site optimization controls.</p>
            
            <div class="uscdn-cloudflare-actions">
                <div class="uscdn-action-card">
                    <h3>Purge All Cache</h3>
                    <p>Clear all cached content from Cloudflare CDN.</p>
                    <button type="button" id="uscdn-cf-purge-all" class="button button-primary">
                        🗑️ Purge All Cache
                    </button>
                </div>
                
                <div class="uscdn-action-card">
                    <h3>Developer Mode</h3>
                    <p>Bypass cache temporarily for testing (auto-off after 3 hours).</p>
                    <label class="uscdn-toggle">
                        <input type="checkbox" id="uscdn-cf-dev-mode">
                        <span class="uscdn-toggle-slider"></span>
                    </label>
                    <span id="uscdn-cf-dev-mode-status">Loading...</span>
                </div>
                
                <div class="uscdn-action-card">
                    <h3>Always Online</h3>
                    <p>Serve cached pages when your origin server is down.</p>
                    <label class="uscdn-toggle">
                        <input type="checkbox" id="uscdn-cf-always-online">
                        <span class="uscdn-toggle-slider"></span>
                    </label>
                    <span id="uscdn-cf-always-online-status">Loading...</span>
                </div>
            </div>
        </div>
        
        <!-- Selective Purge -->
        <div class="uscdn-section">
            <h2>🎯 Selective Cache Purge</h2>
            <p class="description">Purge specific URLs or use wildcards to clear multiple files at once.</p>
            
            <div class="uscdn-purge-tabs">
                <button class="uscdn-tab-button active" data-tab="urls">By URLs</button>
                <button class="uscdn-tab-button" data-tab="wildcard">By Wildcard</button>
            </div>
            
            <!-- Purge by URLs -->
            <div id="uscdn-tab-urls" class="uscdn-tab-content active">
                <h3>Purge Specific URLs</h3>
                <p class="description">Enter one URL per line. Full URLs required including protocol (https://).</p>
                <textarea id="uscdn-cf-urls" 
                          rows="8" 
                          class="large-text code"
                          placeholder="https://example.com/image.jpg&#10;https://example.com/style.css&#10;https://example.com/script.js"></textarea>
                <p class="description">
                    <strong>Examples:</strong><br>
                    • https://example.com/wp-content/uploads/image.jpg<br>
                    • https://example.com/wp-content/themes/mytheme/style.css
                </p>
                <button type="button" id="uscdn-cf-purge-urls" class="button button-primary">
                    Purge URLs
                </button>
            </div>
            
            <!-- Purge by Wildcard -->
            <div id="uscdn-tab-wildcard" class="uscdn-tab-content" style="display: none;">
                <h3>Purge by Wildcard/Prefix</h3>
                <p class="description">Enter URL prefixes to purge multiple files. One prefix per line.</p>
                <textarea id="uscdn-cf-wildcards" 
                          rows="8" 
                          class="large-text code"
                          placeholder="https://example.com/wp-content/uploads/*&#10;https://example.com/wp-content/themes/mytheme/*"></textarea>
                <p class="description">
                    <strong>Examples:</strong><br>
                    • https://example.com/wp-content/uploads/* (all uploads)<br>
                    • https://example.com/category/* (all category pages)<br>
                    • https://example.com/wp-content/themes/* (all theme files)
                </p>
                <button type="button" id="uscdn-cf-purge-wildcard" class="button button-primary">
                    Purge Wildcard
                </button>
            </div>
        </div>
        
        <!-- Cache Settings -->
        <div class="uscdn-section">
            <h2>⚙️ Browser Cache TTL</h2>
            <p class="description">Configure how long browsers should cache your content.</p>
            
            <div class="uscdn-ttl-selector">
                <select id="uscdn-cf-cache-ttl" class="regular-text">
                    <option value="0">Respect Existing Headers</option>
                    <option value="30">30 seconds</option>
                    <option value="60">1 minute</option>
                    <option value="120">2 minutes</option>
                    <option value="300">5 minutes</option>
                    <option value="1200">20 minutes</option>
                    <option value="1800">30 minutes</option>
                    <option value="3600">1 hour</option>
                    <option value="7200">2 hours</option>
                    <option value="10800">3 hours</option>
                    <option value="14400">4 hours</option>
                    <option value="18000">5 hours</option>
                    <option value="28800">8 hours</option>
                    <option value="43200">12 hours</option>
                    <option value="57600">16 hours</option>
                    <option value="72000">20 hours</option>
                    <option value="86400">1 day</option>
                    <option value="172800">2 days</option>
                    <option value="259200">3 days</option>
                    <option value="345600">4 days</option>
                    <option value="432000">5 days</option>
                    <option value="691200">8 days</option>
                    <option value="1382400">16 days</option>
                    <option value="2073600">24 days</option>
                    <option value="2678400">1 month</option>
                    <option value="5356800">2 months</option>
                    <option value="16070400">6 months</option>
                    <option value="31536000">1 year</option>
                </select>
                <button type="button" id="uscdn-cf-set-ttl" class="button button-primary">
                    Update TTL
                </button>
            </div>
        </div>
        
        <?php else: ?>
        
        <!-- Not Configured Message -->
        <div class="uscdn-section">
            <div class="notice notice-info inline">
                <p>
                    <strong>ℹ️ Cloudflare Integration is Optional</strong><br>
                    Configure your Cloudflare credentials above to enable advanced cache management features including selective purge, developer mode, and cache settings.
                </p>
            </div>
        </div>
        
        <?php endif; ?>
        
    </div>
</div>

<style>
.uscdn-cloudflare-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.uscdn-action-card {
    background: #f7f7f7;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
}

.uscdn-action-card h3 {
    margin-top: 0;
    font-size: 16px;
}

.uscdn-action-card p {
    color: #666;
    font-size: 13px;
    margin-bottom: 15px;
}

.uscdn-purge-tabs {
    display: flex;
    gap: 10px;
    margin: 20px 0;
    border-bottom: 2px solid #ddd;
}

.uscdn-tab-button {
    background: none;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    color: #666;
    border-bottom: 3px solid transparent;
    margin-bottom: -2px;
}

.uscdn-tab-button:hover {
    color: #333;
}

.uscdn-tab-button.active {
    color: #667eea;
    border-bottom-color: #667eea;
}

.uscdn-tab-content {
    margin-top: 20px;
}

.uscdn-ttl-selector {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-top: 20px;
}

/* Toggle Switch */
.uscdn-toggle {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
    margin: 10px 0;
}

.uscdn-toggle input {
    opacity: 0;
    width: 0;
    height: 0;
}

.uscdn-toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 34px;
}

.uscdn-toggle-slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

.uscdn-toggle input:checked + .uscdn-toggle-slider {
    background-color: #667eea;
}

.uscdn-toggle input:checked + .uscdn-toggle-slider:before {
    transform: translateX(26px);
}
</style>

<script>
jQuery(document).ready(function($) {
    var nonce = '<?php echo wp_create_nonce('uscdn-cloudflare-nonce'); ?>';
    
    // Load current settings on page load
    <?php if ($is_configured): ?>
    loadCurrentSettings();
    <?php endif; ?>
    
    function loadCurrentSettings() {
        $.post(ajaxurl, {
            action: 'uscdn_cf_get_settings',
            nonce: nonce
        }, function(response) {
            if (response.success && response.data) {
                var settings = response.data;
                
                // Update developer mode toggle and status
                $('#uscdn-cf-dev-mode').prop('checked', settings.dev_mode.enabled);
                if (settings.dev_mode.enabled) {
                    var hours = Math.floor(settings.dev_mode.time_remaining / 3600);
                    var minutes = Math.floor((settings.dev_mode.time_remaining % 3600) / 60);
                    $('#uscdn-cf-dev-mode-status').text('Enabled (' + hours + 'h ' + minutes + 'm remaining)').css('color', '#38a169');
                } else {
                    $('#uscdn-cf-dev-mode-status').text('Disabled').css('color', '#718096');
                }
                
                // Update always online toggle and status
                $('#uscdn-cf-always-online').prop('checked', settings.always_online.enabled);
                $('#uscdn-cf-always-online-status').text(settings.always_online.enabled ? 'Enabled' : 'Disabled')
                    .css('color', settings.always_online.enabled ? '#38a169' : '#718096');
                
                // Update cache TTL dropdown
                $('#uscdn-cf-cache-ttl').val(settings.cache_ttl.value);
            }
        }).fail(function() {
            $('#uscdn-cf-dev-mode-status').text('Unable to load');
            $('#uscdn-cf-always-online-status').text('Unable to load');
        });
    }
    
    // Tab switching
    $('.uscdn-tab-button').on('click', function() {
        var tab = $(this).data('tab');
        $('.uscdn-tab-button').removeClass('active');
        $('.uscdn-tab-content').hide();
        $(this).addClass('active');
        $('#uscdn-tab-' + tab).show();
    });
    
    // Test connection
    $('#uscdn-cf-test-connection').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).text('Testing...');
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_test_connection',
            nonce: nonce
        }, function(response) {
            btn.prop('disabled', false).text('Test Connection');
            if (response.success) {
                alert('✅ ' + response.data);
            } else {
                alert('❌ ' + response.data);
            }
        });
    });
    
    // Purge all cache
    $('#uscdn-cf-purge-all').on('click', function() {
        if (!confirm('Are you sure you want to purge ALL cache from Cloudflare?')) {
            return;
        }
        
        var btn = $(this);
        btn.prop('disabled', true).text('Purging...');
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_purge_all',
            nonce: nonce
        }, function(response) {
            btn.prop('disabled', false).text('🗑️ Purge All Cache');
            if (response.success) {
                alert('✅ ' + response.data);
            } else {
                alert('❌ ' + response.data);
            }
        });
    });
    
    // Purge URLs
    $('#uscdn-cf-purge-urls').on('click', function() {
        var urls = $('#uscdn-cf-urls').val().trim();
        if (!urls) {
            alert('Please enter at least one URL');
            return;
        }
        
        var btn = $(this);
        btn.prop('disabled', true).text('Purging...');
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_purge_urls',
            nonce: nonce,
            urls: urls,
            type: 'urls'
        }, function(response) {
            btn.prop('disabled', false).text('Purge URLs');
            if (response.success) {
                alert('✅ ' + response.data);
                $('#uscdn-cf-urls').val('');
            } else {
                alert('❌ ' + response.data);
            }
        });
    });
    
    // Purge wildcard
    $('#uscdn-cf-purge-wildcard').on('click', function() {
        var wildcards = $('#uscdn-cf-wildcards').val().trim();
        if (!wildcards) {
            alert('Please enter at least one wildcard pattern');
            return;
        }
        
        var btn = $(this);
        btn.prop('disabled', true).text('Purging...');
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_purge_urls',
            nonce: nonce,
            urls: wildcards,
            type: 'wildcard'
        }, function(response) {
            btn.prop('disabled', false).text('Purge Wildcard');
            if (response.success) {
                alert('✅ ' + response.data);
                $('#uscdn-cf-wildcards').val('');
            } else {
                alert('❌ ' + response.data);
            }
        });
    });
    
    // Toggle developer mode
    $('#uscdn-cf-dev-mode').on('change', function() {
        var enabled = $(this).is(':checked');
        var toggle = $(this);
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_toggle_dev_mode',
            nonce: nonce,
            enabled: enabled
        }, function(response) {
            if (response.success) {
                if (enabled) {
                    $('#uscdn-cf-dev-mode-status').text('Enabled (3h 0m remaining)').css('color', '#38a169');
                } else {
                    $('#uscdn-cf-dev-mode-status').text('Disabled').css('color', '#718096');
                }
            } else {
                alert('❌ ' + response.data);
                // Revert toggle on error
                toggle.prop('checked', !enabled);
            }
        });
    });
    
    // Toggle always online
    $('#uscdn-cf-always-online').on('change', function() {
        var enabled = $(this).is(':checked');
        var toggle = $(this);
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_toggle_always_online',
            nonce: nonce,
            enabled: enabled
        }, function(response) {
            if (response.success) {
                $('#uscdn-cf-always-online-status').text(enabled ? 'Enabled' : 'Disabled')
                    .css('color', enabled ? '#38a169' : '#718096');
            } else {
                alert('❌ ' + response.data);
                // Revert toggle on error
                toggle.prop('checked', !enabled);
            }
        });
    });
    
    // Set cache TTL
    $('#uscdn-cf-set-ttl').on('click', function() {
        var ttl = $('#uscdn-cf-cache-ttl').val();
        var btn = $(this);
        btn.prop('disabled', true).text('Updating...');
        
        $.post(ajaxurl, {
            action: 'uscdn_cf_set_cache_ttl',
            nonce: nonce,
            ttl: ttl
        }, function(response) {
            btn.prop('disabled', false).text('Update TTL');
            if (response.success) {
                alert('✅ ' + response.data);
            } else {
                alert('❌ ' + response.data);
            }
        });
    });
});
</script>
