<?php
/**
 * Video Meeting Integration Settings
 * @var array  $providers      — keyed by 'jitsi','daily','whereby' — each has api_key, extra, is_active
 * @var string $activeProvider — currently active provider key
 */

$providersMeta = [
    'jitsi' => [
        'label'       => 'Jitsi Meet',
        'icon'        => 'bi-camera-video-fill',
        'color'       => 'success',
        'badge'       => __('video_meeting.free','100% Free — Open Source'),
        'badge_color' => 'success',
        'url'         => 'https://meet.jit.si',
        'urlLabel'    => 'meet.jit.si',
        'doc_url'     => 'https://jitsi.github.io/handbook/docs/intro',
        'needs_key'   => false,
        'description' => __('video_meeting.jitsi_desc','No API key needed. Works instantly using meet.jit.si or your own self-hosted domain.'),
    ],
    'daily' => [
        'label'       => 'Daily.co',
        'icon'        => 'bi-camera-video',
        'color'       => 'primary',
        'badge'       => __('video_meeting.freemium_daily','Free: 10,000 min/month'),
        'badge_color' => 'primary',
        'url'         => 'https://dashboard.daily.co/developers',
        'urlLabel'    => 'dashboard.daily.co',
        'doc_url'     => 'https://docs.daily.co/reference',
        'needs_key'   => true,
        'key_prefix'  => 'sk_live_...',
        'description' => __('video_meeting.daily_desc','Professional video with recording support. Free up to 10,000 minutes per month, then pay-as-you-go.'),
    ],
    'whereby' => [
        'label'       => 'Whereby',
        'icon'        => 'bi-people-fill',
        'color'       => 'warning',
        'badge'       => __('video_meeting.freemium_whereby','Free plan available'),
        'badge_color' => 'warning',
        'url'         => 'https://whereby.com/user/signup',
        'urlLabel'    => 'whereby.com',
        'doc_url'     => 'https://docs.whereby.com/reference/whereby-rest-api-reference',
        'needs_key'   => true,
        'key_prefix'  => 'eyJhbGc...',
        'description' => __('video_meeting.whereby_desc','Simple and elegant video meetings. Free plan for small teams, paid plans for larger usage.'),
    ],
];
?>

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

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-start mb-4">
        <div>
            <h3 class="mb-1 fw-bold">
                <i class="bi bi-camera-video-fill me-2 text-primary"></i>
                <?= __('video_meeting.settings_title','Video Meeting Integration') ?>
            </h3>
            <p class="text-muted mb-0 small">
                <?= __('video_meeting.settings_subtitle','Add video conferencing to your team meetings — choose a provider and configure it below') ?>
            </p>
        </div>
        <a href="/admin/integrations?tab=team" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-<?= \Core\System\Language::direction() === 'rtl' ? 'right' : 'left' ?> me-1"></i>
            <?= __('actions.back','Back') ?>
        </a>
    </div>

    <?php if (!empty($_SESSION['flash_success'])): ?>
    <div class="alert alert-success alert-dismissible fade show py-2">
        <i class="bi bi-check-circle me-1"></i><?= htmlspecialchars($_SESSION['flash_success']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['flash_success']); endif; ?>

    <form method="POST" action="/admin/integrations/video-meeting/save" id="vmForm">
        <?= \Core\System\Csrf::field() ?>

        <!-- ══════════════════════════════════════════════════
             STEP 1 — Choose Provider
        ══════════════════════════════════════════════════ -->
        <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">
                    <span class="badge bg-primary rounded-circle me-2"
                          style="width:22px;height:22px;line-height:15px">1</span>
                    <?= __('video_meeting.choose_provider','Choose Video Provider') ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <?php foreach ($providersMeta as $key => $meta): ?>
                    <div class="col-md-4">
                        <label class="d-block h-100" style="cursor:pointer">
                            <input type="radio" name="active_provider" value="<?= $key ?>"
                                   class="vm-radio d-none"
                                   <?= $activeProvider === $key ? 'checked' : '' ?>>
                            <div class="vm-card border-2 border rounded-3 p-3 h-100
                                        <?= $activeProvider === $key ? 'border-'.$meta['color'].' bg-'.$meta['color'].'-subtle selected' : 'border-light' ?>">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <div class="rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                                         style="width:38px;height:38px;background:var(--bs-<?= $meta['color'] ?>-bg-subtle,rgba(13,110,253,.1))">
                                        <i class="bi <?= $meta['icon'] ?> text-<?= $meta['color'] ?>"></i>
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <div class="fw-bold small lh-1 mb-1"><?= $meta['label'] ?></div>
                                        <span class="badge bg-<?= $meta['badge_color'] ?>-subtle text-<?= $meta['badge_color'] ?> border border-<?= $meta['badge_color'] ?>-subtle"
                                              style="font-size:.63rem"><?= $meta['badge'] ?></span>
                                    </div>
                                    <?php if ($activeProvider === $key): ?>
                                    <i class="bi bi-check-circle-fill text-<?= $meta['color'] ?> ms-auto"></i>
                                    <?php endif; ?>
                                </div>
                                <p class="small text-muted mb-2" style="font-size:.78rem;line-height:1.5">
                                    <?= $meta['description'] ?>
                                </p>
                                <div class="small text-muted">
                                    <a href="<?= $meta['url'] ?>" target="_blank" rel="noopener"
                                       class="text-decoration-none" onclick="event.stopPropagation()">
                                        <i class="bi bi-box-arrow-up-right me-1"></i><?= $meta['urlLabel'] ?>
                                    </a>
                                </div>
                            </div>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- ══════════════════════════════════════════════════
             STEP 2 — Configure (dynamic panels)
        ══════════════════════════════════════════════════ -->
        <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">
                    <span class="badge bg-primary rounded-circle me-2"
                          style="width:22px;height:22px;line-height:15px">2</span>
                    <span id="vmConfigTitle"><?= __('video_meeting.configure','Configure Provider') ?></span>
                </h6>
            </div>
            <div class="card-body">

                <?php foreach ($providersMeta as $key => $meta):
                    $cfg   = $providers[$key] ?? [];
                    $extra = $cfg['extra'] ?? [];
                ?>
                <!-- Panel: <?= $key ?> -->
                <div id="vm-panel-<?= $key ?>"
                     class="vm-panel <?= $activeProvider === $key ? '' : 'd-none' ?>">

                    <?php if (!$meta['needs_key']): ?>
                    <!-- Jitsi: free, no API key -->
                    <div class="alert alert-success border-0 d-flex align-items-start gap-2 py-2 mb-3">
                        <i class="bi bi-check-circle-fill text-success mt-1 flex-shrink-0"></i>
                        <div class="small">
                            <strong><?= __('video_meeting.no_key_needed','No API key required!') ?></strong><br>
                            <?= __('video_meeting.jitsi_free_note','Jitsi Meet is completely free and open source. Just set your preferred domain below.') ?>
                        </div>
                    </div>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold small">
                                <i class="bi bi-globe me-1"></i>
                                <?= __('video_meeting.jitsi_domain','Jitsi Domain') ?>
                            </label>
                            <input type="text" name="jitsi_domain" class="form-control"
                                   value="<?= htmlspecialchars($extra['domain'] ?? 'meet.jit.si', ENT_QUOTES) ?>"
                                   placeholder="meet.jit.si">
                            <div class="form-text"><?= __('video_meeting.jitsi_domain_hint','Use meet.jit.si (default) or your own self-hosted Jitsi domain') ?></div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold small">
                                <i class="bi bi-hash me-1"></i>
                                <?= __('video_meeting.room_prefix','Room Name Prefix') ?>
                            </label>
                            <input type="text" name="jitsi_room_prefix" class="form-control"
                                   value="<?= htmlspecialchars($extra['room_prefix'] ?? 'meeting', ENT_QUOTES) ?>"
                                   placeholder="meeting">
                            <div class="form-text"><?= __('video_meeting.room_prefix_hint','Example: "myteam" → rooms named myteam-12, myteam-15…') ?></div>
                        </div>
                    </div>
                    <!-- Preview URL -->
                    <div class="mt-3 p-2 bg-light rounded-2 small">
                        <i class="bi bi-link-45deg me-1 text-muted"></i>
                        <?= __('video_meeting.preview','Preview') ?>:
                        <code id="jitsi-preview" class="text-primary"></code>
                    </div>

                    <?php else: ?>
                    <!-- Daily.co / Whereby: API key needed -->
                    <div class="row g-3 mb-3">
                        <div class="col-12">
                            <label class="form-label fw-semibold small">
                                <i class="bi bi-key me-1"></i>
                                <?= __('video_meeting.api_key','API Key') ?>
                                <a href="<?= $meta['doc_url'] ?>" target="_blank" rel="noopener"
                                   class="text-muted ms-2 small text-decoration-none">
                                    <?= __('ai.docs','Docs') ?> ↗
                                </a>
                            </label>
                            <div class="input-group">
                                <input type="password"
                                       id="vm-key-<?= $key ?>"
                                       name="<?= $key ?>_api_key"
                                       class="form-control"
                                       value="<?= htmlspecialchars($cfg['api_key'] ?? '', ENT_QUOTES) ?>"
                                       placeholder="<?= htmlspecialchars($meta['key_prefix'] ?? '', ENT_QUOTES) ?>"
                                       autocomplete="new-password">
                                <button type="button" class="btn btn-outline-secondary px-3"
                                        onclick="vmToggleKey('<?= $key ?>')" tabindex="-1">
                                    <i class="bi bi-eye" id="vm-eye-<?= $key ?>"></i>
                                </button>
                            </div>
                            <div class="form-text">
                                <a href="<?= $meta['url'] ?>" target="_blank" rel="noopener" class="text-decoration-none">
                                    <i class="bi bi-box-arrow-up-right me-1"></i><?= __('video_meeting.get_key','Get your API key from') ?> <?= $meta['urlLabel'] ?>
                                </a>
                            </div>
                        </div>

                        <?php if ($key === 'daily'): ?>
                        <div class="col-12">
                            <div class="alert alert-info border-0 py-2 small d-flex gap-2">
                                <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
                                <div><?= __('video_meeting.daily_note','Meeting rooms are created automatically the first time a meeting is opened. Free tier includes 10,000 minutes per month.') ?></div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ($key === 'whereby'): ?>
                        <div class="col-12">
                            <div class="alert alert-warning border-0 py-2 small d-flex gap-2">
                                <i class="bi bi-exclamation-triangle-fill flex-shrink-0 mt-1"></i>
                                <div><?= __('video_meeting.whereby_note','Meeting room links are generated via the Whereby API and cached automatically. A free Whereby account supports up to 200 monthly meeting minutes.') ?></div>
                            </div>
                        </div>
                        <?php endif; ?>

                    </div>
                    <?php endif; ?>

                    <!-- Test Connection button -->
                    <div class="d-flex align-items-center gap-3 pt-3 border-top mt-2">
                        <button type="button"
                                class="btn btn-sm btn-outline-<?= $meta['color'] ?>"
                                onclick="vmTest('<?= $key ?>')">
                            <i class="bi bi-plug me-1"></i>
                            <?= __('ai.test_connection','Test Connection') ?>
                        </button>
                        <span id="vm-test-result-<?= $key ?>" class="small"></span>
                    </div>

                </div><!-- /.vm-panel -->
                <?php endforeach; ?>

            </div>
        </div>

        <!-- Save -->
        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary px-4">
                <i class="bi bi-save me-2"></i><?= __('actions.save','Save Settings') ?>
            </button>
        </div>

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

<script>
const vmProviderLabels = {
    jitsi:  'Jitsi Meet',
    daily:  'Daily.co',
    whereby:'Whereby',
};
const vmProviderColors = {
    jitsi:  'success',
    daily:  'primary',
    whereby:'warning',
};

/* ── Init: click on card selects radio ── */
document.querySelectorAll('.vm-card').forEach(card => {
    card.addEventListener('click', function() {
        const radio = this.closest('label').querySelector('.vm-radio');
        if (radio) { radio.checked = true; radio.dispatchEvent(new Event('change')); }
    });
});
document.querySelectorAll('.vm-radio').forEach(r => r.addEventListener('change', e => vmSwitch(e.target.value)));

function vmSwitch(key) {
    /* update card styles */
    document.querySelectorAll('.vm-card').forEach(c => {
        const r = c.closest('label').querySelector('.vm-radio');
        const sel = r && r.value === key;
        c.classList.toggle('selected', sel);
        ['primary','success','warning','info','secondary','danger'].forEach(cl => {
            c.classList.remove('border-' + cl, 'bg-' + cl + '-subtle');
        });
        if (sel) {
            c.classList.add('border-' + vmProviderColors[key], 'bg-' + vmProviderColors[key] + '-subtle');
        } else {
            c.classList.add('border-light');
        }
        /* check icon */
        const existing = c.querySelector('.bi-check-circle-fill');
        if (existing) existing.remove();
        if (sel) {
            const icon = document.createElement('i');
            icon.className = 'bi bi-check-circle-fill text-' + vmProviderColors[key] + ' ms-auto';
            c.querySelector('.d-flex').appendChild(icon);
        }
    });
    /* show/hide panels */
    document.querySelectorAll('.vm-panel').forEach(p => p.classList.add('d-none'));
    const panel = document.getElementById('vm-panel-' + key);
    if (panel) panel.classList.remove('d-none');
    /* update header */
    document.getElementById('vmConfigTitle').textContent =
        '<?= __('video_meeting.configure','Configure') ?> ' + (vmProviderLabels[key] || key);
    /* update Jitsi preview */
    if (key === 'jitsi') vmUpdateJitsiPreview();
}

/* ── Jitsi preview URL ── */
function vmUpdateJitsiPreview() {
    const domain = (document.querySelector('[name=jitsi_domain]')?.value || 'meet.jit.si').replace(/^https?:\/\//,'').replace(/\/+$/,'');
    const prefix = document.querySelector('[name=jitsi_room_prefix]')?.value || 'meeting';
    const el = document.getElementById('jitsi-preview');
    if (el) el.textContent = 'https://' + domain + '/' + prefix + '-{meeting_id}';
}
document.querySelector('[name=jitsi_domain]')?.addEventListener('input', vmUpdateJitsiPreview);
document.querySelector('[name=jitsi_room_prefix]')?.addEventListener('input', vmUpdateJitsiPreview);
vmUpdateJitsiPreview();

/* ── Toggle API key visibility ── */
function vmToggleKey(key) {
    const inp  = document.getElementById('vm-key-' + key);
    const icon = document.getElementById('vm-eye-' + key);
    if (!inp) return;
    inp.type  = inp.type === 'password' ? 'text' : 'password';
    icon.className = inp.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

/* ── Test Connection ── */
function vmTest(provider) {
    const apiKey = document.getElementById('vm-key-' + provider)?.value?.trim() || '';
    const result = document.getElementById('vm-test-result-' + provider);
    const csrf   = document.querySelector('input[name=_csrf]')?.value || '';

    const extra = {};
    if (provider === 'jitsi') {
        extra.domain      = document.querySelector('[name=jitsi_domain]')?.value?.trim() || 'meet.jit.si';
        extra.room_prefix = document.querySelector('[name=jitsi_room_prefix]')?.value?.trim() || 'meeting';
    } else if (provider === 'daily') {
        extra.subdomain = document.querySelector('[name=daily_subdomain]')?.value?.trim() || '';
    }

    result.innerHTML = '<span class="spinner-border spinner-border-sm me-1 text-muted"></span><?= __('ai.testing','Testing...') ?>';

    const fd = new FormData();
    fd.append('provider', provider);
    fd.append('api_key',  apiKey);
    fd.append('extra',    JSON.stringify(extra));
    fd.append('_csrf',    csrf);

    fetch('/admin/integrations/video-meeting/test', {
        method: 'POST', body: fd, credentials: 'same-origin'
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            result.innerHTML = '<span class="text-success"><i class="bi bi-check-circle-fill me-1"></i>'
                + (res.message || '<?= __('ai.connected','Connected successfully!') ?>') + '</span>';
        } else {
            result.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle me-1"></i>'
                + (res.error || '<?= __('ai.failed','Failed') ?>') + '</span>';
        }
    })
    .catch(err => {
        result.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle me-1"></i>' + err.message + '</span>';
    });
}
</script>

<style>
.vm-card { cursor:pointer; transition: all .18s ease; }
.vm-card:hover { border-color: #6c757d !important; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.vm-card.selected { box-shadow: 0 0 0 2px rgba(13,110,253,.18); }
</style>
