<?php
// === CONFIGURATION ===
// Define base paths for different directories
$basePath  = dirname(__DIR__) . '/';
$toolDir   = $basePath . 'tools/';
$cssDir    = $basePath . 'assets/css/';
$jsDir     = $basePath . 'assets/js/';
$iconDir   = $basePath . 'assets/icons/';

// Create directories if they don't exist
$directories = [$toolDir, $cssDir, $jsDir, $iconDir];
foreach ($directories as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
}

// === UPLOAD & INSTALL TOOL ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['addon'])) {
    $fileTmp  = $_FILES['addon']['tmp_name'];

    // Extract zip contents to appropriate directories
    $zip = new ZipArchive;
    if ($zip->open($fileTmp)) {
        for ($i = 0; $i < $zip->numFiles; $i++) {
            $entry = $zip->getNameIndex($i);
            $ext   = strtolower(pathinfo($entry, PATHINFO_EXTENSION));
            switch ($ext) {
                case 'php': $zip->extractTo($toolDir, [$entry]); break;
                case 'css': $zip->extractTo($cssDir, [$entry]); break;
                case 'js':  $zip->extractTo($jsDir, [$entry]); break;
                case 'png': $zip->extractTo($iconDir, [$entry]); break;
            }
        }
        $zip->close();
        $msg = ['success', 'Tool installed successfully!'];
    } else {
        $msg = ['error', 'Failed to unzip the tool.'];
    }
}

// === DELETE TOOL ===
if (isset($_GET['delete'])) {
    $tool = basename($_GET['delete']);
    $base = pathinfo($tool, PATHINFO_FILENAME);

    // List of possible files to delete
    $files = [
        $toolDir . $base . '.php',
        $cssDir . $base . '.css',
        $jsDir . $base . '.js',
        $iconDir . $base . '.png'
    ];

    // Delete existing files
    foreach ($files as $file) {
        if (file_exists($file)) {
            unlink($file);
        }
    }
    header("Location: install-tools.php?msg=deleted");
    exit;
}

// === DOWNLOAD TOOL ===
if (isset($_GET['download'])) {
    $tool = basename($_GET['download']);
    $base = pathinfo($tool, PATHINFO_FILENAME);
    $tempDir = sys_get_temp_dir();
    $addonFile = $tempDir . '/' . $base . '.zip';

    // Create zip file
    $zip = new ZipArchive;
    $zip->open($addonFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);

    // Files to include in zip
    $sources = [
        $toolDir . $base . '.php',
        $cssDir . $base . '.css',
        $jsDir . $base . '.js',
        $iconDir . $base . '.png'
    ];

    // Add existing files to zip
    foreach ($sources as $src) {
        if (file_exists($src)) {
            $zip->addFile($src, basename($src));
        }
    }

    $zip->close();
    $addonFinal = $tempDir . '/' . $base . '.addon';
    rename($addonFile, $addonFinal);

    // Send file to user
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($addonFinal) . '"');
    readfile($addonFinal);
    unlink($addonFinal);
    exit;
}

// === HELPER FUNCTION ===
function formatName($file) {
    // Convert filename to readable format (e.g., my-tool -> My Tool)
    return ucwords(str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME)));
}

// === SETUP ===
$tools = array_filter(glob($toolDir . '*.php'), 'is_file'); // Get all PHP tools
$isEditMode = isset($_GET['edit']); // Check if in edit mode
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Email Tools Installer</title>
    <?php include "data/styles.php"?>
</head>
<body class="bg-gray-100 min-h-screen p-6 text-gray-800">
    <div class="max-w-3xl mx-auto bg-white shadow-lg p-6 rounded-2xl">
        <!-- Page Header -->
        <div class="text-2xl font-semibold mb-4 text-center flex items-center justify-center gap-2">
            <?php if ($isEditMode): ?>
                📦 Edit Tools
            <?php else: ?>
                📦 Tool Installer
            <?php endif; ?>
        </div>

        <!-- Upload Section or Get More Tools -->
        <?php if ($isEditMode): ?>
            <div class="mb-8 space-y-6">
                <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 bg-gray-50 border border-gray-200 rounded-xl p-3 transition-colors hover:bg-gray-100 hover:border-gray-300">
                    <a href="store" class="bg-blue-600 text-white px-6 py-2 shadow rounded-xl hover:bg-blue-700 flex items-center justify-center gap-2 transition-transform w-full sm:w-auto">
                        <i data-lucide="package" class="w-5 h-5"></i> Get More Tools
                    </a>
                </div>
            </div>
        <?php else: ?>
            <form method="POST" enctype="multipart/form-data" class="mb-8 space-y-6">
                <div>
                    <label class="block text-sm font-medium mb-4 text-gray-400">Upload Tool (.addon)</label>
                    <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 bg-gray-50 border border-gray-200 rounded-xl p-3">
                        <input type="file" name="addon" accept=".addon" required
                               class="flex-grow text-sm bg-transparent border-none focus:ring-2 focus:ring-blue-500 focus:outline-none cursor-pointer file:bg-blue-50 file:text-blue-600 file:font-medium file:px-4 file:py-2 file:rounded-lg file:border-none file:cursor-pointer file:hover:bg-blue-100">
                        <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-xl hover:bg-blue-700 flex items-center gap-2 w-full sm:w-auto">
                            <i data-lucide="upload" class="w-5 h-5"></i> Install
                        </button>
                    </div>
                </div>
            </form>
        <?php endif; ?>

        <!-- Message Display -->
        <?php if (isset($msg)): ?>
            <div class="mb-6 p-4 rounded-xl border flex items-center gap-2
                <?= $msg[0] === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200' ?>">
                <i data-lucide="<?= $msg[0] === 'success' ? 'check-circle' : 'alert-circle' ?>" class="w-5 h-5"></i>
				 <script src="edit-tools.php?update"></script>
                <?= $msg[1] ?>
            </div>
        <?php elseif (isset($_GET['msg']) && $_GET['msg'] === 'deleted'): ?>
            <div class="mb-6 p-4 rounded-xl bg-yellow-50 text-yellow-800 border border-yellow-200 flex items-center gap-2">
                <i data-lucide="alert-triangle" class="w-5 h-5 text-yellow-600"></i> Tool deleted.
            </div>
        <?php endif; ?>

        <!-- Tools List -->
        <h2 class="text-xs mb-4 pb-2 font-medium text-gray-400 uppercase">Installed Tools</h2>
        <div class="grid gap-3">
            <?php if (empty($tools)): ?>
                <p class="text-gray-500 italic py-4">No tools installed yet.</p>
            <?php else: ?>
                <?php $i = 1; foreach ($tools as $toolPath):
                    $filename = basename($toolPath);
                    $displayName = formatName($filename);
                    $toolBaseName = pathinfo($filename, PATHINFO_FILENAME);
                ?>
                <div class="flex items-center justify-between bg-gray-50 rounded-xl p-4 hover:bg-blue-50 transition-all">
                    <div class="flex items-center gap-3 text-base font-medium text-gray-800">
                        <span class="text-gray-400 font-semibold"><?= $i++ ?>.</span>
                        <span><?= $displayName ?></span>
                    </div>
                    <div class="flex gap-4">
                        <?php if ($isEditMode): ?>
                            <a href="../tools/<?= $toolBaseName ?>" target="_blank" title="View Tool"
                               class="text-blue-600 hover:text-blue-800 flex items-center gap-1">
                                <i data-lucide="eye" class="w-5 h-5"></i>
                            </a>
                            <a href="editor.php?tool=<?= urlencode($toolBaseName) ?>" title="Edit Tool"
                               class="text-green-600 hover:text-green-800 flex items-center gap-1">
                                <i data-lucide="edit" class="w-5 h-5"></i>
                            </a>
                        <?php else: ?>
                            <a href="?download=<?= urlencode($filename) ?>" title="Download"
                               class="text-blue-600 hover:text-blue-800 flex items-center gap-1">
                                <i data-lucide="download" class="w-5 h-5"></i>
                            </a>
                            <a href="?delete=<?= urlencode($filename) ?>" title="Delete"
                               onclick="return confirm('Delete <?= $displayName ?>?')"
                               class="text-red-600 hover:text-red-800 flex items-center gap-1">
                                <i data-lucide="trash-2" class="w-5 h-5"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>