<?php

/**
 * Универсальная карточка пакета (плагин/тема) для админки
 *
 * Ожидаемые переменные:
 * - $type: 'plugin' | 'theme'
 * - $package: array данных плагина/темы
 * - $colClass: CSS класс колонки (optional)
 *
 * Type-specific переменные для actions могут быть определены в scope (например, $supportsCustomization, $hasSettings).
 */

if (!isset($type) || !is_string($type)) {
    return;
}
$type = strtolower(trim($type));
if (!in_array($type, ['plugin', 'theme'], true)) {
    return;
}

if (!isset($package) || !is_array($package)) {
    return;
}

if (!isset($colClass)) {
    $colClass = 'col-12 col-sm-6 col-lg-4 col-xl-3';
}

$prefix = $type === 'plugin' ? 'plugin' : 'theme';

$name = htmlspecialchars($package['name'] ?? ($type === 'plugin' ? 'Неизвестный плагин' : 'Неизвестная тема'));
$slugRaw = (string)($package['slug'] ?? '');
$slug = htmlspecialchars($slugRaw);
$version = htmlspecialchars($package['version'] ?? '1.0.0');
$description = htmlspecialchars($package['description'] ?? 'Описание отсутствует');
$author = htmlspecialchars($package['author'] ?? '');
$authorUrl = htmlspecialchars($package['author_url'] ?? '');

// Status
if ($type === 'plugin') {
    $status = $package['status'] ?? 'Non-install';
    $isActive = ($status === 'active');
    $isInstalled = ($status !== 'Non-install');
} else {
    // Для тем получаем статус из themes.ini
    $status = $package['status'] ?? 'non-install';
    if (class_exists(\Flowaxy\Infrastructure\Config\ThemeConfigManager::class)) {
        $slugForStatus = $package['slug'] ?? '';
        if (!empty($slugForStatus)) {
            $status = \Flowaxy\Infrastructure\Config\ThemeConfigManager::getStatus($slugForStatus);
        }
    }
    $isActive = ($status === 'activated');
    $isInstalled = ($status !== 'non-install');
}
$statusClass = $isActive ? 'active' : ($isInstalled ? 'inactive' : 'available');

// Preview image (preview.png) with fallback Font Awesome icon
$preview = function_exists('admin_package_preview')
    ? admin_package_preview($type, $slugRaw)
    : [
        'url' => '',
        'is_placeholder' => true
    ];
$previewUrl = htmlspecialchars((string)($preview['url'] ?? ''), ENT_QUOTES, 'UTF-8');
$previewIsPlaceholder = (bool)($preview['is_placeholder'] ?? true);
$previewIcon = $type === 'plugin' ? 'fa-puzzle-piece' : 'fa-palette';
?>
<div class="<?= htmlspecialchars($colClass) ?> mb-3 <?= $prefix ?>-item" data-status="<?= $statusClass ?>" data-name="<?= strtolower($name) ?>">
    <div class="<?= $prefix ?>-card">
        <div class="<?= $prefix ?>-header-section">
            <h6 class="<?= $prefix ?>-name"><?= $name ?></h6>
            <span class="<?= $prefix ?>-version-top">v<?= $version ?></span>
        </div>

        <div class="<?= $prefix ?>-preview-section<?= $previewIsPlaceholder ? ' is-placeholder' : '' ?>">
            <?php if (!$previewIsPlaceholder && !empty($previewUrl)): ?>
                <img
                    src="<?= $previewUrl ?>"
                    class="<?= $prefix ?>-preview-img"
                    alt="<?= $name ?>"
                    loading="lazy"
                    decoding="async">
            <?php else: ?>
                <i class="fas <?= $previewIcon ?> <?= $prefix ?>-preview-icon"></i>
            <?php endif; ?>
        </div>

        <div class="<?= $prefix ?>-description-section">
            <p class="<?= $prefix ?>-description"><?= $description ?></p>

            <?php if ($type === 'plugin'): ?>
                <?php
                // Показываем тег "требует БД" если плагин имеет миграции
                $requiresDatabase = $package['requires_database'] ?? false;
                if ($requiresDatabase):
                ?>
                    <div class="plugin-tags mt-2">
                        <span class="badge bg-warning text-dark" title="Плагін потребує підключення до бази даних">
                            <i class="fas fa-database"></i> Потребує БД
                        </span>
                    </div>
                <?php endif; ?>
            <?php elseif ($type === 'theme'): ?>
                <?php
                // Показываем зависимости темы
                $requiresPlugins = $package['requires_plugins'] ?? [];
                if (!empty($requiresPlugins)):
                ?>
                    <div class="theme-dependencies mt-2">
                        <div class="small text-muted mb-1">
                            <i class="fas fa-puzzle-piece"></i> Потребує плагінів:
                        </div>
                        <div class="d-flex flex-wrap gap-1">
                            <?php foreach ($requiresPlugins as $pluginSlug => $pluginName): ?>
                                <span class="badge bg-info text-white" title="<?= htmlspecialchars($pluginName) ?>">
                                    <?= htmlspecialchars($pluginName) ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <div class="<?= $prefix ?>-footer-section">
            <div class="<?= $prefix ?>-meta">
                <?php if (!empty($author)): ?>
                    <?php if (!empty($authorUrl)): ?>
                        <a href="<?= htmlspecialchars($authorUrl) ?>" target="_blank" rel="noopener noreferrer" class="<?= $prefix ?>-author-link">
                            <?= $author ?>
                        </a>
                    <?php else: ?>
                        <span class="<?= $prefix ?>-author-text"><?= $author ?></span>
                    <?php endif; ?>
                <?php endif; ?>
            </div>

            <div class="<?= $prefix ?>-actions">
                <?php if ($type === 'plugin'): ?>
                    <?php
                    $pluginSlugRaw = $slugRaw;
                    $pluginSlug = htmlspecialchars($pluginSlugRaw, ENT_QUOTES, 'UTF-8');

                    $status = $package['status'] ?? 'Non-install';
                    $isActive = ($status === 'active');
                    $isInstalled = ($status !== 'Non-install');
                    $hasSettings = $package['has_settings'] ?? false;

                    $hasAccess = function_exists('current_user_can') && current_user_can('admin.access');
                    $hasInstallAccess = $hasAccess;
                    $hasActivateAccess = $hasAccess;
                    $hasDeactivateAccess = $hasAccess;
                    $hasDeleteAccess = $hasAccess;
                    $hasSettingsAccess = $hasAccess;
                    ?>

                    <?php if (!$isInstalled): ?>
                        <?php if ($hasInstallAccess): ?>
                            <form method="POST" action="<?= admin_url('plugins') ?>" class="d-inline" onsubmit="return confirm('Встановити цей плагін?');">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="install">
                                <input type="hidden" name="plugin_slug" value="<?= $pluginSlug ?>">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-download btn-icon"></i>
                                    <span class="btn-text">Встановити</span>
                                </button>
                            </form>
                        <?php endif; ?>
                    <?php elseif ($isActive): ?>
                        <?php if ($hasDeactivateAccess): ?>
                            <form method="POST" action="<?= admin_url('plugins') ?>" class="d-inline">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="deactivate">
                                <input type="hidden" name="plugin_slug" value="<?= $pluginSlug ?>">
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-pause btn-icon"></i>
                                    <span class="btn-text">Деактивувати</span>
                                </button>
                            </form>
                        <?php endif; ?>

                        <?php if ($hasSettings && $hasSettingsAccess): ?>
                            <a href="<?= admin_url('plugins?settings=' . urlencode($pluginSlugRaw)) ?>" class="btn btn-secondary" title="Налаштування плагіна">
                                <i class="fas fa-cog btn-icon"></i>
                                <span class="btn-text"></span>
                            </a>
                        <?php endif; ?>
                    <?php else: ?>
                        <?php if ($hasActivateAccess): ?>
                            <form method="POST" action="<?= admin_url('plugins') ?>" class="d-inline">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="activate">
                                <input type="hidden" name="plugin_slug" value="<?= $pluginSlug ?>">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-play btn-icon"></i>
                                    <span class="btn-text">Активувати</span>
                                </button>
                            </form>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if ($isInstalled && $hasDeleteAccess): ?>
                        <?php if ($isActive): ?>
                            <button type="button" class="btn btn-danger" disabled title="Спочатку деактивуйте плагін перед видаленням">
                                <i class="fas fa-trash btn-icon"></i>
                                <span class="btn-text"></span>
                            </button>
                        <?php else: ?>
                            <form method="POST" action="<?= admin_url('plugins') ?>" class="d-inline" onsubmit="return confirm('Ви впевнені, що хочете видалити цей плагін? Всі дані плагіна будуть втрачені.');">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="uninstall">
                                <input type="hidden" name="plugin_slug" value="<?= $pluginSlug ?>">
                                <button type="submit" class="btn btn-danger" title="Видалити плагін">
                                    <i class="fas fa-trash btn-icon"></i>
                                    <span class="btn-text"></span>
                                </button>
                            </form>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php else: ?>
                    <?php
                    $themeSlugRaw = $slugRaw;
                    $themeSlug = htmlspecialchars($themeSlugRaw, ENT_QUOTES, 'UTF-8');

                    // Получаем реальный статус темы
                    $themeStatus = $package['status'] ?? 'non-install';
                    if (class_exists(\Flowaxy\Infrastructure\Config\ThemeConfigManager::class) && !empty($themeSlugRaw)) {
                        $themeStatus = \Flowaxy\Infrastructure\Config\ThemeConfigManager::getStatus($themeSlugRaw);
                    }
                    $isActive = ($themeStatus === 'activated');
                    $isInstalled = ($themeStatus !== 'non-install');
                    $isDeactivated = ($themeStatus === 'deactivated');
                    $isOnlyInstalled = ($themeStatus === 'installed'); // Только установлена, но не деактивирована

                    $supportsCustomization = $supportsCustomization ?? (isset($package['supports_customization']) && $package['supports_customization']);
                    $hasSettings = $hasSettings ?? (isset($package['has_settings']) && $package['has_settings']);

                    $hasAccess = function_exists('current_user_can') && current_user_can('admin.access');
                    $hasInstallAccess = $hasAccess;
                    $hasActivateAccess = $hasAccess;
                    $hasDeactivateAccess = $hasAccess;
                    $hasUninstallAccess = $hasAccess;
                    $hasSettingsAccess = $hasAccess;
                    ?>

                    <?php if (!$isInstalled): ?>
                        <?php if ($hasInstallAccess): ?>
                            <form method="POST" action="<?= admin_url('themes') ?>" class="d-inline" onsubmit="return confirm('Встановити цю тему?');">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="install_theme">
                                <input type="hidden" name="theme_slug" value="<?= $themeSlug ?>">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-download btn-icon"></i>
                                    <span class="btn-text">Встановити</span>
                                </button>
                            </form>
                        <?php endif; ?>
                    <?php elseif ($isActive): ?>
                        <?php if ($hasDeactivateAccess): ?>
                            <form method="POST" action="<?= admin_url('themes') ?>" class="d-inline">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="deactivate_theme">
                                <input type="hidden" name="theme_slug" value="<?= $themeSlug ?>">
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-pause btn-icon"></i>
                                    <span class="btn-text">Деактивувати</span>
                                </button>
                            </form>
                        <?php endif; ?>

                        <?php if ($supportsCustomization && $hasSettingsAccess): ?>
                            <a href="<?= admin_url('themes?customize=' . urlencode($themeSlugRaw)) ?>" class="btn btn-secondary" title="Кастомізувати тему">
                                <i class="fas fa-paint-brush btn-icon"></i>
                                <span class="btn-text"></span>
                            </a>
                        <?php endif; ?>

                        <?php if ($hasSettings && $hasSettingsAccess): ?>
                            <a href="<?= admin_url('themes?settings=' . urlencode($themeSlugRaw)) ?>" class="btn btn-secondary" title="Налаштування теми">
                                <i class="fas fa-cog btn-icon"></i>
                                <span class="btn-text"></span>
                            </a>
                        <?php endif; ?>
                    <?php else: ?>
                        <?php if ($hasActivateAccess): ?>
                            <form method="POST" action="<?= admin_url('themes') ?>" class="d-inline">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="activate_theme">
                                <input type="hidden" name="theme_slug" value="<?= $themeSlug ?>">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-play btn-icon"></i>
                                    <span class="btn-text">Активувати</span>
                                </button>
                            </form>
                        <?php endif; ?>

                        <?php if ($isDeactivated && !$isOnlyInstalled && $hasAccess): ?>
                            <form method="POST" action="<?= admin_url('themes') ?>" class="d-inline" onsubmit="return confirm('Ви впевнені, що хочете видалити цю тему? Всі дані теми будуть втрачені.');">
                                <input type="hidden" name="csrf_token" value="<?= function_exists('csrf_token') ? csrf_token() : '' ?>">
                                <input type="hidden" name="action" value="uninstall_theme">
                                <input type="hidden" name="theme_slug" value="<?= $themeSlug ?>">
                                <button type="submit" class="btn btn-danger" title="Видалити тему">
                                    <i class="fas fa-trash btn-icon"></i>
                                    <span class="btn-text"></span>
                                </button>
                            </form>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
