<?php
/**
 * Manual File Copy from temp/extract/
 * File: manual_copy.php
 * 
 * Manually copies files from temp/extract/ to root to test and show errors
 */

session_start();
require_once 'config.php';
requireLogin();

if ($_SESSION['role'] !== 'admin') {
    die('Access denied. Admin only.');
}

$logs = [];
$errors = [];
$copied_files = [];
$skipped_files = [];

// ==========================================
// COPY FUNCTION WITH DETAILED LOGGING
// ==========================================
function copyUpdateFiles($source, $dest, &$logs, &$errors, &$copied_files, &$skipped_files, $level = 0) {
    $excludeFiles = ['config.php', 'license.key', '.htaccess', 'db_connect.php'];
    $excludeDirs = ['backups', 'temp', 'cache', 'uploads', 'logs'];
    
    if (!is_dir($source)) {
        $errors[] = "Source directory doesn't exist: $source";
        return false;
    }
    
    $dir = @opendir($source);
    if (!$dir) {
        $errors[] = "Cannot open source directory: $source";
        return false;
    }
    
    while (($file = readdir($dir)) !== false) {
        if ($file === '.' || $file === '..') {
            continue;
        }
        
        if (in_array($file, $excludeFiles) || in_array($file, $excludeDirs)) {
            $skipped_files[] = $file . " (excluded)";
            continue;
        }
        
        $srcPath = $source . '/' . $file;
        $destPath = $dest . '/' . $file;
        
        if (is_dir($srcPath)) {
            $logs[] = str_repeat('  ', $level) . "📁 Directory: $file";
            
            if (!is_dir($destPath)) {
                if (@mkdir($destPath, 0755, true)) {
                    $logs[] = str_repeat('  ', $level) . "  ✓ Created: $destPath";
                } else {
                    $errors[] = "Failed to create directory: $destPath";
                    continue;
                }
            }
            
            copyUpdateFiles($srcPath, $destPath, $logs, $errors, $copied_files, $skipped_files, $level + 1);
        } else {
            $logs[] = str_repeat('  ', $level) . "📄 File: $file (" . filesize($srcPath) . " bytes)";
            
            if (@copy($srcPath, $destPath)) {
                $copied_files[] = $destPath;
                $logs[] = str_repeat('  ', $level) . "  ✓ Copied to: $destPath";
            } else {
                $errors[] = "Failed to copy: $srcPath → $destPath";
                $error = error_get_last();
                if ($error) {
                    $errors[] = "  Error: " . $error['message'];
                }
            }
        }
    }
    closedir($dir);
    
    return true;
}

// ==========================================
// CHECK WHAT'S IN TEMP/EXTRACT/
// ==========================================
$source_dir = 'temp/extract';
$files_exist = is_dir($source_dir);

$source_files = [];
if ($files_exist) {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($source_dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $file) {
        $source_files[] = str_replace('\\', '/', $file->getPathname());
    }
}

// ==========================================
// HANDLE MANUAL COPY
// ==========================================
$copy_executed = false;

if (isset($_POST['do_copy']) && $files_exist) {
    $copy_executed = true;
    
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    $logs[] = "=== STARTING MANUAL COPY ===";
    $logs[] = "Source: $source_dir";
    $logs[] = "Destination: " . __DIR__;
    $logs[] = "";
    
    copyUpdateFiles($source_dir, __DIR__, $logs, $errors, $copied_files, $skipped_files);
    
    $logs[] = "";
    $logs[] = "=== COPY COMPLETE ===";
    $logs[] = "Files copied: " . count($copied_files);
    $logs[] = "Files skipped: " . count($skipped_files);
    $logs[] = "Errors: " . count($errors);
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Manual File Copy</title>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background: #f5f5f5; padding: 20px; font-family: monospace; }
        .container { max-width: 1000px; }
        pre { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 5px; overflow-x: auto; font-size: 12px; max-height: 500px; overflow-y: auto; }
        .log-line { margin: 2px 0; }
        .error-line { color: #ff6b6b; }
        .success-line { color: #51cf66; }
    </style>
</head>
<body>

<div class="container">
    <h1 class="mb-4"><i class="bi bi-files"></i> Manual File Copy Tool</h1>
    
    <div class="alert alert-info">
        <strong>Purpose:</strong> Manually copy files from temp/extract/ to root and see detailed errors.
    </div>

    <!-- Source Files -->
    <?php if ($files_exist): ?>
    <div class="card mb-4">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="bi bi-folder2-open"></i> Files in temp/extract/ (<?= count($source_files) ?>)</h5>
        </div>
        <div class="card-body">
            <pre><?php
            foreach ($source_files as $file) {
                echo htmlspecialchars($file) . "\n";
            }
            ?></pre>
            
            <?php if (!$copy_executed): ?>
            <form method="POST" class="mt-3">
                <button type="submit" name="do_copy" class="btn btn-primary btn-lg" onclick="return confirm('Copy these files to root directory?')">
                    <i class="bi bi-arrow-right-circle"></i> Copy Files to Root Now
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="alert alert-warning">
        <strong>No files found in temp/extract/</strong>
        <p>The update needs to be run first to download and extract files.</p>
    </div>
    <?php endif; ?>

    <!-- Copy Results -->
    <?php if ($copy_executed): ?>
    
    <!-- Errors -->
    <?php if (!empty($errors)): ?>
    <div class="card border-danger mb-4">
        <div class="card-header bg-danger text-white">
            <h5 class="mb-0"><i class="bi bi-exclamation-triangle-fill"></i> Errors (<?= count($errors) ?>)</h5>
        </div>
        <div class="card-body">
            <pre><?php
            foreach ($errors as $error) {
                echo '<div class="error-line">' . htmlspecialchars($error) . '</div>';
            }
            ?></pre>
        </div>
    </div>
    <?php endif; ?>

    <!-- Copy Log -->
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="bi bi-list-ul"></i> Copy Log</h5>
        </div>
        <div class="card-body">
            <pre><?php
            foreach ($logs as $log) {
                if (strpos($log, '✓') !== false) {
                    echo '<div class="success-line">' . htmlspecialchars($log) . '</div>';
                } else {
                    echo '<div class="log-line">' . htmlspecialchars($log) . '</div>';
                }
            }
            ?></pre>
        </div>
    </div>

    <!-- Files Copied -->
    <?php if (!empty($copied_files)): ?>
    <div class="card border-success mb-4">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="bi bi-check-circle"></i> Files Successfully Copied (<?= count($copied_files) ?>)</h5>
        </div>
        <div class="card-body">
            <pre><?php
            foreach ($copied_files as $file) {
                echo htmlspecialchars($file) . "\n";
            }
            ?></pre>
        </div>
    </div>
    <?php endif; ?>

    <!-- Skipped Files -->
    <?php if (!empty($skipped_files)): ?>
    <div class="card border-info mb-4">
        <div class="card-header bg-info text-white">
            <h5 class="mb-0"><i class="bi bi-skip-forward"></i> Files Skipped (<?= count($skipped_files) ?>)</h5>
        </div>
        <div class="card-body">
            <pre><?php
            foreach ($skipped_files as $file) {
                echo htmlspecialchars($file) . "\n";
            }
            ?></pre>
        </div>
    </div>
    <?php endif; ?>

    <!-- Summary -->
    <div class="card border-primary">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="bi bi-clipboard-check"></i> Summary</h5>
        </div>
        <div class="card-body">
            <table class="table">
                <tr>
                    <td><strong>Files Copied:</strong></td>
                    <td><span class="badge bg-success"><?= count($copied_files) ?></span></td>
                </tr>
                <tr>
                    <td><strong>Files Skipped:</strong></td>
                    <td><span class="badge bg-info"><?= count($skipped_files) ?></span></td>
                </tr>
                <tr>
                    <td><strong>Errors:</strong></td>
                    <td><span class="badge bg-danger"><?= count($errors) ?></span></td>
                </tr>
            </table>
            
            <?php if (empty($errors) && !empty($copied_files)): ?>
                <div class="alert alert-success">
                    <h6>✓ Files Copied Successfully!</h6>
                    <p>The update files have been manually copied to the root directory.</p>
                    <p>You can now:</p>
                    <ul>
                        <li>Visit <a href="verify_update.php">verify_update.php</a> to confirm</li>
                        <li>Check your application to see if new files/features are there</li>
                        <li>Delete temp/extract/ folder to clean up</li>
                    </ul>
                </div>
            <?php elseif (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <h6>❌ Copy Failed</h6>
                    <p>See errors above for details. Common causes:</p>
                    <ul>
                        <li>Permission issues on specific directories</li>
                        <li>Disk space full</li>
                        <li>File conflicts</li>
                    </ul>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="text-center mt-4">
        <?php if ($copy_executed): ?>
            <a href="verify_update.php" class="btn btn-success btn-lg">
                <i class="bi bi-check-circle"></i> Verify Update
            </a>
            <a href="manual_copy.php" class="btn btn-secondary">
                <i class="bi bi-arrow-clockwise"></i> Reload
            </a>
        <?php endif; ?>
        <a href="admin_settings.php" class="btn btn-secondary">
            <i class="bi bi-gear"></i> Admin Settings
        </a>
    </div>

    <?php endif; ?>
</div>

</body>
</html>