@extends('admin.layouts.app')

@section('title', $title)

@section('content')
<div class="col-md-12">
    <div class="bgc-white bd bdrs-3 p-20 mB-20">

        {{-- Header --}}
        <div class="peers ai-c jc-sb mB-20">
            <div class="peer">
                <h4 class="c-grey-900 mB-0">
                    <i class="ti-package c-blue-500 mR-10"></i>
                    Module Manager
                </h4>
                <small class="c-grey-600">Install, activate, and manage your SaaS modules.</small>
            </div>
            <div class="peer">
                <button id="checkUpdatesBtn" class="btn btn-secondary btn-sm mR-5"
                        data-check-url="{{ route('ch-admin.modules.check-updates') }}">
                    <i class="ti-reload mR-5"></i> Check for Updates
                </button>
                <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#uploadModuleModal">
                    <i class="ti-upload mR-5"></i> Upload Module
                </button>
            </div>
        </div>

        {{-- Unregistered modules found on the filesystem --}}
        @if($unregistered->isNotEmpty())
            <div class="alert alert-info mB-20">
                <strong><i class="ti-info-alt mR-5"></i> Modules found on filesystem</strong><br>
                The following module(s) were found in the <code>modules/</code> directory but are not registered in the database.
                Click <strong>Register</strong> to add them so you can activate them.
            </div>
            <div class="table-responsive mB-20">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Module</th>
                            <th>Version</th>
                            <th>Author</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($unregistered as $mod)
                        <tr>
                            <td>
                                <strong class="c-grey-900">{{ $mod['name'] ?? $mod['slug'] }}</strong>
                                @if(!empty($mod['description']))
                                    <br><small class="c-grey-600">{{ $mod['description'] }}</small>
                                @endif
                            </td>
                            <td><code>{{ $mod['version'] ?? '—' }}</code></td>
                            <td>{{ $mod['author'] ?? '—' }}</td>
                            <td class="text-end">
                                <form action="{{ route('ch-admin.modules.register-from-filesystem') }}" method="POST">
                                    @csrf
                                    <input type="hidden" name="slug" value="{{ $mod['slug'] }}">
                                    <button type="submit" class="btn btn-success btn-sm">
                                        <i class="ti-plus mR-5"></i> Register
                                    </button>
                                </form>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif

        {{-- No modules state --}}
        @if($modules->isEmpty())
            <div class="text-center pY-40">
                <i class="ti-package" style="font-size: 48px; color: #ccc;"></i>
                <p class="c-grey-600 mT-15">No modules installed yet.</p>
                <p class="c-grey-500">Upload a module <code>.zip</code> to get started.</p>
            </div>
        @else
            <div class="table-responsive">
                <table class="table table-hover align-middle" id="modulesTable">
                    <colgroup>
                        <col>{{-- Module --}}
                        <col style="width:80px">{{-- Version --}}
                        <col style="width:110px">{{-- Installed --}}
                        <col style="width:90px">{{-- Status --}}
                        <col style="width:170px">{{-- Actions --}}
                        <col style="width:100px">{{-- Update --}}
                    </colgroup>
                    <thead>
                        <tr>
                            <th>Module</th>
                            <th>Version</th>
                            <th>Installed</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                            <th>Update</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($modules as $module)
                        <tr data-module-slug="{{ $module->slug }}">
                            <td>
                                <div class="fw-semibold c-grey-900">{{ $module->name }}</div>
                                @if($module->description)
                                    <div class="c-grey-600" style="font-size:12px; max-width:480px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
                                        {{ $module->description }}
                                    </div>
                                @endif
                                @if($module->author)
                                    <div style="font-size:11px;" class="c-grey-500 mT-3">by {{ $module->author }}</div>
                                @endif
                            </td>
                            <td>
                                <span class="badge bg-light border text-secondary fw-normal">{{ $module->version }}</span>
                            </td>
                            <td>
                                <small class="c-grey-600">
                                    {{ $module->installed_at?->diffForHumans() ?? '—' }}
                                </small>
                            </td>
                            <td>
                                @if($module->isActive())
                                    <span class="badge bg-success">Active</span>
                                @else
                                    <span class="badge bg-secondary">Inactive</span>
                                @endif
                            </td>
                            <td>
                                <div class="d-flex align-items-center justify-content-end gap-1 flex-nowrap">
                                @if($module->isActive())
                                    <form action="{{ route('ch-admin.modules.deactivate', $module) }}" method="POST">
                                        @csrf
                                        @method('PATCH')
                                        <button type="submit" class="btn btn-warning btn-sm"
                                                onclick="return confirm('Deactivate {{ $module->name }}?')">
                                            <i class="ti-na"></i> Deactivate
                                        </button>
                                    </form>
                                    <button type="button"
                                            class="btn btn-secondary btn-sm"
                                            title="Reinstall"
                                            data-bs-toggle="modal"
                                            data-bs-target="#reinstallModal"
                                            data-module-name="{{ $module->name }}"
                                            data-reinstall-url="{{ route('ch-admin.modules.reinstall', $module) }}">
                                        <i class="ti-reload"></i>
                                    </button>
                                @else
                                    @php
                                        $requires    = $module->meta['module_requires'] ?? [];
                                        $activeSlugs = $modules->where('status', 'active')->pluck('slug')->all();
                                        $missingDeps = array_filter((array) $requires, fn ($s) => ! in_array($s, $activeSlugs));
                                    @endphp
                                    @if(! empty($missingDeps))
                                        <button type="button" class="btn btn-secondary btn-sm" disabled
                                                title="Requires: {{ implode(', ', $missingDeps) }}">
                                            <i class="ti-lock"></i> Activate
                                        </button>
                                    @else
                                        <form action="{{ route('ch-admin.modules.activate', $module) }}" method="POST">
                                            @csrf
                                            @method('PATCH')
                                            <button type="submit" class="btn btn-success btn-sm">
                                                <i class="ti-check"></i> Activate
                                            </button>
                                        </form>
                                    @endif
                                    <form action="{{ route('ch-admin.modules.uninstall', $module) }}" method="POST">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-danger btn-sm"
                                                title="Remove module"
                                                onclick="return confirm('Permanently remove {{ $module->name }}? This cannot be undone.')">
                                            <i class="ti-trash"></i>
                                        </button>
                                    </form>
                                @endif
                                </div>
                            </td>
                            {{-- Update cell — populated by JS after check --}}
                            <td class="module-update-cell">
                                <small class="c-grey-500">—</small>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif

    </div>
</div>

{{-- Upload Module Modal --}}
<div class="modal fade" id="uploadModuleModal" tabindex="-1" aria-labelledby="uploadModuleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="uploadModuleModalLabel">
                    <i class="ti-upload mR-5"></i> Upload Module
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('ch-admin.modules.upload') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <p class="c-grey-600 mB-15">Upload a module <code>.zip</code> file. The zip must contain a valid <code>module.json</code> manifest.</p>
                    <div class="form-group">
                        <label class="form-label" for="module_zip">Module ZIP File</label>
                        <input type="file"
                               class="form-control @error('module_zip') is-invalid @enderror"
                               id="module_zip"
                               name="module_zip"
                               accept=".zip">
                        @error('module_zip')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="ti-upload mR-5"></i> Install Module
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{{-- Reinstall Module Modal --}}
<div class="modal fade" id="reinstallModal" tabindex="-1" aria-labelledby="reinstallModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reinstallModalLabel">
                    <i class="ti-reload mR-5 c-orange-500"></i> Reinstall Module
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning mB-15">
                    <strong><i class="ti-alert mR-5"></i> Warning</strong><br>
                    This will re-run the setup seeder for <strong id="reinstallModuleName"></strong>.
                </div>
                <p class="c-grey-700 mB-10">What reinstall does:</p>
                <ul class="c-grey-700 mB-15">
                    <li>Re-runs the module's setup seeder (products, plans, entitlements).</li>
                    <li>Only <strong>missing</strong> records are created — existing data is never deleted or overwritten.</li>
                    <li>Use this if the module was activated before products existed, or after accidentally deleting the module's product.</li>
                </ul>
                <p class="c-grey-600"><small>Any prices or entitlement values you have edited in the Product Manager will be preserved.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form id="reinstallForm" method="POST" class="d-inline">
                    @csrf
                    <button type="submit" class="btn btn-warning">
                        <i class="ti-reload mR-5"></i> Yes, Reinstall
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
(function () {
    'use strict';

    // Reinstall modal — populate name and form action from the button's data attributes.
    const reinstallModal = document.getElementById('reinstallModal');
    if (reinstallModal) {
        reinstallModal.addEventListener('show.bs.modal', function (e) {
            const btn = e.relatedTarget;
            document.getElementById('reinstallModuleName').textContent = btn.dataset.moduleName;
            document.getElementById('reinstallForm').action = btn.dataset.reinstallUrl;
        });
    }

    const checkBtn = document.getElementById('checkUpdatesBtn');
    if (!checkBtn) return;

    const checkUrl   = checkBtn.dataset.checkUrl;
    const csrfToken  = document.querySelector('meta[name="_token"]')?.content ?? '';

    checkBtn.addEventListener('click', function () {
        checkBtn.disabled = true;
        checkBtn.innerHTML = '<i class="ti-reload mR-5"></i> Checking…';

        fetch(checkUrl, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(r => r.json())
            .then(results => {
                let updatesFound = 0;
                Object.entries(results).forEach(([slug, info]) => {
                    const row  = document.querySelector(`tr[data-module-slug="${slug}"]`);
                    const cell = row?.querySelector('.module-update-cell');
                    if (!cell) return;

                    if (info.error) {
                        cell.innerHTML = `<small class="text-danger" title="${info.error}">Error</small>`;
                    } else if (info.update_available) {
                        updatesFound++;
                        const applyUrl = `/ch-admin/modules/${slug}/apply-update`;
                        cell.innerHTML = `
                            <span class="badge bg-warning text-dark mR-5">v${info.latest_version}</span>
                            <button class="btn btn-primary btn-xs apply-update-btn"
                                    data-slug="${slug}"
                                    data-apply-url="${applyUrl}"
                                    data-download-url="${info.download_url}"
                                    data-checksum="${info.checksum}"
                                    data-version="${info.latest_version}"
                                    data-changelog="${(info.changelog || '').replace(/"/g, '&quot;')}">
                                Update
                            </button>`;
                    } else {
                        cell.innerHTML = `<small class="c-grey-500">Up to date</small>`;
                    }
                });

                checkBtn.innerHTML = updatesFound > 0
                    ? `<i class="ti-arrow-up mR-5"></i> ${updatesFound} update(s) found`
                    : '<i class="ti-check mR-5"></i> All up to date';
                checkBtn.disabled = false;

                // Wire apply buttons.
                document.querySelectorAll('.apply-update-btn').forEach(btn => {
                    btn.addEventListener('click', applyUpdate);
                });
            })
            .catch(err => {
                checkBtn.innerHTML = '<i class="ti-alert mR-5"></i> Check failed';
                checkBtn.disabled = false;
                console.error('Update check failed:', err);
            });
    });

    function applyUpdate(e) {
        const btn      = e.currentTarget;
        const slug     = btn.dataset.slug;
        const version  = btn.dataset.version;
        const changelog = btn.dataset.changelog || 'No changelog provided.';

        if (!confirm(`Update ${slug} to v${version}?\n\nChangelog:\n${changelog}`)) return;

        btn.disabled = true;
        btn.textContent = 'Updating…';

        fetch(btn.dataset.applyUrl, {
            method: 'POST',
            headers: {
                'Content-Type':     'application/json',
                'X-CSRF-TOKEN':     csrfToken,
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: JSON.stringify({
                download_url: btn.dataset.downloadUrl,
                checksum:     btn.dataset.checksum,
                version:      btn.dataset.version,
                changelog:    btn.dataset.changelog,
            }),
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                btn.closest('.module-update-cell').innerHTML =
                    `<small class="text-success">Updated to v${data.version}</small>`;
                // Reload after short delay so version column refreshes.
                setTimeout(() => location.reload(), 1500);
            } else {
                alert('Update failed: ' + (data.error ?? 'Unknown error'));
                btn.disabled = false;
                btn.textContent = 'Retry';
            }
        })
        .catch(err => {
            alert('Update request failed: ' + err.message);
            btn.disabled = false;
            btn.textContent = 'Retry';
        });
    }
})();
</script>
@endpush
@endsection
