<?php
// File: index.php (o filemanager.php) da posizionare su api.napolinelcuore.it
// Versione 1.3 - Correzione Logica di Login

// In un ambiente di produzione, è consigliabile disabilitare la visualizzazione diretta degli errori.
// ini_set('display_errors', 0);
// error_reporting(0);

session_start();

// --- CONFIGURAZIONE DI SICUREZZA ---
define('PASSWORD', getenv('CDN_ADMIN_PASSWORD') ?: '');
if (PASSWORD === '') {
    http_response_code(500);
    exit('CDN_ADMIN_PASSWORD non configurata');
}
define('ROOT_DIR', __DIR__);
define('BASE_URL', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST']);
// Lista dei tipi di file permessi per l'upload
define('ALLOWED_EXTENSIONS', ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf']);
// Lista di file da nascondere sempre
define('HIDDEN_FILES', ['.', '..', basename(__FILE__), '.htaccess', 'config.php']);

// --- GESTIONE LOGIN / LOGOUT & CSRF TOKEN ---
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . basename(__FILE__));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    // --- CORREZIONE LOGICA PASSWORD ---
    // Confronta direttamente la password inviata con quella definita.
    if ($_POST['password'] === PASSWORD) {
        $_SESSION['logged_in'] = true;
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // Genera token CSRF al login
        header('Location: ' . basename(__FILE__));
        exit;
    } else {
        $error = 'Password errata.';
    }
}

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    // FORM DI LOGIN (invariato, ma lo lascio per completezza)
    ?>
    <!DOCTYPE html><html lang="it"><head><meta charset="UTF-8"><title>Accesso</title><script src="https://cdn.tailwindcss.com"></script></head><body class="bg-stone-900 flex items-center justify-center h-screen"><div class="w-full max-w-sm"><form method="POST" class="bg-stone-800 shadow-md rounded-2xl px-8 pt-6 pb-8 mb-4"><h1 class="text-2xl font-bold text-white text-center mb-6">File Manager Login</h1><?php if(isset($error)) echo "<p class='bg-red-900/50 text-red-300 p-3 rounded-lg text-center mb-4'>$error</p>"; ?><div class="mb-4"><label class="block text-stone-300 text-sm font-bold mb-2" for="password">Password</label><input class="bg-stone-700 border border-stone-600 rounded-lg w-full py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-rose-500" id="password" name="password" type="password" placeholder="******************"></div><button class="bg-rose-600 hover:bg-rose-700 text-white font-bold py-2 px-4 rounded-lg focus:outline-none focus:shadow-outline w-full" type="submit">Accedi</button></form></div></body></html>
    <?php
    exit;
}

// --- LOGICA DEL FILE MANAGER ---

// Verifica del token CSRF per tutte le richieste POST e GET che modificano i dati
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die('Errore di sicurezza: Token CSRF non valido.');
    }
}
if (isset($_GET['delete'])) {
     if (!isset($_GET['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_GET['csrf_token'])) {
        die('Errore di sicurezza: Token CSRF non valido.');
    }
}

// Funzione per creare versioni WebP ridimensionate usando Imagick
function create_webp_versions($source_path, $dest_base_path, $widths = [300, 600, 1200]) {
    if (!class_exists('Imagick') && !class_exists('\Imagick')) {
        error_log('Imagick non è installato o abilitato su questo server.');
        return false;
    }
    try {
        $img = new \Imagick($source_path);
        $orig_w = $img->getImageWidth();
        $orig_h = $img->getImageHeight();
        foreach ($widths as $w) {
            $h = intval($orig_h * $w / $orig_w);
            $clone = clone $img;
            $clone->resizeImage($w, $h, \Imagick::FILTER_LANCZOS, 1);
            $clone->setImageFormat('webp');
            $clone->setImageCompressionQuality(85);
            $webp_path = $dest_base_path . "-{$w}.webp";
            $clone->writeImage($webp_path);
            $clone->destroy();
        }
        $img->destroy();
        return true;
    } catch (Exception $e) {
        error_log('Errore Imagick: ' . $e->getMessage());
        return false;
    }
}

function sanitize_path($path) {
    $real_root = realpath(ROOT_DIR);
    $real_user_path = realpath(ROOT_DIR . '/' . $path);
    if ($real_user_path === false || strpos($real_user_path, $real_root) !== 0) {
        return '';
    }
    return str_replace(ROOT_DIR, '', $real_user_path);
}

$current_path = isset($_GET['path']) ? sanitize_path($_GET['path']) : '';
$current_dir = ROOT_DIR . $current_path;

$action_message = '';
$action_success = true;

// Carica file
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload']) && $_FILES['fileToUpload']['error'] == UPLOAD_ERR_OK) {
    $file_name = basename($_FILES['fileToUpload']['name']);
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    // Controllo estensione
    if (!in_array($file_ext, ALLOWED_EXTENSIONS)) {
        $action_message = 'Errore: tipo di file non permesso.';
        $action_success = false;
    } else {
        // Nuovo nome file se fornito
        if (!empty($_POST['new_file_name'])) {
            $sanitized_name = preg_replace('/[^a-zA-Z0-9._-]/', '', $_POST['new_file_name']);
        } else {
            $sanitized_name = preg_replace('/[^a-zA-Z0-9._-]/', '', pathinfo($file_name, PATHINFO_FILENAME));
        }
        $target_file = $current_dir . '/' . $sanitized_name . '.' . $file_ext;
        
        if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
            // Se è un'immagine, crea le versioni webp
            if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
                $base_path = $current_dir . '/' . $sanitized_name;
                if (create_webp_versions($target_file, $base_path)) {
                    $action_message = 'File caricato e versioni WebP generate con successo.';
                } else {
                    $action_message = 'File caricato, ma errore nella generazione delle versioni WebP.';
                }
            } else {
                $action_message = 'File caricato con successo.';
            }
        } else {
            $action_message = 'Errore durante il caricamento del file.';
            $action_success = false;
        }
    }
}

// Rinomina file/cartella esistente
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rename_old']) && isset($_POST['rename_new'])) {
    $old = sanitize_path($_POST['rename_old']);
    $new = preg_replace('/[^a-zA-Z0-9._-]/', '', $_POST['rename_new']);
    if (!empty($old) && !empty($new)) {
        $old_path = ROOT_DIR . $old;
        $new_path = dirname($old_path) . '/' . $new;
        if (file_exists($new_path)) {
            $action_message = 'Esiste già un file/cartella con questo nome.';
            $action_success = false;
        } else {
            if (rename($old_path, $new_path)) {
                $action_message = 'Rinominato con successo.';
            } else {
                $action_message = 'Errore durante la rinomina.';
                $action_success = false;
            }
        }
    }
}

// Crea cartella
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_folder'])) {
    $folder_name = preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['new_folder']);
    if (!empty($folder_name)) {
        // Permessi sicuri: 0755
        if (!mkdir($current_dir . '/' . $folder_name, 0755)) {
            $action_message = 'Errore durante la creazione della cartella.';
            $action_success = false;
        } else {
            $action_message = 'Cartella creata con successo.';
        }
    }
}

// Elimina file o cartella
if (isset($_GET['delete'])) {
    $file_to_delete = sanitize_path($_GET['delete']);
    if (!empty($file_to_delete)) {
        $full_path = ROOT_DIR . $file_to_delete;
        if (is_dir($full_path)) {
            if (count(scandir($full_path)) == 2) {
                if (rmdir($full_path)) $action_message = 'Cartella eliminata.'; else { $action_message = 'Errore eliminazione cartella.'; $action_success = false; }
            } else {
                $action_message = 'Impossibile eliminare: la cartella non è vuota.'; $action_success = false;
            }
        } else {
            if (unlink($full_path)) $action_message = 'File eliminato.'; else { $action_message = 'Errore eliminazione file.'; $action_success = false; }
        }
    }
}

// Ottiene la lista di file e cartelle, nascondendo quelli sensibili
$files = array_diff(scandir($current_dir), HIDDEN_FILES);
$folders = [];
$items = [];
foreach ($files as $file) {
    if (is_dir($current_dir . '/' . $file)) $folders[] = $file; else $items[] = $file;
}

?>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CDN Cilentodoc</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;700;800&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>
    <style> body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #0c0a09; color: #e7e5e4; } .glass-effect { background: rgba(28, 25, 23, 0.6); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); } .file-item:hover { background-color: #292524; } </style>
</head>
<body class="antialiased">
    <div class="container mx-auto px-6 py-8">
        <div class="flex justify-between items-center mb-8"><h1 class="text-3xl font-bold text-white">File Manager</h1><a href="?logout=true" class="bg-rose-600 hover:bg-rose-700 text-white font-bold py-2 px-4 rounded-lg">Logout</a></div>
        <?php if ($action_message): ?><div class="p-4 mb-6 rounded-lg <?php echo $action_success ? 'bg-green-900/50 text-green-300' : 'bg-red-900/50 text-red-300'; ?>"><?php echo $action_message; ?></div><?php endif; ?>
        <div class="grid md:grid-cols-2 gap-8 mb-8">
            <div class="glass-effect p-6 rounded-xl"><h2 class="text-xl font-bold mb-4 text-white">Carica un File</h2><form method="POST" enctype="multipart/form-data"><input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>"><input type="file" name="fileToUpload" id="fileToUpload" class="block w-full text-sm text-stone-400 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-rose-50 file:text-rose-700 hover:file:bg-rose-100 mb-4"><input type="text" name="new_file_name" placeholder="Nuovo nome file (senza estensione)" class="bg-stone-700 border border-stone-600 rounded-lg w-full py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-rose-500 mb-4"><button type="submit" class="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-2 px-4 rounded-lg">Carica</button></form></div>
            <div class="glass-effect p-6 rounded-xl"><h2 class="text-xl font-bold mb-4 text-white">Crea Nuova Cartella</h2><form method="POST"><input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>"><input type="text" name="new_folder" placeholder="Nome cartella" class="bg-stone-800 border border-stone-700 rounded-lg w-full py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-rose-500 mb-4"><button type="submit" class="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-2 px-4 rounded-lg">Crea</button></form></div>
        </div>
        <div class="mb-4 text-stone-400"><a href="?path=" class="hover:text-rose-400">Home</a>
            <?php
            $path_parts = explode('/', trim($current_path, '/')); $built_path = '';
            foreach ($path_parts as $part) { if (empty($part)) continue; $built_path .= '/' . $part; echo ' / <a href="?path=' . urlencode($built_path) . '" class="hover:text-rose-400">' . htmlspecialchars($part) . '</a>'; }
            ?>
        </div>
        <div class="glass-effect rounded-xl overflow-hidden">
            <table class="w-full text-left">
                <thead class="bg-stone-800"><tr><th class="p-4">Nome</th><th class="p-4 hidden md:table-cell">Dimensione</th><th class="p-4 hidden md:table-cell">Link Pubblico</th><th class="p-4 text-right">Azioni</th></tr></thead>
                <tbody>
                    <?php if ($current_path !== ''): ?><tr class="file-item border-b border-stone-700"><td class="p-4"><a href="?path=<?php echo urlencode(dirname($current_path)); ?>" class="flex items-center gap-2 text-sky-400 hover:text-sky-300"><i data-lucide="corner-left-up"></i> ...</a></td><td></td><td></td><td></td></tr><?php endif; ?>
                    <?php foreach ($folders as $folder): ?>
                    <tr class="file-item border-b border-stone-700">
                        <td class="p-4">
                            <a href="?path=<?php echo urlencode($current_path . '/' . $folder); ?>" class="flex items-center gap-2 text-white font-medium hover:text-rose-400"><i data-lucide="folder" class="text-yellow-400"></i> <?php echo htmlspecialchars($folder); ?></a>
                        </td>
                        <td class="p-4 text-stone-400 hidden md:table-cell">--</td>
                        <td class="p-4 text-stone-400 hidden md:table-cell">--</td>
                        <td class="p-4 text-right">
                            <form method="POST" style="display:inline-block;" onsubmit="return confirm('Vuoi davvero rinominare questa cartella?');">
                                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                                <input type="hidden" name="rename_old" value="<?php echo htmlspecialchars($current_path . '/' . $folder); ?>">
                                <input type="text" name="rename_new" placeholder="Nuovo nome" class="bg-stone-800 border border-stone-700 rounded-lg px-2 py-1 text-white text-xs" style="width:90px;">
                                <button type="submit" class="bg-sky-700 hover:bg-sky-800 text-white text-xs font-bold py-1 px-2 rounded">Rinomina</button>
                            </form>
                            <a href="?path=<?php echo urlencode($current_path); ?>&delete=<?php echo urlencode($current_path . '/' . $folder); ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" onclick="return confirm('Sei sicuro? La cartella deve essere vuota.');" class="text-red-500 hover:text-red-400"><i data-lucide="trash-2"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php foreach ($items as $item): 
                        $file_path = $current_path . '/' . $item;
                        $public_url = BASE_URL . str_replace(' ', '%20', $file_path);
                    ?><tr class="file-item border-b border-stone-700"><td class="p-4"><span class="flex items-center gap-2 text-white"><i data-lucide="file" class="text-stone-400"></i> <?php echo htmlspecialchars($item); ?></span></td><td class="p-4 text-stone-400 hidden md:table-cell"><?php echo round(filesize($current_dir . '/' . $item) / 1024, 2); ?> KB</td><td class="p-4 text-stone-400 hidden md:table-cell"><a href="<?php echo htmlspecialchars($public_url); ?>" target="_blank" class="text-sky-400 hover:underline">Apri</a></td><td class="p-4 text-right">
                        <form method="POST" style="display:inline-block;" onsubmit="return confirm('Vuoi davvero rinominare?');">
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                            <input type="hidden" name="rename_old" value="<?php echo htmlspecialchars($current_path . '/' . $item); ?>">
                            <input type="text" name="rename_new" placeholder="Nuovo nome" class="bg-stone-800 border border-stone-700 rounded-lg px-2 py-1 text-white text-xs" style="width:90px;">
                            <button type="submit" class="bg-sky-700 hover:bg-sky-800 text-white text-xs font-bold py-1 px-2 rounded">Rinomina</button>
                        </form>
                        <button class="copy-link-btn bg-stone-700 hover:bg-stone-600 text-white text-xs font-bold py-1 px-2 rounded mr-2" data-link="<?php echo htmlspecialchars($public_url); ?>">Copia Link</button>
                        <a href="?path=<?php echo urlencode($current_path); ?>&delete=<?php echo urlencode($file_path); ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" onclick="return confirm('Sei sicuro di voler eliminare questo file?');" class="text-red-500 hover:text-red-400 inline-block align-middle"><i data-lucide="trash-2"></i></a>
                    </td></tr><?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <script>
        lucide.createIcons();
        document.querySelectorAll('.copy-link-btn').forEach(button => {
            button.addEventListener('click', function() {
                const link = this.dataset.link;
                navigator.clipboard.writeText(link).then(() => {
                    const originalText = this.textContent;
                    this.textContent = 'Copiato!';
                    setTimeout(() => { this.textContent = originalText; }, 1500);
                }).catch(err => console.error('Errore copia link:', err));
            });
        });
    </script>
</body>
</html>
