<?php $base=array_filter(['token'=>$token]); ?>
<main class="container py-4 py-md-5">
    <div class="d-flex flex-column flex-md-row justify-content-between gap-3 align-items-md-center mb-4"><div><span class="badge text-bg-warning text-dark rounded-pill px-3 py-2 mb-2">Gestão teórica</span><h1 class="h3 fw-bold text-cfc-dark mb-1">Vídeos das minhas turmas</h1><p class="text-muted mb-0">Cadastre por link ou envie um arquivo e escolha a turma que receberá o conteúdo.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?= e(url('professional/panel',$base)) ?>"><i class="bi bi-arrow-left"></i> Voltar ao painel</a></div>
    <?php if(empty($groups)): ?><div class="alert alert-warning rounded-4">Crie uma turma teórica antes de adicionar vídeos.</div><?php else: ?>
    <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
        <form id="professionalTheoryVideoForm" method="post" action="<?= e(url('professional/theory-videos/save')) ?>" enctype="multipart/form-data" class="row g-3">
            <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="uploaded_video_token" id="professionalUploadedVideoToken">
            <div class="col-md-6"><label class="form-label">Título</label><input name="title" class="form-control" required></div>
            <div class="col-md-3"><label class="form-label">Turma</label><select name="group_id" class="form-select" required><option value="">Selecione...</option><?php foreach($groups as $group): ?><option value="<?= (int)$group['id'] ?>"><?= e($group['name']) ?></option><?php endforeach; ?></select></div>
            <div class="col-md-3"><label class="form-label">Origem do vídeo</label><select name="source_type" id="professionalVideoSource" class="form-select"><option value="link">Link</option><option value="upload">Arquivo</option></select></div>
            <div class="col-12"><label class="form-label">Descrição (opcional)</label><textarea name="description" rows="2" class="form-control"></textarea></div>
            <div class="col-md-8" id="professionalVideoLinkBox"><label class="form-label">Link do vídeo</label><input name="video_url" type="url" class="form-control" placeholder="https://..."></div>
            <div class="col-md-8 d-none" id="professionalVideoFileBox"><label class="form-label">Arquivo do vídeo</label><input type="file" name="video_file" id="professionalVideoFileInput" class="form-control" accept="video/mp4,video/webm,video/ogg,video/quicktime,video/x-m4v,video/3gpp,video/x-matroska"></div>
            <div class="col-md-4"><label class="form-label">Capa (opcional)</label><input type="file" name="cover_image" class="form-control" accept="image/jpeg,image/png,image/webp"></div>
            <div class="col-12 d-none" id="professionalVideoUploadProgress"><div class="progress" style="height:24px"><div class="progress-bar" id="professionalVideoUploadBar" style="width:0">0%</div></div><small class="text-muted d-block mt-2" id="professionalVideoUploadStatus"></small></div>
            <div class="col-12"><button id="professionalVideoSaveButton" class="btn btn-success rounded-pill px-4"><i class="bi bi-cloud-arrow-up"></i> Adicionar vídeo à turma</button></div>
        </form>
    </div></div>
    <?php endif; ?>
    <div class="row g-4"><?php foreach($videos as $video): ?><div class="col-lg-6"><div class="card border-0 shadow-soft rounded-4 h-100 overflow-hidden"><?php if(!empty($video['cover_path'])): ?><img src="<?= e(asset($video['cover_path'])) ?>" class="video-cover" alt="Capa"><?php endif; ?><div class="card-body p-4"><h2 class="h5 fw-bold"><?= e($video['title']) ?></h2><p class="text-muted"><?= e($video['description']??'') ?></p><div class="d-flex flex-wrap gap-2"><a class="btn btn-sm btn-primary rounded-pill" href="<?= e(url('portal/videos',$base)) ?>">Visualizar</a><form method="post" action="<?= e(url('professional/theory-videos/delete')) ?>" onsubmit="return confirm('Apagar este vídeo?');"><?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><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></div></div></div><?php endforeach; ?><?php if(empty($videos)): ?><div class="col-12"><div class="alert alert-info rounded-4">Nenhum vídeo adicionado por você.</div></div><?php endif; ?></div>
</main>
<script>
(() => {
 const source=document.getElementById('professionalVideoSource'),linkBox=document.getElementById('professionalVideoLinkBox'),fileBox=document.getElementById('professionalVideoFileBox'),form=document.getElementById('professionalTheoryVideoForm'); if(!form)return;
 const fileInput=document.getElementById('professionalVideoFileInput'),tokenInput=document.getElementById('professionalUploadedVideoToken'),progressWrap=document.getElementById('professionalVideoUploadProgress'),bar=document.getElementById('professionalVideoUploadBar'),status=document.getElementById('professionalVideoUploadStatus'),button=document.getElementById('professionalVideoSaveButton'),cover=form.querySelector('[name="cover_image"]');
 const endpoint=<?= json_encode(url('professional/theory-videos/upload-chunk'),JSON_UNESCAPED_SLASHES) ?>;
 const token=<?= json_encode($token,JSON_UNESCAPED_SLASHES) ?>;
 function sync(){const upload=source.value==='upload';linkBox.classList.toggle('d-none',upload);fileBox.classList.toggle('d-none',!upload);} source.addEventListener('change',sync);sync();
 form.addEventListener('submit',async e=>{
   if(form.dataset.coverPrepared!=='1'&&cover?.files?.[0]){e.preventDefault();button.disabled=true;try{if(window.CFCImageTools)await window.CFCImageTools.prepareInput(cover);form.dataset.coverPrepared='1';button.disabled=false;form.requestSubmit();}catch(err){button.disabled=false;alert(err?.message||'Falha ao preparar a capa.');}return;}
   if(source.value!=='upload'||tokenInput.value!=='')return;const file=fileInput.files?.[0];if(!file)return;e.preventDefault();
   const chunkSize=512*1024,total=Math.ceil(file.size/chunkSize),uploadId=`${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,csrf=form.querySelector('[name="_csrf"]').value;progressWrap.classList.remove('d-none');button.disabled=true;source.disabled=true;fileInput.disabled=true;
   try{for(let i=0;i<total;i++){const data=new FormData();data.append('_csrf',csrf);data.append('token',token);data.append('upload_id',uploadId);data.append('chunk_index',String(i));data.append('total_chunks',String(total));data.append('original_name',file.name);data.append('file_size',String(file.size));data.append('file_chunk',file.slice(i*chunkSize,Math.min(file.size,(i+1)*chunkSize)),`${file.name}.part`);status.textContent=`Enviando parte ${i+1} de ${total}...`;const response=await fetch(endpoint,{method:'POST',body:data,credentials:'same-origin'}),raw=await response.text();let result;try{result=JSON.parse(raw);}catch(_){throw new Error(raw||'Resposta inválida.');}if(!response.ok||!result.ok)throw new Error(result.message||'Falha no envio.');const pct=Math.round(((i+1)/total)*100);bar.style.width=`${pct}%`;bar.textContent=`${pct}%`;}
   tokenInput.value=uploadId;status.textContent='Vídeo recebido. Salvando...';source.disabled=false;form.submit();
   }catch(err){fileInput.disabled=false;source.disabled=false;button.disabled=false;status.textContent=err.message||'Falha ao enviar vídeo.';status.classList.add('text-danger');}
 });
})();
</script>
