<?php
/**
 * Storage Migration Script for Shared Hosting
 *
 * Script ini akan memindahkan files dari storage/app/public ke public folder.
 * Termasuk: avatars, logos, dan folder lainnya.
 * Jalankan sekali saja, lalu hapus file ini.
 *
 * URL: https://presensi.nizhamia.sch.id/migrate-avatars.php?key=nizhamia-migrate-2024
 */

// Security check
$secretKey = 'nizhamia-migrate-2024';
$providedKey = $_GET['key'] ?? '';

if ($providedKey !== $secretKey) {
    die('Akses ditolak. Tambahkan ?key=nizhamia-migrate-2024 ke URL');
}

echo "<h2>Storage Migration Script</h2>";
echo "<pre>";

$publicPath = __DIR__;
$storagePath = dirname($publicPath) . '/storage/app/public';

echo "Public Path: $publicPath\n";
echo "Storage Path: $storagePath\n\n";

// Folders to migrate
$foldersToMigrate = ['avatars', 'logos', 'documents'];
$totalSuccess = 0;
$totalFailed = 0;

foreach ($foldersToMigrate as $folder) {
    echo "=== Migrating: $folder ===\n";

    $sourceDir = $storagePath . '/' . $folder;
    $targetDir = $publicPath . '/' . $folder;

    echo "Source: $sourceDir\n";
    echo "Target: $targetDir\n";

    // Check if source exists
    if (!is_dir($sourceDir)) {
        echo "Source folder tidak ada.\n";

        // Check if target exists
        if (is_dir($targetDir)) {
            $files = scandir($targetDir);
            $files = array_filter($files, fn($f) => !in_array($f, ['.', '..']));
            echo "Target folder sudah ada dengan " . count($files) . " files.\n";
        } else {
            echo "Membuat folder kosong...\n";
            if (@mkdir($targetDir, 0755, true)) {
                echo "Folder $folder berhasil dibuat di public/\n";
            } else {
                echo "GAGAL membuat folder $folder.\n";
            }
        }
        echo "\n";
        continue;
    }

    // Create target directory if not exists
    if (!is_dir($targetDir)) {
        if (!@mkdir($targetDir, 0755, true)) {
            echo "GAGAL membuat folder target: $targetDir\n\n";
            continue;
        }
        echo "Folder target berhasil dibuat.\n";
    }

    // Get files from source
    $files = scandir($sourceDir);
    $files = array_filter($files, fn($f) => !in_array($f, ['.', '..']));

    echo "Ditemukan " . count($files) . " file untuk dipindahkan.\n";

    $success = 0;
    $failed = 0;

    foreach ($files as $file) {
        $sourcePath = $sourceDir . '/' . $file;
        $destPath = $targetDir . '/' . $file;

        if (is_file($sourcePath)) {
            // Copy file
            if (copy($sourcePath, $destPath)) {
                // Verify copy
                if (filesize($destPath) === filesize($sourcePath)) {
                    // Delete source after successful copy
                    unlink($sourcePath);
                    echo "[OK] $file\n";
                    $success++;
                } else {
                    unlink($destPath); // Remove incomplete copy
                    echo "[FAIL - size mismatch] $file\n";
                    $failed++;
                }
            } else {
                echo "[FAIL - copy failed] $file\n";
                $failed++;
            }
        }
    }

    echo "Hasil $folder: $success berhasil, $failed gagal\n";
    $totalSuccess += $success;
    $totalFailed += $failed;

    // Try to remove source directory if empty
    $remaining = scandir($sourceDir);
    $remaining = array_filter($remaining, fn($f) => !in_array($f, ['.', '..']));
    if (empty($remaining)) {
        rmdir($sourceDir);
        echo "Folder source kosong, dihapus.\n";
    }

    echo "\n";
}

echo "=== TOTAL HASIL ===\n";
echo "Total Berhasil: $totalSuccess\n";
echo "Total Gagal: $totalFailed\n";

echo "\n</pre>";
echo "<hr>";
echo "<p><strong>HAPUS FILE INI SETELAH SELESAI!</strong></p>";
echo "<p>Test akses:</p>";
echo "<ul>";
echo "<li><a href='/avatars/' target='_blank'>/avatars/</a></li>";
echo "<li><a href='/logos/' target='_blank'>/logos/</a></li>";
echo "</ul>";
