<?php
/**
 * Complete Script: FORCE COPY System & UI Folders to All Subdomains
 * This script will FORCE COPY and OVERWRITE existing system and ui folders
 */

// ==================== CONFIGURATION ====================
$source_system = '/var/www/html/billing/system';
$source_ui = '/var/www/html/billing/ui';
$base_path = '/var/www/html/subdomains';

// Set to TRUE to force overwrite, FALSE to skip existing
$FORCE_OVERWRITE = true;  // ? FORCE COPY - will overwrite existing folders

// List of all target directories (database names)
$target_dirs = [
    'alpha', 'amzwifi', 'basiru', 'billing', 'bissau', 'blacka', 'bulanjor',
    'busra', 'byd', 'byde', 'dembawifi', 'dembawifi1', 'dijastarnet', 'empire',
    'enjoy', 'enjoy1', 'fast', 'fatty', 'foday', 'isp', 'jahstarnet1',
    'jahstarnet2', 'jallowwifi', 'jamano', 'jambur', 'jamisa', 'jamono', 'janz',
    'kanneh', 'kiosk', 'master', 'master-installer', 'modou', 'mummy', 'network',
    'njies', 'nnnwifi', 'oj', 'pkt', 'pointnet', 'register', 'sara', 'sol',
    'stayfocus', 'tendaba', 'vpnonex', 'wurry', 'zainaba'
];

// ==================== FUNCTIONS ====================

/**
 * Recursively copy files and directories (FORCE OVERWRITE)
 */
function recurse_copy_force($src, $dst) {
    if (!is_dir($src)) {
        return false;
    }
    
    // Create destination directory if it doesn't exist
    if (!is_dir($dst)) {
        if (!mkdir($dst, 0755, true)) {
            return false;
        }
    }
    
    $dir = opendir($src);
    $success = true;
    
    while (false !== ($file = readdir($dir))) {
        if (($file != '.') && ($file != '..')) {
            $srcPath = $src . '/' . $file;
            $dstPath = $dst . '/' . $file;
            
            if (is_dir($srcPath)) {
                // Recursively copy subdirectories
                if (!recurse_copy_force($srcPath, $dstPath)) {
                    $success = false;
                }
            } else {
                // FORCE COPY - will overwrite existing files
                if (file_exists($dstPath)) {
                    @unlink($dstPath); // Delete existing file
                }
                if (!copy($srcPath, $dstPath)) {
                    $success = false;
                } else {
                    chmod($dstPath, 0644);
                }
            }
        }
    }
    
    closedir($dir);
    return $success;
}

/**
 * Remove directory and all its contents
 */
function remove_directory($dir) {
    if (!is_dir($dir)) {
        return true;
    }
    
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        $path = $dir . '/' . $item;
        if (is_dir($path)) {
            remove_directory($path);
        } else {
            @unlink($path);
        }
    }
    
    return @rmdir($dir);
}

/**
 * Format bytes to human readable format
 */
function format_size($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return $bytes . ' byte';
    } else {
        return '0 bytes';
    }
}

/**
 * Get directory size
 */
function get_dir_size($dir) {
    $size = 0;
    if (!is_dir($dir)) {
        return 0;
    }
    
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                $size += get_dir_size($path);
            } else {
                $size += filesize($path);
            }
        }
    }
    return $size;
}

// ==================== MAIN SCRIPT ====================

// Start output buffering for cleaner display
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FORCE COPY - System & UI Folder Deployment</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .header .force-badge {
            display: inline-block;
            background: #ff0000;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
            margin-top: 10px;
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .content {
            padding: 30px;
        }
        
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #f5576c;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        
        .info-box h3 {
            color: #f5576c;
            margin-bottom: 10px;
        }
        
        .warning-box {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            color: #856404;
        }
        
        .warning-box h3 {
            color: #856404;
            margin-bottom: 10px;
        }
        
        .status-box {
            background: #1e1e1e;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 500px;
            overflow-y: auto;
            color: #d4d4d4;
        }
        
        .status-line {
            padding: 5px;
            margin: 2px 0;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        
        .status-line.success {
            color: #4ec9b0;
            background: rgba(78, 201, 176, 0.1);
        }
        
        .status-line.error {
            color: #f48771;
            background: rgba(244, 135, 113, 0.1);
        }
        
        .status-line.warning {
            color: #dcdcaa;
            background: rgba(220, 220, 170, 0.1);
        }
        
        .status-line.info {
            color: #9cdcfe;
            background: rgba(156, 220, 254, 0.1);
        }
        
        .status-line.overwrite {
            color: #ce9178;
            background: rgba(206, 145, 120, 0.1);
        }
        
        .summary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }
        
        .summary h3 {
            margin-bottom: 15px;
            font-size: 20px;
        }
        
        .summary-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: rgba(255,255,255,0.1);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            display: block;
        }
        
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
            margin-top: 5px;
            display: block;
        }
        
        .button {
            background: white;
            color: #f5576c;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            margin-top: 10px;
            transition: transform 0.2s;
        }
        
        .button:hover {
            transform: translateY(-2px);
        }
        
        .progress-bar {
            width: 100%;
            height: 30px;
            background: #e0e0e0;
            border-radius: 15px;
            overflow: hidden;
            margin: 20px 0;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #f093fb, #f5576c);
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 12px;
        }
        
        .footer {
            background: #f8f9fa;
            padding: 15px;
            text-align: center;
            font-size: 12px;
            color: #666;
        }
        
        pre {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
            margin-top: 10px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>?? FORCE COPY DEPLOYMENT</h1>
            <p>Overwriting existing system and ui folders in all subdomains</p>
            <div class="force-badge">?? FORCE OVERWRITE ENABLED ??</div>
        </div>
        
        <div class="content">
            <?php
            // Display warning about force overwrite
            echo "<div class='warning-box'>";
            echo "<h3>?? FORCE OVERWRITE WARNING</h3>";
            echo "<p>This script is configured to <strong>FORCE COPY and OVERWRITE</strong> existing system and ui folders.</p>";
            echo "<p><strong>This will delete existing system/ui folders and replace them with new ones from:</strong><br>";
            echo "?? $source_system<br>";
            echo "?? $source_ui</p>";
            echo "<p style='color: #dc3545; font-weight: bold;'>?? Make sure you have backups if needed!</p>";
            echo "</div>";
            
            // Check source folders
            echo "<div class='info-box'>";
            echo "<h3>?? Source Verification</h3>";
            
            $system_exists = file_exists($source_system);
            $ui_exists = file_exists($source_ui);
            
            echo "<div>";
            echo $system_exists ? "? " : "? ";
            echo "System folder: <strong>$source_system</strong><br>";
            echo $ui_exists ? "? " : "? ";
            echo "UI folder: <strong>$source_ui</strong><br>";
            
            if ($system_exists && $ui_exists) {
                $system_size = get_dir_size($source_system);
                $ui_size = get_dir_size($source_ui);
                echo "<br>?? System size: " . format_size($system_size) . "<br>";
                echo "?? UI size: " . format_size($ui_size) . "<br>";
                echo "<span style='color: green;'>? Source folders are ready for FORCE COPY</span>";
            } else {
                echo "<br><span style='color: red;'>? ERROR: Source folders not found! Cannot proceed.</span>";
                echo "</div></div></div></div></body></html>";
                exit;
            }
            echo "</div></div>";
            
            // Check if base path exists
            echo "<div class='info-box'>";
            echo "<h3>?? Target Base Path</h3>";
            if (is_dir($base_path)) {
                echo "? Base path exists: <strong>$base_path</strong><br>";
            } else {
                echo "?? Base path does not exist: <strong>$base_path</strong><br>";
                echo "Attempting to create... ";
                if (mkdir($base_path, 0755, true)) {
                    echo "<span style='color: green;'>? Created!</span>";
                } else {
                    echo "<span style='color: red;'>? Failed!</span>";
                }
            }
            echo "</div>";
            
            // Initialize progress
            $total_dirs = count($target_dirs);
            $current_dir = 0;
            $stats = [
                'created' => 0,
                'overwritten' => 0,
                'failed' => 0,
                'total_size' => 0
            ];
            
            $results = [];
            
            echo "<div class='progress-bar'>";
            echo "<div class='progress-fill' id='progressFill' style='width: 0%'>0%</div>";
            echo "</div>";
            
            echo "<div class='status-box' id='statusBox'>";
            echo "<div class='status-line info'>?? Starting FORCE COPY deployment...</div>";
            echo "<div class='status-line info'>?? Total directories to process: $total_dirs</div>";
            echo "<div class='status-line info'>?? Target base path: $base_path</div>";
            echo "<div class='status-line warning'>?? FORCE OVERWRITE is ENABLED - Existing folders will be replaced!</div>";
            echo "<div class='status-line info'>????????????????????????????????????????</div>";
            
            // Process each directory
            foreach ($target_dirs as $index => $dir) {
                $current_dir++;
                $percentage = round(($current_dir / $total_dirs) * 100);
                $target_path = "$base_path/$dir";
                $target_system = "$target_path/system";
                $target_ui = "$target_path/ui";
                
                // Create directory if doesn't exist
                if (!is_dir($target_path)) {
                    if (mkdir($target_path, 0755, true)) {
                        $stats['created']++;
                        echo "<div class='status-line info'>? $dir: Directory created</div>";
                    } else {
                        $stats['failed']++;
                        echo "<div class='status-line error'>? $dir: Failed to create directory</div>";
                        $results[] = ['name' => $dir, 'status' => 'failed', 'reason' => 'Cannot create directory'];
                        continue;
                    }
                }
                
                // Check if folders exist and mark for overwrite
                $had_system = is_dir($target_system);
                $had_ui = is_dir($target_ui);
                
                if ($had_system || $had_ui) {
                    echo "<div class='status-line overwrite'>?? $dir: Existing folders found - Overwriting...</div>";
                }
                
                // FORCE COPY system folder (remove existing first)
                $copy_success = true;
                $copied_items = [];
                
                // Remove existing system folder if it exists
                if (is_dir($target_system)) {
                    remove_directory($target_system);
                    echo "<div class='status-line overwrite'>  ?? Removed existing system folder</div>";
                }
                
                // Copy system folder
                if (recurse_copy_force($source_system, $target_system)) {
                    $copied_items[] = "system";
                } else {
                    $copy_success = false;
                }
                
                // Remove existing ui folder if it exists
                if (is_dir($target_ui)) {
                    remove_directory($target_ui);
                    echo "<div class='status-line overwrite'>  ?? Removed existing ui folder</div>";
                }
                
                // Copy ui folder
                if (recurse_copy_force($source_ui, $target_ui)) {
                    $copied_items[] = "ui";
                } else {
                    $copy_success = false;
                }
                
                if ($copy_success) {
                    $stats['overwritten']++;
                    $status_class = "success";
                    $status_text = "? Copied: " . implode(', ', $copied_items);
                    $results[] = ['name' => $dir, 'status' => 'success'];
                    
                    // Calculate size added
                    $system_size = get_dir_size($target_system);
                    $ui_size = get_dir_size($target_ui);
                    $stats['total_size'] += ($system_size + $ui_size);
                    
                    echo "<div class='status-line success'>  $status_text</div>";
                } else {
                    $stats['failed']++;
                    echo "<div class='status-line error'>  ? Failed to copy folders</div>";
                    $results[] = ['name' => $dir, 'status' => 'failed', 'reason' => 'Copy failed'];
                }
                
                // Update progress via JavaScript
                echo "<script>
                    document.getElementById('progressFill').style.width = '{$percentage}%';
                    document.getElementById('progressFill').innerHTML = '{$percentage}%';
                    document.getElementById('statusBox').scrollTop = document.getElementById('statusBox').scrollHeight;
                </script>";
                
                flush();
                ob_flush();
            }
            
            echo "<div class='status-line info'>????????????????????????????????????????</div>";
            echo "<div class='status-line success'>? FORCE COPY deployment completed!</div>";
            echo "</div>";
            
            // Display summary
            echo "<div class='summary'>";
            echo "<h3>?? FORCE COPY Summary</h3>";
            echo "<div class='summary-stats'>";
            echo "<div class='stat-card'><span class='stat-number'>{$stats['created']}</span><span class='stat-label'>Directories Created</span></div>";
            echo "<div class='stat-card'><span class='stat-number'>{$stats['overwritten']}</span><span class='stat-label'>Overwritten/Updated</span></div>";
            echo "<div class='stat-card'><span class='stat-number'>{$stats['failed']}</span><span class='stat-label'>Failed</span></div>";
            echo "<div class='stat-card'><span class='stat-number'>" . format_size($stats['total_size']) . "</span><span class='stat-label'>Total Data Deployed</span></div>";
            echo "<div class='stat-card'><span class='stat-number'>$total_dirs</span><span class='stat-label'>Total Processed</span></div>";
            echo "</div>";
            
            // Show success list
            if ($stats['overwritten'] > 0) {
                echo "<details style='margin-top: 15px;'>";
                echo "<summary style='cursor: pointer; font-weight: bold;'>? Successfully deployed to ({$stats['overwritten']} directories)</summary>";
                echo "<div style='margin-top: 10px; max-height: 200px; overflow-y: auto;'>";
                foreach ($results as $result) {
                    if ($result['status'] == 'success') {
                        echo "• {$result['name']}<br>";
                    }
                }
                echo "</div></details>";
            }
            
            // Show failed list
            if ($stats['failed'] > 0) {
                echo "<details style='margin-top: 10px;'>";
                echo "<summary style='cursor: pointer; font-weight: bold; color: #ffcc00;'>? Failed ({$stats['failed']} directories)</summary>";
                echo "<div style='margin-top: 10px; max-height: 200px; overflow-y: auto;'>";
                foreach ($results as $result) {
                    if ($result['status'] == 'failed') {
                        $reason = isset($result['reason']) ? " - {$result['reason']}" : "";
                        echo "• {$result['name']}{$reason}<br>";
                    }
                }
                echo "</div></details>";
            }
            
            echo "</div>";
            
            // Post-deployment instructions
            echo "<div class='info-box' style='margin-top: 20px;'>";
            echo "<h3>?? Post-Deployment Tasks</h3>";
            echo "<p>Run these commands via SSH to set correct permissions:</p>";
            echo "<pre>
# Set ownership to www-data
chown -R www-data:www-data $base_path/*/

# Set directory permissions
find $base_path/*/ -type d -exec chmod 755 {} \\;

# Set file permissions
find $base_path/*/ -type f -exec chmod 644 {} \\;

# Restart web server (optional)
systemctl restart apache2  # For Apache
# or
systemctl restart nginx     # For Nginx
            </pre>";
            echo "<button class='button' onclick='copyCommands()'>?? Copy Commands</button>";
            echo "</div>";
            ?>
        </div>
        
        <div class="footer">
            <p>FORCE COPY Deployment | Time: <?php echo date('Y-m-d H:i:s'); ?></p>
        </div>
    </div>
    
    <script>
        function copyCommands() {
            const commands = `chown -R www-data:www-data <?php echo $base_path; ?>/*/\nfind <?php echo $base_path; ?>/*/ -type d -exec chmod 755 {} \\;\nfind <?php echo $base_path; ?>/*/ -type f -exec chmod 644 {} \\;`;
            navigator.clipboard.writeText(commands).then(() => {
                alert('Commands copied to clipboard!');
            });
        }
        
        // Auto-scroll status box
        const statusBox = document.getElementById('statusBox');
        if (statusBox) {
            statusBox.scrollTop = statusBox.scrollHeight;
        }
    </script>
</body>
</html>
<?php
ob_end_flush();
?>