<?php
/**
 * admin/templates/plugins/index.php
 * - Icon column (reads icon.svg from plugin folder)
 * - Translated description via description_key in plugin.json
 * - Unified license activation modal for licensed plugins
 */
require_once __DIR__ . '/../header.php';

// Pre-load manifest + icon for each plugin
$slugToFolder = fn(string $s): string => str_replace(' ', '', ucwords(str_replace('-', ' ', $s)));

$pluginMeta = [];
foreach ($plugins ?? [] as $p) {
    $folder   = ROOT_PATH . '/plugins/' . $slugToFolder($p['slug']);
    $manifest = is_file($folder . '/plugin.json')
              ? (json_decode(file_get_contents($folder . '/plugin.json'), true) ?: [])
              : [];
    $iconFile = $folder . '/' . ($manifest['icon'] ?? 'icon.svg');
    $pluginMeta[$p['slug']] = [
        'manifest'    => $manifest,
        'icon_svg'    => is_file($iconFile) ? file_get_contents($iconFile) : null,
        'is_licensed' => !empty($manifest['description_key']),
        'desc'        => !empty($manifest['description_key'])
                         ? __($manifest['description_key'], $p['description'] ?? '')
                         : ($p['description'] ?? ''),
    ];
}
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold"><i class="bi bi-plugin me-2 text-primary"></i><?= __('admin.plugins','Plugins') ?></h3>
        <p class="text-muted mb-0 small"><?= __('plugins.subtitle','Extend your store with plugins') ?></p>
    </div>
</div>

<!-- Upload -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white border-bottom py-3">
        <h6 class="mb-0 fw-semibold"><i class="bi bi-cloud-upload me-2 text-muted"></i><?= __('plugins.install_title','Install New Plugin') ?></h6>
    </div>
    <div class="card-body">
        <form method="post" action="/admin/plugins/install" enctype="multipart/form-data">
            <?= \Core\System\Csrf::field() ?>
            <div class="input-group" style="max-width:480px">
                <input type="file" name="plugin" accept=".zip" class="form-control" required>
                <button class="btn btn-primary"><i class="bi bi-upload me-1"></i><?= __('admin.install_plugin','Install Plugin') ?></button>
            </div>
            <div class="text-muted small mt-2"><i class="bi bi-info-circle me-1"></i><?= __('plugins.install_hint','Upload a .zip plugin file') ?></div>
        </form>
    </div>
</div>

<!-- Plugins list -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center py-3">
        <h6 class="mb-0 fw-semibold"><i class="bi bi-list-ul me-2 text-muted"></i><?= __('plugins.installed','Installed Plugins') ?></h6>
        <span class="badge bg-secondary rounded-pill"><?= count($plugins??[]) ?></span>
    </div>
    <div class="card-body p-0">
    <?php if(empty($plugins)): ?>
        <div class="text-center py-5 text-muted">
            <i class="bi bi-plugin display-4 d-block mb-2 opacity-50"></i>
            <p class="mb-0"><?= __('admin.no_plugins','No plugins found.') ?></p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3" style="width:62px"></th>
                        <th><?= __('admin.plugin_name','Name') ?></th>
                        <th><?= __('admin.plugin_version','Version') ?></th>
                        <th><?= __('admin.plugin_description','Description') ?></th>
                        <th class="text-end pe-3"><?= __('admin.plugin_status','Status') ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach($plugins as $plugin):
                    $meta       = $pluginMeta[$plugin['slug']] ?? [];
                    $iconSvg    = $meta['icon_svg']   ?? null;
                    $desc       = $meta['desc']        ?? ($plugin['description'] ?? '');
                    $isLicensed = $meta['is_licensed'] ?? false;
                    $iconB64    = $iconSvg ? base64_encode($iconSvg) : '';
                    $nameJs     = addslashes($plugin['name']);
                ?>
                <tr>
                    <!-- Icon -->
                    <td class="ps-3">
                        <div style="width:46px;height:46px;border-radius:10px;overflow:hidden;flex-shrink:0">
                        <?php if($iconSvg): ?>
                            <?= $iconSvg ?>
                        <?php else: ?>
                            <div style="width:46px;height:46px;background:#f1f5f9;display:flex;align-items:center;justify-content:center">
                                <i class="bi bi-plugin text-muted" style="font-size:1.3rem"></i>
                            </div>
                        <?php endif; ?>
                        </div>
                    </td>
                    <!-- Name -->
                    <td class="fw-semibold"><?= htmlspecialchars($plugin['name']) ?></td>
                    <!-- Version -->
                    <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($plugin['version']) ?></span></td>
                    <!-- Description (translated via description_key) -->
                    <td class="text-muted small" style="max-width:280px"><?= htmlspecialchars($desc) ?></td>
                    <!-- Action -->
                    <td class="text-end pe-3">
                    <?php if($plugin['enabled']): ?>
                        <form method="post" action="/admin/plugins/disable/<?= htmlspecialchars($plugin['slug']) ?>" class="d-inline">
                            <?= \Core\System\Csrf::field() ?>
                            <button class="btn btn-sm btn-outline-danger">
                                <i class="bi bi-pause me-1"></i><?= __('admin.plugin_disable','Disable') ?>
                            </button>
                        </form>
                    <?php elseif($isLicensed): ?>
                        <!-- Licensed plugin → open activation modal -->
                        <button type="button" class="btn btn-sm btn-outline-success"
                                onclick="openLicenseModal('<?= htmlspecialchars($plugin['slug']) ?>','<?= $nameJs ?>','<?= $iconB64 ?>')">
                            <i class="bi bi-key me-1"></i><?= __('admin.plugin_activate','Activate') ?>
                        </button>
                    <?php else: ?>
                        <form method="post" action="/admin/plugins/enable/<?= htmlspecialchars($plugin['slug']) ?>" class="d-inline">
                            <?= \Core\System\Csrf::field() ?>
                            <button class="btn btn-sm btn-outline-success">
                                <i class="bi bi-play me-1"></i><?= __('admin.plugin_enable','Enable') ?>
                            </button>
                        </form>
                    <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
    </div>
</div>

</div></section></div>

<!-- ══ License Activation Modal ════════════════════════════════════════ -->
<div class="modal fade" id="licenseModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width:440px">
        <div class="modal-content border-0 shadow-lg" style="border-radius:18px;overflow:hidden">

            <!-- Gradient header -->
            <div id="lm-header" style="padding:26px 26px 20px;position:relative">
                <button type="button" class="btn-close btn-close-white"
                        data-bs-dismiss="modal"
                        style="position:absolute;top:14px;<?= (($_SESSION['lang'] ?? 'ar') === 'ar') ? 'left' : 'right' ?>:14px;opacity:.8"></button>
                <div class="d-flex align-items-center gap-3">
                    <div id="lm-icon"
                         style="width:56px;height:56px;border-radius:12px;overflow:hidden;flex-shrink:0;box-shadow:0 4px 14px rgba(0,0,0,.25)">
                    </div>
                    <div>
                        <div style="color:rgba(255,255,255,.6);font-size:.7rem;font-weight:600;letter-spacing:.07em;text-transform:uppercase;margin-bottom:3px">
                            <?= __('plugins.activate_plugin','Activate Plugin') ?>
                        </div>
                        <div id="lm-name" style="color:#fff;font-size:1.1rem;font-weight:700;line-height:1.2"></div>
                    </div>
                </div>
            </div>

            <!-- Body -->
            <div class="modal-body px-4 py-4">
                <p class="text-muted small mb-4" style="line-height:1.65">
                    <i class="bi bi-shield-lock-fill me-2 text-primary"></i>
                    <?= __('plugins.license_hint','Enter your license key to activate. The key will be permanently bound to your domain.') ?>
                </p>

                <label class="form-label fw-semibold small mb-1"><?= __('plugins.license_key','License Key') ?></label>
                <div class="input-group mb-3">
                    <span class="input-group-text bg-light border-end-0"><i class="bi bi-key text-muted"></i></span>
                    <input type="text" id="lm-key"
                           class="form-control border-start-0 font-monospace"
                           placeholder="XXXX-XXXX-XXXX-XXXX"
                           autocomplete="off"
                           style="letter-spacing:.05em">
                </div>

                <div id="lm-result" style="display:none" class="mb-3"></div>

                <div class="small px-3 py-2 rounded-3 d-flex justify-content-between align-items-center"
                     style="background:#f8fafc;border:1px solid #e2e8f0">
                    <span class="text-muted"><?= __('plugins.your_domain','Your domain') ?>:</span>
                    <code class="text-primary"><?= htmlspecialchars(
                        preg_replace('/^www\./i', '',
                        strtolower(preg_replace('/:\d+$/', '',
                        $_SERVER['HTTP_HOST'] ?? 'localhost')))
                    ) ?></code>
                </div>

                <div class="text-center mt-3">
                    <a href="https://license.ar-script.com/store" target="_blank"
                       class="small text-muted text-decoration-none">
                        <?= __('plugins.no_license','No license?') ?>
                        <span class="text-primary fw-semibold"><?= __('plugins.buy_here','Buy here →') ?></span>
                    </a>
                </div>
            </div>

            <!-- Footer -->
            <div class="modal-footer border-0 px-4 pb-4 pt-0 gap-2">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal"
                        style="border-radius:10px"><?= __('plugins.cancel','Cancel') ?></button>
                <button type="button" id="lm-btn" onclick="activateLicense()"
                        class="btn btn-primary fw-semibold flex-grow-1"
                        style="border-radius:10px">
                    <i class="bi bi-shield-check me-2"></i><?= __('plugins.verify_and_activate','Verify & Activate') ?>
                </button>
            </div>

        </div>
    </div>
</div>

<script>
(function () {
'use strict';

var _slug = '';
var CSRF  = '<?= \Core\System\Csrf::token() ?>';

var gradients = {
    'rewards-contest':  'linear-gradient(135deg,#7c3aed,#a855f7)',
    'social-campaigns': 'linear-gradient(135deg,#e1306c,#f58529)',
    'facebook-ads':     'linear-gradient(135deg,#185fcc,#1877f2)',
};

window.openLicenseModal = function (slug, name, iconB64) {
    _slug = slug;
    document.getElementById('lm-name').textContent = name;

    var icon = document.getElementById('lm-icon');
    icon.innerHTML = iconB64
        ? '<img src="data:image/svg+xml;base64,' + iconB64 + '" style="width:56px;height:56px;object-fit:cover">'
        : '<div style="width:56px;height:56px;background:#1e293b;display:flex;align-items:center;justify-content:center">'
          + '<i class="bi bi-plugin" style="color:#fff;font-size:1.5rem"></i></div>';

    document.getElementById('lm-header').style.background =
        gradients[slug] || 'linear-gradient(135deg,#1e293b,#0f172a)';

    document.getElementById('lm-key').value = '';
    document.getElementById('lm-result').style.display = 'none';
    resetBtn();

    new bootstrap.Modal(document.getElementById('licenseModal')).show();
    setTimeout(function () { document.getElementById('lm-key').focus(); }, 400);
};

function resetBtn() {
    var btn = document.getElementById('lm-btn');
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-shield-check me-2"></i><?= __('plugins.verify_and_activate','Verify & Activate') ?>';
}

function showResult(type, html) {
    var el  = document.getElementById('lm-result');
    var cls = { success:'alert-success', danger:'alert-danger', warning:'alert-warning', info:'alert-info' };
    el.innerHTML = '<div class="alert ' + (cls[type] || 'alert-secondary') + ' border-0 py-2 small mb-0">' + html + '</div>';
    el.style.display = '';
}

window.activateLicense = function () {
    var key = document.getElementById('lm-key').value.trim();
    var btn = document.getElementById('lm-btn');

    if (!key) {
        showResult('warning', '<i class="bi bi-exclamation-triangle me-1"></i><?= __('plugins.enter_key','Please enter your license key first.') ?>');
        return;
    }

    btn.disabled = true;
    btn.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div><?= __('plugins.verifying','Verifying...') ?>';

    // Step 1: verify key with license server
    var fd1 = new FormData();
    fd1.append('_csrf', CSRF);
    fd1.append('license_key', key);
    fd1.append('slug', _slug);

    fetch('/admin/plugins/verify-license', { method: 'POST', body: fd1 })
        .then(function (r) { return r.text().then(function (t) { try { return JSON.parse(t); } catch (e) { return { success:false, message:t && t.trim() ? t.trim() : 'استجابة غير صالحة من السيرفر.' }; } }); })
        .then(function (d) {
            if (!d.success) {
                resetBtn();
                showResult('danger', '<i class="bi bi-x-circle me-1"></i>' + d.message);
                return;
            }

            // Step 2: enable plugin + save key
            showResult('info', '<i class="bi bi-check-circle me-1"></i><?= __('plugins.license_valid','License valid! Activating plugin...') ?>');

            var fd2 = new FormData();
            fd2.append('_csrf', CSRF);
            fd2.append('license_key', key);

            fetch('/admin/plugins/enable-licensed/' + _slug, { method: 'POST', body: fd2 })
                .then(function (r) { return r.text().then(function (t) { try { return JSON.parse(t); } catch (e) { return { success:false, message:t && t.trim() ? t.trim() : 'استجابة غير صالحة من السيرفر.' }; } }); })
                .then(function (d2) {
                    if (d2.success) {
                        showResult('success',
                            '<i class="bi bi-check-circle-fill me-1"></i>' +
                            '<?= __('plugins.activated_success','Plugin activated successfully!') ?>' +
                            '<div class="opacity-75 mt-1"><?= __('plugins.redirecting','Refreshing page...') ?></div>'
                        );
                        setTimeout(function () { location.reload(); }, 1800);
                    } else {
                        resetBtn();
                        showResult('danger', '<i class="bi bi-x-circle me-1"></i>' + (d2.message || 'Activation failed.'));
                    }
                })
                .catch(function () { resetBtn(); showResult('danger', 'Connection error.'); });
        })
        .catch(function () {
            resetBtn();
            showResult('danger', '<i class="bi bi-wifi-off me-1"></i><?= __('plugins.network_error','Connection error. Try again.') ?>');
        });
};

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('lm-key').addEventListener('keydown', function (e) {
        if (e.key === 'Enter') window.activateLicense();
    });

    var retrySlug = <?= json_encode((string)($_GET['license_retry'] ?? '')) ?>;
    if (retrySlug) {
        var selector = '[onclick*="openLicenseModal(\'' + retrySlug + '\'"]';
        var btn = document.querySelector(selector);
        if (btn) {
            btn.click();
        }
    }
});

})();
</script>
<?php require_once __DIR__ . '/../footer.php'; ?>

