<?php
/**
 * Rig N Dig - Advanced File Manager
 * Complete control over your site files without cPanel
 */

$adminTitle = 'Advanced File Manager';
require_once __DIR__ . '/includes/header.php';

// Authorization check
if ($_SESSION['admin_role'] !== 'super_admin') {
    echo '<div class="bg-red-900 border border-red-600 text-red-200 p-4 rounded">Access Denied. Super Admin required.</div>';
    include __DIR__ . '/includes/footer.php';
    exit;
}

$baseDir = ROOT_PATH;
$currentSub = isset($_GET['dir']) ? sanitize($_GET['dir']) : '';
$currentPath = realpath($baseDir . '/' . $currentSub);

// Security: Prevent directory traversal
if (!$currentPath || strpos($currentPath, realpath($baseDir)) !== 0) {
    $currentPath = realpath($baseDir);
    $currentSub = '';
}

// ─── HANDLERS ────────────────────────────────────────────────────────

// 1. New Folder
if (isset($_POST['action']) && $_POST['action'] === 'new_folder') {
    $folderName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $_POST['folder_name']);
    $newDir = $currentPath . '/' . $folderName;
    if ($folderName && !file_exists($newDir)) {
        if (@mkdir($newDir, 0755, true)) $_SESSION['flash']['success'] = "Folder created: $folderName";
        else $_SESSION['flash']['error'] = "Failed to create folder.";
    }
    header("Location: filemanager.php?dir=" . urlencode($currentSub)); exit;
}

// 2. Upload File
if (isset($_POST['action']) && $_POST['action'] === 'upload') {
    if (!empty($_FILES['site_file'])) {
        $file = $_FILES['site_file'];
        $dest = $currentPath . '/' . basename($file['name']);
        if (move_uploaded_file($file['tmp_name'], $dest)) {
            $_SESSION['flash']['success'] = "File uploaded: " . basename($file['name']);
        } else {
            $_SESSION['flash']['error'] = "Upload failed.";
        }
    }
    header("Location: filemanager.php?dir=" . urlencode($currentSub)); exit;
}

// 3. Delete Item
if (isset($_GET['delete'])) {
    $target = realpath($currentPath . '/' . sanitize($_GET['delete']));
    if ($target && strpos($target, realpath($baseDir)) === 0 && !is_protected($target)) {
        if (is_dir($target)) {
            // Primitive recursive delete
            $it = new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS);
            $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
            foreach($files as $file) {
                if ($file->isDir()) rmdir($file->getRealPath());
                else unlink($file->getRealPath());
            }
            rmdir($target);
        } else {
            unlink($target);
        }
        $_SESSION['flash']['success'] = "Item deleted successfully.";
    }
    header("Location: filemanager.php?dir=" . urlencode($currentSub)); exit;
}

// 4. Rename Item
if (isset($_POST['action']) && $_POST['action'] === 'rename') {
    $old = realpath($currentPath . '/' . sanitize($_POST['old_name']));
    $new = $currentPath . '/' . preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $_POST['new_name']);
    if ($old && strpos($old, realpath($baseDir)) === 0 && !is_protected($old)) {
        if (rename($old, $new)) $_SESSION['flash']['success'] = "Renamed successfully.";
        else $_SESSION['flash']['error'] = "Rename failed.";
    }
    header("Location: filemanager.php?dir=" . urlencode($currentSub)); exit;
}

// 5. CHMOD (Permissions)
if (isset($_POST['action']) && $_POST['action'] === 'chmod') {
    $target = realpath($currentPath . '/' . sanitize($_POST['item_name']));
    $mode = octdec($_POST['mode']);
    if ($target && strpos($target, realpath($baseDir)) === 0) {
        if (chmod($target, $mode)) $_SESSION['flash']['success'] = "Permissions updated to " . $_POST['mode'];
        else $_SESSION['flash']['error'] = "Failed to update permissions.";
    }
    header("Location: filemanager.php?dir=" . urlencode($currentSub)); exit;
}

// 6. Save File Edit
if (isset($_POST['action']) && $_POST['action'] === 'save_edit') {
    $target = realpath($currentPath . '/' . sanitize($_POST['item_name']));
    if ($target && strpos($target, realpath($baseDir)) === 0 && !is_dir($target)) {
        if (file_put_contents($target, $_POST['content'])) $_SESSION['flash']['success'] = "File saved successfully.";
        else $_SESSION['flash']['error'] = "Failed to save file. Check permissions.";
    }
    header("Location: filemanager.php?dir=" . urlencode($currentSub)); exit;
}

// Helper: Check if path is protected
function is_protected($path) {
    $name = basename($path);
    $protected = ['config.php', '.htaccess', 'logs', 'uploads', 'admin'];
    // Don't allow deleting core folders from root, but allow editing within them
    if (dirname($path) === realpath(ROOT_PATH) && in_array($name, $protected)) return true;
    return false;
}

// Read items
$items = array_diff(scandir($currentPath), ['.', '..']);
natcasesort($items);
$dirs = [];
$files = [];

foreach ($items as $item) {
    $fullPath = $currentPath . '/' . $item;
    $isDir = is_dir($fullPath);
    $info = [
        'name' => $item,
        'path' => $currentSub ? $currentSub . '/' . $item : $item,
        'size' => $isDir ? '-' : formatBytes(filesize($fullPath)),
        'modified' => date("Y-m-d H:i", filemtime($fullPath)),
        'permissions' => substr(sprintf('%o', fileperms($fullPath)), -4),
        'is_protected' => is_protected($fullPath),
        'is_editable' => !$isDir && in_array(pathinfo($item, PATHINFO_EXTENSION), ['php', 'html', 'css', 'js', 'sql', 'txt', 'json'])
    ];
    if ($isDir) $dirs[] = $info;
    else $files[] = $info;
}

function formatBytes($bytes, $precision = 1) { 
    $units = ['B', 'KB', 'MB', 'GB']; 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow]; 
}
?>

<div class="mb-10">
  <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
    <div>
      <h1 class="text-2xl font-black text-white uppercase tracking-tighter mb-1">File Architecture</h1>
      <div class="flex items-center gap-2 text-[10px] font-bold text-gray-500 uppercase tracking-widest leading-none">
        <a href="filemanager.php" class="hover:text-orange-500">Root</a>
        <?php if ($currentSub): ?>
          <?php 
          $crumbs = explode('/', $currentSub); $running = '';
          foreach ($crumbs as $c): $running .= ($running ? '/' : '') . $c;
          ?>
            <span>/</span>
            <a href="filemanager.php?dir=<?= urlencode($running) ?>" class="hover:text-orange-500"><?= e($c) ?></a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
    
    <div class="flex flex-wrap gap-2">
      <button onclick="openModal('upload-modal')" class="btn-outline py-2.5 px-4 text-[10px] font-black uppercase tracking-widest">⬆️ Upload</button>
      <button onclick="openModal('folder-modal')" class="btn-outline py-2.5 px-4 text-[10px] font-black uppercase tracking-widest">📂 Folder</button>
      <a href="updater.php" class="btn-primary py-2.5 px-4 text-[10px] font-black uppercase tracking-widest">🔄 Updater</a>
    </div>
  </div>

  <!-- TABLE -->
  <div class="card-dark overflow-hidden border border-white/5">
    <table class="data-table">
      <thead class="bg-navy-800">
        <tr>
          <th class="w-1/2">Name</th>
          <th>Size</th>
          <th>Perm</th>
          <th>Modified</th>
          <th class="text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-white/5">
        <?php if ($currentSub): ?>
        <?php $parent = dirname($currentSub); if ($parent === '.') $parent = ''; ?>
        <tr class="hover:bg-white/[0.02] cursor-pointer" onclick="window.location='filemanager.php?dir=<?= urlencode($parent) ?>'">
          <td colspan="5" class="py-4 px-4 text-orange-500 font-black text-xs uppercase tracking-widest">⤴️ Parent Directory</td>
        </tr>
        <?php endif; ?>

        <?php foreach (array_merge($dirs, $files) as $item): $isDir = in_array($item, $dirs); ?>
        <tr class="group hover:bg-white/[0.02] transition-colors">
          <td class="py-4 px-4 flex items-center gap-3">
            <span class="text-xl"><?= $isDir ? '📁' : '📄' ?></span>
            <div class="flex flex-col">
              <span class="text-sm font-bold <?= $isDir ? 'text-white' : 'text-gray-300' ?>">
                <?php if ($isDir): ?>
                <a href="filemanager.php?dir=<?= urlencode($item['path']) ?>" class="hover:text-orange-500 transition-colors"><?= e($item['name']) ?></a>
                <?php else: ?>
                <?= e($item['name']) ?>
                <?php endif; ?>
              </span>
              <?php if ($item['is_protected']): ?>
              <span class="text-[9px] font-black text-red-500 uppercase tracking-widest mt-0.5">System Lock</span>
              <?php endif; ?>
            </div>
          </td>
          <td class="text-xs text-gray-500"><?= $item['size'] ?></td>
          <td class="text-xs font-mono text-gray-500"><?= $item['permissions'] ?></td>
          <td class="text-[10px] text-gray-600 font-bold uppercase"><?= $item['modified'] ?></td>
          <td class="px-4 text-right">
             <div class="flex items-center justify-end gap-1.5 opacity-0 group-hover:opacity-100 transition-all">
                <?php if ($item['is_editable']): ?>
                <button onclick="editFile('<?= e($item['name']) ?>')" class="p-1.5 hover:bg-orange-600/20 rounded transition-colors text-orange-500" title="Edit Content">✏️</button>
                <?php endif; ?>
                <button onclick="chmodItem('<?= e($item['name']) ?>', '<?= $item['permissions'] ?>')" class="p-1.5 hover:bg-blue-600/20 rounded transition-colors" title="Permissions">🛡️</button>
                <button onclick="renameItem('<?= e($item['name']) ?>')" class="p-1.5 hover:bg-white/10 rounded transition-colors" title="Rename">🔡</button>
                <?php if (!$item['is_protected']): ?>
                <a href="?dir=<?= urlencode($currentSub) ?>&delete=<?= urlencode($item['name']) ?>" 
                   onclick="return confirm('EXTERMINATE THIS ITEM? This cannot be undone.')" 
                   class="p-1.5 hover:bg-red-600/20 rounded transition-colors" title="Extinguish">🗑️</a>
                <?php endif; ?>
             </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- MODALS -->
<div id="folder-modal" class="modal-overlay hidden">
    <div class="modal-box max-w-sm">
        <h3 class="text-xl font-black text-white uppercase tracking-tighter mb-4">Create New Sector</h3>
        <form method="POST">
            <input type="hidden" name="action" value="new_folder">
            <input type="text" name="folder_name" placeholder="folder_name" required class="mb-4">
            <div class="flex justify-end gap-3">
                <button type="button" onclick="closeModal('folder-modal')" class="btn-outline px-4 py-2 text-[10px] font-black uppercase">Cancel</button>
                <button type="submit" class="btn-primary px-4 py-2 text-[10px] font-black uppercase">Initialize</button>
            </div>
        </form>
    </div>
</div>

<div id="upload-modal" class="modal-overlay hidden">
    <div class="modal-box max-w-sm">
        <h3 class="text-xl font-black text-white uppercase tracking-tighter mb-4">Upload Asset</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="upload">
            <input type="file" name="site_file" required class="mb-4 text-xs">
            <div class="flex justify-end gap-3">
                <button type="button" onclick="closeModal('upload-modal')" class="btn-outline px-4 py-2 text-[10px] font-black uppercase">Cancel</button>
                <button type="submit" class="btn-primary px-4 py-2 text-[10px] font-black uppercase">Transmit</button>
            </div>
        </form>
    </div>
</div>

<div id="rename-modal" class="modal-overlay hidden">
    <div class="modal-box max-w-sm">
        <h3 class="text-xl font-black text-white uppercase tracking-tighter mb-4">Rename Protocol</h3>
        <form method="POST">
            <input type="hidden" name="action" value="rename">
            <input type="hidden" name="old_name" id="rename-old">
            <input type="text" name="new_name" id="rename-new" required class="mb-4">
            <div class="flex justify-end gap-3">
                <button type="button" onclick="closeModal('rename-modal')" class="btn-outline px-4 py-2 text-[10px] font-black uppercase">Cancel</button>
                <button type="submit" class="btn-primary px-4 py-2 text-[10px] font-black uppercase">Update</button>
            </div>
        </form>
    </div>
</div>

<div id="chmod-modal" class="modal-overlay hidden">
    <div class="modal-box max-w-sm">
        <h3 class="text-xl font-black text-white uppercase tracking-tighter mb-4">Security Level</h3>
        <form method="POST">
            <input type="hidden" name="action" value="chmod">
            <input type="hidden" name="item_name" id="chmod-name">
            <div class="text-xs text-gray-500 mb-2 uppercase font-black">Numeric Mask (e.g. 0644, 0755)</div>
            <input type="text" name="mode" id="chmod-mode" required class="mb-4 font-mono">
            <div class="flex justify-end gap-3">
                <button type="button" onclick="closeModal('chmod-modal')" class="btn-outline px-4 py-2 text-[10px] font-black uppercase">Cancel</button>
                <button type="submit" class="btn-primary px-4 py-2 text-[10px] font-black uppercase">Set Perms</button>
            </div>
        </form>
    </div>
</div>

<div id="edit-modal" class="modal-overlay hidden">
    <div class="modal-box max-w-5xl h-[80vh] flex flex-col">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-xl font-black text-white uppercase tracking-tighter" id="edit-title">Edit Component</h3>
            <button onclick="closeModal('edit-modal')" class="text-gray-500 hover:text-white">✕</button>
        </div>
        <form method="POST" class="flex-1 flex flex-col">
            <input type="hidden" name="action" value="save_edit">
            <input type="hidden" name="item_name" id="edit-name">
            <textarea name="content" id="edit-content" class="flex-1 font-mono text-sm bg-navy-950 p-4 border-white/5 resize-none leading-relaxed" spellcheck="false"></textarea>
            <div class="flex justify-end gap-3 mt-4 pt-4 border-t border-white/5">
                <button type="button" onclick="closeModal('edit-modal')" class="btn-outline px-6 py-2.5 text-[10px] font-black uppercase">Abandon</button>
                <button type="submit" class="btn-primary px-6 py-2.5 text-[10px] font-black uppercase">Safe Save</button>
            </div>
        </form>
    </div>
</div>

<script>
function openModal(id) { document.getElementById(id).classList.remove('hidden'); }
function closeModal(id) { document.getElementById(id).classList.add('hidden'); }

function renameItem(name) {
    document.getElementById('rename-old').value = name;
    document.getElementById('rename-new').value = name;
    openModal('rename-modal');
}

function chmodItem(name, mode) {
    document.getElementById('chmod-name').value = name;
    document.getElementById('chmod-mode').value = mode;
    openModal('chmod-modal');
}

function editFile(name) {
    document.getElementById('edit-title').innerText = 'Editing Source: ' + name;
    document.getElementById('edit-name').value = name;
    document.getElementById('edit-content').value = 'Loading...';
    openModal('edit-modal');
    
    // Fetch file content via AJAX or simpler: just use a hidden path and read it here
    fetch('api/get-file-content.php?dir=' + encodeURIComponent('<?= urlencode($currentSub) ?>') + '&file=' + encodeURIComponent(name))
        .then(r => r.text())
        .then(t => {
            document.getElementById('edit-content').value = t;
        });
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>

