<?php
/**
 * Clear Test Certificates Script
 * 
 * This script clears test certificate data from the staging server.
 * Access it at: https://yourdomain.com/wp-content/plugins/hvac-community-events/clear-test-certificates.php
 */

// Load WordPress
require_once dirname(__FILE__) . '/../../../../wp-load.php';

// Check if user is logged in and has permission
if (!is_user_logged_in() || !current_user_can('manage_options')) {
    die('Access denied. Please log in as an administrator.');
}

// Get action from URL parameter
$action = isset($_GET['action']) ? $_GET['action'] : '';
$confirm = isset($_GET['confirm']) ? $_GET['confirm'] : '';

?>
<!DOCTYPE html>
<html>
<head>
    <title>Clear Test Certificates</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 40px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #23282d;
            margin-bottom: 30px;
        }
        .stats {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 4px;
            margin-bottom: 30px;
        }
        .stat-item {
            margin: 10px 0;
            font-size: 16px;
        }
        .stat-label {
            font-weight: bold;
            display: inline-block;
            width: 200px;
        }
        .actions {
            margin-top: 30px;
        }
        .button {
            display: inline-block;
            padding: 10px 20px;
            margin: 5px;
            text-decoration: none;
            border-radius: 4px;
            font-weight: 500;
        }
        .button-primary {
            background: #007cba;
            color: white;
        }
        .button-danger {
            background: #dc3545;
            color: white;
        }
        .button-secondary {
            background: #6c757d;
            color: white;
        }
        .button:hover {
            opacity: 0.9;
        }
        .alert {
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeeba;
        }
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Clear Test Certificates</h1>
        
        <?php
        // Get current statistics
        global $wpdb;
        
        // Get certificate count
        $total_certs = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}hvac_certificates");
        
        // Get test user certificates
        $test_user = get_user_by('login', 'test_trainer');
        $test_user_id = $test_user ? $test_user->ID : 0;
        $test_certs = 0;
        
        if ($test_user_id) {
            $test_certs = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}hvac_certificates WHERE generated_by = %d",
                $test_user_id
            ));
        }
        
        // Get certificate file count
        $upload_dir = wp_upload_dir();
        $cert_dir = $upload_dir['basedir'] . '/hvac-certificates';
        $file_count = 0;
        
        if (is_dir($cert_dir)) {
            $files = glob($cert_dir . '/*/*.pdf');
            $file_count = $files ? count($files) : 0;
        }
        
        // Handle actions
        if ($action && $confirm === 'yes') {
            echo '<div class="alert alert-warning">Processing...</div>';
            
            switch ($action) {
                case 'clear_all':
                    // Clear all certificates
                    $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}hvac_certificates");
                    
                    // Clear files
                    if (is_dir($cert_dir)) {
                        $files = glob($cert_dir . '/*/*.pdf');
                        foreach ($files as $file) {
                            unlink($file);
                        }
                    }
                    
                    // Clear transients
                    $wpdb->query("DELETE FROM {$wpdb->prefix}options WHERE option_name LIKE '_transient_hvac_cert_%' OR option_name LIKE '_transient_timeout_hvac_cert_%'");
                    
                    echo '<div class="alert alert-success">All certificates have been cleared!</div>';
                    break;
                    
                case 'clear_test':
                    if ($test_user_id) {
                        // Get certificate IDs
                        $cert_ids = $wpdb->get_col($wpdb->prepare(
                            "SELECT certificate_id FROM {$wpdb->prefix}hvac_certificates WHERE generated_by = %d",
                            $test_user_id
                        ));
                        
                        if ($cert_ids) {
                            // Delete from database
                            $wpdb->query($wpdb->prepare(
                                "DELETE FROM {$wpdb->prefix}hvac_certificates WHERE generated_by = %d",
                                $test_user_id
                            ));
                            
                            echo '<div class="alert alert-success">Test certificates have been cleared from the database!</div>';
                        }
                    }
                    break;
                    
                case 'clear_files':
                    if (is_dir($cert_dir)) {
                        $files = glob($cert_dir . '/*/*.pdf');
                        $deleted = 0;
                        foreach ($files as $file) {
                            if (unlink($file)) {
                                $deleted++;
                            }
                        }
                        echo '<div class="alert alert-success">' . $deleted . ' certificate files have been deleted!</div>';
                    }
                    break;
            }
            
            // Refresh stats
            echo '<script>setTimeout(function() { window.location.href = "' . $_SERVER['PHP_SELF'] . '"; }, 2000);</script>';
        }
        ?>
        
        <div class="stats">
            <h2>Current Statistics</h2>
            <div class="stat-item">
                <span class="stat-label">Total Certificates:</span>
                <span><?php echo $total_certs; ?></span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Test Certificates:</span>
                <span><?php echo $test_certs; ?> (by test_trainer)</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Certificate Files:</span>
                <span><?php echo $file_count; ?> PDF files</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Certificate Directory:</span>
                <span><?php echo $cert_dir; ?></span>
            </div>
        </div>
        
        <?php if (!$action): ?>
        <div class="actions">
            <h2>Actions</h2>
            <p>Choose an action to perform:</p>
            
            <a href="?action=clear_all" class="button button-danger" onclick="return confirm('Are you sure you want to clear ALL certificates? This cannot be undone!');">Clear All Certificates</a>
            
            <?php if ($test_certs > 0): ?>
            <a href="?action=clear_test" class="button button-warning" onclick="return confirm('Clear all test certificates generated by test_trainer?');">Clear Test Certificates Only</a>
            <?php endif; ?>
            
            <?php if ($file_count > 0): ?>
            <a href="?action=clear_files" class="button button-warning" onclick="return confirm('Delete all certificate PDF files?');">Clear Certificate Files Only</a>
            <?php endif; ?>
            
            <a href="/hvac-dashboard/" class="button button-secondary">Back to Dashboard</a>
        </div>
        <?php elseif (!$confirm): ?>
        <div class="alert alert-danger">
            <h3>Confirm Action</h3>
            <p>You are about to: <strong><?php echo str_replace('_', ' ', $action); ?></strong></p>
            <p>This action cannot be undone!</p>
            
            <a href="?action=<?php echo $action; ?>&confirm=yes" class="button button-danger">Yes, Proceed</a>
            <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="button button-secondary">Cancel</a>
        </div>
        <?php endif; ?>
        
        <hr style="margin-top: 40px;">
        
        <div style="margin-top: 30px;">
            <h3>Regenerate Test Data</h3>
            <p>After clearing certificates, you can regenerate test data by:</p>
            <ol>
                <li>Log in as <strong>test_trainer</strong></li>
                <li>Go to <a href="/generate-certificates/">Generate Certificates</a></li>
                <li>Select an event and attendees</li>
                <li>Click "Generate Selected Certificates"</li>
            </ol>
        </div>
    </div>
</body>
</html>