<main class="container-fluid py-4">
    <div class="row g-4">
        <div class="col-lg-3"><?php require APP_PATH.'/Views/admin/_sidebar.php'; ?></div>
        <div class="col-lg-9">
            <div class="d-flex justify-content-between align-items-center gap-3 mb-4">
                <div>
                    <h1 class="h3 fw-bold text-cfc-dark mb-1">Videoaulas</h1>
                    <p class="text-muted mb-0">Cadastre link ou arquivo e libere individualmente ou para um grupo teórico.</p>
                </div>
                <a class="btn btn-outline-primary rounded-pill" href="<?= e(url('portal/videos')) ?>">Visualizar</a>
            </div>

            <div class="card border-0 shadow-soft rounded-4 mb-4">
                <div class="card-body p-4">
                    <h2 class="h5 fw-bold mb-3">Nova videoaula</h2>
                    <form id="videoLessonForm" method="post" action="<?= e(url('admin/video-lessons/save')) ?>" enctype="multipart/form-data" class="row g-3">
                        <?= CSRF::input() ?>
                        <input type="hidden" name="uploaded_video_token" id="uploadedVideoToken">
                        <div class="col-md-5"><label class="form-label">Título</label><input name="title" class="form-control" required></div>
                        <div class="col-md-3"><label class="form-label">Origem</label><select name="source_type" class="form-select" id="videoSource"><option value="link">Link de vídeo</option><option value="upload">Arquivo enviado</option></select></div>
                        <div class="col-md-2"><label class="form-label">Público</label><select name="audience" class="form-select"><option value="student">Alunos / grupos</option><option value="professional">Instrutores</option><option value="beginner">Em formação</option><option value="all">Todos</option></select></div>
                        <div class="col-md-2"><label class="form-label">Liberação</label><select name="access_mode" class="form-select"><option value="individual">Selecionada</option><option value="all">Todos do público</option></select></div>
                        <div class="col-md-6" id="videoLinkBox"><label class="form-label">Link</label><input name="video_url" class="form-control" placeholder="YouTube, Vimeo ou MP4 direto"></div>
                        <div class="col-md-6 d-none" id="videoFileBox">
                            <label class="form-label">Arquivo de vídeo</label>
                            <input type="file" name="video_file" id="videoFileInput" class="form-control" accept="video/*,.mp4,.webm,.ogg,.mov,.m4v,.3gp,.mkv">
                            <small class="text-muted">O vídeo é enviado em partes de 512 KB para funcionar mesmo quando a hospedagem possui limite de upload.</small>
                            <div id="videoUploadProgress" class="d-none mt-3">
                                <div class="progress" role="progressbar" aria-label="Progresso do vídeo"><div id="videoUploadBar" class="progress-bar" style="width:0%">0%</div></div>
                                <small id="videoUploadStatus" class="text-muted d-block mt-2">Preparando envio...</small>
                            </div>
                        </div>
                        <div class="col-md-6"><label class="form-label">Imagem de capa</label><input type="file" name="cover_image" class="form-control" accept="image/*"></div>
                        <div class="col-12"><label class="form-label">Descrição</label><textarea name="description" rows="3" class="form-control"></textarea></div>
                        <div class="col-12"><button id="videoSaveButton" class="btn btn-primary rounded-pill px-4"><i class="bi bi-save"></i> Salvar videoaula</button></div>
                    </form>
                </div>
            </div>

            <div class="row g-4">
                <?php foreach($videos as $video): ?>
                    <div class="col-xl-6"><div class="card border-0 shadow-soft rounded-4 h-100 overflow-hidden">
                        <?php if(!empty($video['cover_path'])): ?><img class="video-cover" src="<?= e(asset($video['cover_path'])) ?>" alt="Capa"><?php endif; ?>
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between gap-2"><div><h2 class="h5 fw-bold mb-1"><?= e($video['title']) ?></h2><small class="text-muted"><?= e(($video['source_type']==='upload'?'Arquivo':'Link').' · Público: '.$video['audience'].' · Liberação: '.$video['access_mode']) ?></small></div><span class="badge <?= !empty($video['is_active'])?'text-bg-success':'text-bg-secondary' ?>"><?= !empty($video['is_active'])?'Ativa':'Inativa' ?></span></div>
                            <p class="text-muted mt-3"><?= e($video['description']??'') ?></p>
                            <?php if(($video['access_mode']??'')==='individual'): ?>
                                <form method="post" action="<?= e(url('admin/video-lessons/grant')) ?>" class="row g-2 recipient-form mb-3">
                                    <?= CSRF::input() ?><input type="hidden" name="video_lesson_id" value="<?= (int)$video['id'] ?>"><input type="hidden" name="recipient_type"><input type="hidden" name="recipient_id">
                                    <div class="col-8"><select class="form-select form-select-sm recipient-picker" required><option value="">Liberar para...</option>
                                        <?php if(in_array($video['audience'],['student','all'],true)): ?><optgroup label="Alunos"><?php foreach($students as $p): ?><option value="student:<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></optgroup><optgroup label="Grupos teóricos"><?php foreach($groups as $g): if(empty($g['is_active']))continue; ?><option value="group:<?= (int)$g['id'] ?>"><?= e($g['name']) ?></option><?php endforeach; ?></optgroup><?php endif; ?>
                                        <?php if(in_array($video['audience'],['professional','all'],true)): ?><optgroup label="Instrutores"><?php foreach($professionals as $p): ?><option value="professional:<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></optgroup><?php endif; ?>
                                        <?php if(in_array($video['audience'],['beginner','all'],true)): ?><optgroup label="Em formação"><?php foreach($beginners as $p): ?><option value="beginner:<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></optgroup><?php endif; ?>
                                    </select></div><div class="col-4"><button class="btn btn-sm btn-success w-100">Liberar</button></div>
                                </form>
                            <?php endif; ?>
                            <div class="d-flex flex-wrap gap-2"><a class="btn btn-sm btn-primary rounded-pill" href="<?= e(url('portal/videos')) ?>">Pré-visualizar</a><form method="post" action="<?= e(url('admin/video-lessons/toggle')) ?>"><?= CSRF::input() ?><input type="hidden" name="video_lesson_id" value="<?= (int)$video['id'] ?>"><button class="btn btn-sm btn-outline-primary rounded-pill"><?= !empty($video['is_active'])?'Desativar':'Ativar' ?></button></form><form method="post" action="<?= e(url('admin/video-lessons/delete')) ?>" onsubmit="return confirm('Apagar esta videoaula e suas liberações?');"><?= CSRF::input() ?><input type="hidden" name="video_lesson_id" value="<?= (int)$video['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill">Apagar</button></form></div>
                            <?php if(($video['access_mode']??'')==='individual'&&!empty($accessMap[(int)$video['id']])): ?><hr><small class="fw-bold d-block mb-2">Liberado para:</small><div class="d-flex flex-wrap gap-2"><?php foreach($accessMap[(int)$video['id']] as $type=>$ids): foreach(array_keys($ids) as $rid): $actor=$type==='group'?TheoryGroup::find((int)$rid):Communication::actorByTypeAndId($type,(int)$rid); ?><form method="post" action="<?= e(url('admin/video-lessons/revoke')) ?>"><?= CSRF::input() ?><input type="hidden" name="video_lesson_id" value="<?= (int)$video['id'] ?>"><input type="hidden" name="recipient_type" value="<?= e($type) ?>"><input type="hidden" name="recipient_id" value="<?= (int)$rid ?>"><button class="btn btn-sm btn-light border rounded-pill"><?= e($type==='group'?'Grupo: '.($actor['name']??'Removido'):short_person_name($actor['name']??'Removido')) ?> ×</button></form><?php endforeach; endforeach; ?></div><?php endif; ?>
                        </div>
                    </div></div>
                <?php endforeach; ?>
                <?php if(empty($videos)): ?><div class="col-12"><div class="alert alert-info rounded-4">Nenhuma videoaula cadastrada.</div></div><?php endif; ?>
            </div>
        </div>
    </div>
</main>
<script>
(() => {
    const source = document.getElementById('videoSource');
    const linkBox = document.getElementById('videoLinkBox');
    const fileBox = document.getElementById('videoFileBox');
    const form = document.getElementById('videoLessonForm');
    const fileInput = document.getElementById('videoFileInput');
    const tokenInput = document.getElementById('uploadedVideoToken');
    const progressWrap = document.getElementById('videoUploadProgress');
    const progressBar = document.getElementById('videoUploadBar');
    const progressStatus = document.getElementById('videoUploadStatus');
    const saveButton = document.getElementById('videoSaveButton');
    const coverInput = form.querySelector('[name="cover_image"]');
    const chunkEndpoint = <?= json_encode(url('admin/video-lessons/upload-chunk'), JSON_UNESCAPED_SLASHES) ?>;

    function syncSource() {
        const upload = source.value === 'upload';
        linkBox.classList.toggle('d-none', upload);
        fileBox.classList.toggle('d-none', !upload);
    }
    source.addEventListener('change', syncSource);
    syncSource();

    form.addEventListener('submit', async (event) => {
        if (form.dataset.coverPrepared !== '1' && coverInput?.files?.[0]) {
            event.preventDefault();
            saveButton.disabled = true;
            try {
                if (window.CFCImageTools) await window.CFCImageTools.prepareInput(coverInput);
                form.dataset.coverPrepared = '1';
                saveButton.disabled = false;
                form.requestSubmit();
            } catch (error) {
                saveButton.disabled = false;
                alert(error?.message || 'Não foi possível preparar a capa.');
            }
            return;
        }
        if (source.value !== 'upload' || tokenInput.value !== '') return;
        const file = fileInput.files[0];
        if (!file) return;
        event.preventDefault();
        const chunkSize = 512 * 1024;
        const totalChunks = Math.ceil(file.size / chunkSize);
        const uploadId = `${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
        const csrf = form.querySelector('[name="_csrf"]').value;
        progressWrap.classList.remove('d-none');
        saveButton.disabled = true;
        source.disabled = true;
        fileInput.disabled = true;

        try {
            for (let index = 0; index < totalChunks; index++) {
                const start = index * chunkSize;
                const blob = file.slice(start, Math.min(file.size, start + chunkSize));
                const data = new FormData();
                data.append('_csrf', csrf);
                data.append('upload_id', uploadId);
                data.append('chunk_index', String(index));
                data.append('total_chunks', String(totalChunks));
                data.append('original_name', file.name);
                data.append('file_size', String(file.size));
                data.append('file_chunk', blob, `${file.name}.part`);
                progressStatus.textContent = `Enviando parte ${index + 1} de ${totalChunks}...`;
                const response = await fetch(chunkEndpoint, {method: 'POST', body: data, credentials: 'same-origin'});
                const raw = await response.text();
                let result;
                try { result = JSON.parse(raw); } catch (_) { throw new Error(raw || 'Resposta inválida da hospedagem.'); }
                if (!response.ok || !result.ok) throw new Error(result.message || 'Falha ao enviar o vídeo.');
                const percent = Math.round(((index + 1) / totalChunks) * 100);
                progressBar.style.width = `${percent}%`;
                progressBar.textContent = `${percent}%`;
            }
            tokenInput.value = uploadId;
            progressStatus.textContent = 'Vídeo recebido. Salvando o cadastro...';
            source.disabled = false;
            form.submit();
        } catch (error) {
            fileInput.disabled = false;
            source.disabled = false;
            saveButton.disabled = false;
            progressStatus.textContent = error.message || 'Falha ao enviar o vídeo.';
            progressStatus.classList.add('text-danger');
        }
    });

    document.querySelectorAll('.recipient-form').forEach(formItem => formItem.addEventListener('submit', event => {
        const value = formItem.querySelector('.recipient-picker').value.split(':');
        if (value.length !== 2) { event.preventDefault(); return; }
        formItem.querySelector('[name=recipient_type]').value = value[0];
        formItem.querySelector('[name=recipient_id]').value = value[1];
    }));
})();
</script>
