<?php
/**
 * Admin Settings Page
 */

// Prevent direct access
if (!defined('WPINC')) {
    die('Direct access not permitted.');
}

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

// Additional security check
if (!function_exists('current_user_can')) {
    die('WordPress environment not loaded.');
}

// Check user capabilities
if (!current_user_can('manage_options')) {
    wp_die('You do not have sufficient permissions to access this page.');
}

// Save settings
if (isset($_POST['mcb_save_settings'])) {
    // Verify nonce
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'mcb_settings_nonce')) {
        wp_die('Security check failed');
    }
    
    // Double-check capabilities
    if (!current_user_can('manage_options')) {
        wp_die('Insufficient permissions');
    }
    
    // Save platform tokens
    $platforms = array('github', 'gitlab', 'bitbucket', 'codeberg');
    foreach ($platforms as $platform) {
        $token_field = 'mcb_' . $platform . '_token';
        $token = sanitize_text_field($_POST[$token_field] ?? '');
        update_option($token_field, $token);
    }
    
    // Save cache duration
    $cache_duration = absint($_POST['mcb_cache_duration']);
    update_option('mcb_cache_duration', $cache_duration);
    
    // Save default theme
    $default_theme = sanitize_text_field($_POST['mcb_default_theme']);
    update_option('mcb_default_theme', $default_theme);
    
    echo '<div class="notice notice-success"><p>Settings saved successfully!</p></div>';
}

// Get current settings
$github_token = get_option('mcb_github_token', '');
$gitlab_token = get_option('mcb_gitlab_token', '');
$bitbucket_token = get_option('mcb_bitbucket_token', '');
$codeberg_token = get_option('mcb_codeberg_token', '');
$cache_duration = get_option('mcb_cache_duration', 3600);
$default_theme = get_option('mcb_default_theme', 'dark');
?>

<div class="wrap">
    <h1>Maple Code Blocks Settings</h1>
    <p>Configure your Maple Code Blocks plugin settings below. Developed by <a href="https://sspmedia.ca/wordpress/" target="_blank">SSP Media</a>.</p>
    
    <form method="post" action="">
        <?php wp_nonce_field('mcb_settings_nonce'); ?>
        
        <table class="form-table">
            <tr>
                <th colspan="2">
                    <h2>Platform API Tokens</h2>
                    <p>Optional: Add personal access tokens to increase API rate limits for each platform.</p>
                </th>
            </tr>
            
            <tr>
                <th scope="row">
                    <label for="mcb_github_token">GitHub Token</label>
                </th>
                <td>
                    <input type="text" id="mcb_github_token" name="mcb_github_token" 
                           value="<?php echo esc_attr($github_token); ?>" class="regular-text" />
                    <p class="description">
                        <a href="https://github.com/settings/tokens" target="_blank">Generate GitHub token</a> 
                        (no special permissions needed for public repos)
                    </p>
                </td>
            </tr>
            
            <tr>
                <th scope="row">
                    <label for="mcb_gitlab_token">GitLab Token</label>
                </th>
                <td>
                    <input type="text" id="mcb_gitlab_token" name="mcb_gitlab_token" 
                           value="<?php echo esc_attr($gitlab_token); ?>" class="regular-text" />
                    <p class="description">
                        <a href="https://gitlab.com/-/profile/personal_access_tokens" target="_blank">Generate GitLab token</a> 
                        (read_api scope for public repos)
                    </p>
                </td>
            </tr>
            
            <tr>
                <th scope="row">
                    <label for="mcb_bitbucket_token">Bitbucket App Password</label>
                </th>
                <td>
                    <input type="text" id="mcb_bitbucket_token" name="mcb_bitbucket_token" 
                           value="<?php echo esc_attr($bitbucket_token); ?>" class="regular-text" />
                    <p class="description">
                        <a href="https://bitbucket.org/account/settings/app-passwords/" target="_blank">Generate Bitbucket app password</a> 
                        (repository read permission)
                    </p>
                </td>
            </tr>
            
            <tr>
                <th scope="row">
                    <label for="mcb_codeberg_token">Codeberg Token</label>
                </th>
                <td>
                    <input type="text" id="mcb_codeberg_token" name="mcb_codeberg_token" 
                           value="<?php echo esc_attr($codeberg_token); ?>" class="regular-text" />
                    <p class="description">
                        <a href="https://codeberg.org/user/settings/applications" target="_blank">Generate Codeberg token</a> 
                        (read:repository scope)
                    </p>
                </td>
            </tr>
            
            <tr>
                <th colspan="2">
                    <h2>General Settings</h2>
                </th>
            </tr>
            
            <tr>
                <th scope="row">
                    <label for="mcb_cache_duration">Cache Duration</label>
                </th>
                <td>
                    <input type="number" id="mcb_cache_duration" name="mcb_cache_duration" 
                           value="<?php echo esc_attr($cache_duration); ?>" min="0" /> seconds
                    <p class="description">
                        How long to cache repository files (default: 3600 seconds = 1 hour).<br>
                        Set to 0 to disable caching.
                    </p>
                </td>
            </tr>
            
            <tr>
                <th scope="row">
                    <label for="mcb_default_theme">Default Theme</label>
                </th>
                <td>
                    <select id="mcb_default_theme" name="mcb_default_theme">
                        <option value="dark" <?php selected($default_theme, 'dark'); ?>>Dark</option>
                        <option value="light" <?php selected($default_theme, 'light'); ?>>Light</option>
                        <option value="monokai" <?php selected($default_theme, 'monokai'); ?>>Monokai</option>
                        <option value="solarized" <?php selected($default_theme, 'solarized'); ?>>Solarized</option>
                    </select>
                    <p class="description">
                        Default theme for the code viewer. Can be overridden per shortcode.
                    </p>
                </td>
            </tr>
        </table>
        
        <p class="submit">
            <input type="submit" name="mcb_save_settings" class="button-primary" value="Save Settings" />
        </p>
    </form>
    
    <hr />
    
    <h2>Usage Instructions</h2>
    
    <div class="card">
        <h3>Supported Platforms</h3>
        <p>This plugin supports repositories from:</p>
        <ul>
            <li><strong>GitHub</strong> - github.com</li>
            <li><strong>GitLab</strong> - gitlab.com</li>
            <li><strong>Bitbucket</strong> - bitbucket.org</li>
            <li><strong>Codeberg</strong> - codeberg.org</li>
        </ul>
        
        <h3>Repository Formats</h3>
        <p>You can specify repositories in multiple ways:</p>
        <ul>
            <li><strong>Default (GitHub):</strong> <code>owner/repository</code></li>
            <li><strong>With platform prefix:</strong> <code>gitlab:owner/repository</code></li>
            <li><strong>Full URL:</strong> <code>https://gitlab.com/owner/repository</code></li>
        </ul>
        
        <h3>Basic Usage</h3>
        <p>Use the following shortcode to display repository code:</p>
        <code>[maple_code_block repo="owner/repository"]</code>
        
        <h3>Platform Examples</h3>
        <ul>
            <li><strong>GitHub:</strong> <code>[maple_code_block repo="facebook/react"]</code></li>
            <li><strong>GitLab:</strong> <code>[maple_code_block repo="gitlab:gitlab-org/gitlab"]</code></li>
            <li><strong>Bitbucket:</strong> <code>[maple_code_block repo="bitbucket:atlassian/python-bitbucket"]</code></li>
            <li><strong>Codeberg:</strong> <code>[maple_code_block repo="codeberg:forgejo/forgejo"]</code></li>
        </ul>
        
        <h3>Shortcode Parameters</h3>
        <ul>
            <li><strong>repo</strong> - (required) The GitHub repository in format "owner/repository"</li>
            <li><strong>theme</strong> - Theme: dark, light, monokai, or solarized (default: dark)</li>
            <li><strong>height</strong> - Height of the viewer (default: 600px)</li>
            <li><strong>show_line_numbers</strong> - Show line numbers: true or false (default: true)</li>
            <li><strong>initial_file</strong> - Path to file to load initially</li>
            <li><strong>title</strong> - Optional title to display above the viewer</li>
        </ul>
        
        <h3>Example</h3>
        <code>[github_code_viewer repo="facebook/react" theme="dark" height="500px" initial_file="README.md" title="React Source Code"]</code>
        
        <h3>Security Features</h3>
        <ul>
            <li>✅ All code is HTML-escaped to prevent XSS attacks</li>
            <li>✅ JavaScript code is displayed as text only, never executed</li>
            <li>✅ Binary files are automatically filtered out</li>
            <li>✅ File size limits prevent loading huge files</li>
            <li>✅ Content is sanitized multiple times before display</li>
        </ul>
    </div>
    
    <hr />
    
    <div class="card">
        <h3>About</h3>
        <p>
            <strong>GitHub Code Viewer</strong> Version 1.0.0<br>
            This plugin displays code from GitHub repositories in a beautiful, safe terminal/IDE-style interface.
        </p>
        <p>
            <strong>Features:</strong>
        </p>
        <ul>
            <li>Beautiful syntax highlighting with Prism.js</li>
            <li>Terminal/IDE-style interface</li>
            <li>File browser with search</li>
            <li>Tabbed interface for multiple files</li>
            <li>Copy code functionality</li>
            <li>Line numbers</li>
            <li>Multiple themes</li>
            <li>Fullscreen mode</li>
            <li>Responsive design</li>
            <li>Safe display (no code execution)</li>
        </ul>
    </div>
</div>

<style>
    .card {
        background: white;
        border: 1px solid #ccd0d4;
        padding: 20px;
        margin: 20px 0;
        border-radius: 4px;
    }
    .card h3 {
        margin-top: 0;
    }
    .card code {
        display: block;
        padding: 10px;
        background: #f1f1f1;
        border-radius: 3px;
        margin: 10px 0;
    }
</style>
