<?php include app()->basePath('app/Views/partials/header.php'); ?>
<?php
    $isEdit = $course !== null;
    $value = fn (string $key, mixed $default = '') => old($key, $course[$key] ?? $default);
?>

<section class="panel">
    <p class="eyebrow"><?= $isEdit ? 'Editar' : 'Novo curso' ?></p>
    <h1><?= $isEdit ? e($course['title']) : 'Criar curso' ?></h1>
    <p class="form-note">Preencha a pagina de venda do curso como numa vitrine: promessa clara, video de apresentacao, capa, preco, desconto e resultados que o aluno vai alcancar.</p>

    <?php if ($isEdit && !empty($publicationChecklist)): ?>
        <div class="quality-box">
            <div>
                <span class="eyebrow">Prontidao para publicacao</span>
                <strong><?= e((string) $publicationChecklist['score']) ?>%</strong>
                <p><?= $publicationChecklist['ready'] ? 'Curso pronto para ser submetido ao admin.' : 'Complete os itens abaixo antes de submeter para aprovacao.' ?></p>
            </div>
            <div class="quality-meter"><span style="width: <?= e((string) $publicationChecklist['score']) ?>%"></span></div>
        </div>

        <div class="quality-list">
            <?php foreach ($publicationChecklist['items'] as $item): ?>
                <div class="<?= $item['passed'] ? 'done' : 'missing' ?>">
                    <strong><?= $item['passed'] ? 'OK' : 'Falta' ?></strong>
                    <span><?= e($item['label']) ?></span>
                    <small><?= e($item['hint']) ?></small>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form method="post" action="<?= e($action) ?>" class="form course-form">
        <?= csrf_field() ?>
        <?php if ($isEdit): ?>
            <input type="hidden" name="id" value="<?= e((string) $course['id']) ?>">
        <?php endif; ?>

        <fieldset class="form-section">
            <legend>Informacao principal</legend>
            <div class="grid two">
            <label>
                Titulo
                <input name="title" value="<?= e((string) $value('title')) ?>" required>
            </label>
            <label>
                Categoria
                <select name="category_id" required>
                    <option value="">Escolha</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?= e((string) $category['id']) ?>" <?= (int) $value('category_id') === (int) $category['id'] ? 'selected' : '' ?>>
                            <?= e($category['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>
            </div>

            <label>
                Subtitulo / promessa curta
                <input name="subtitle" value="<?= e((string) $value('subtitle')) ?>" placeholder="Ex: Aprenda Excel do zero e crie relatorios profissionais">
            </label>

            <label>
                Descricao completa
                <textarea name="description" rows="5" required placeholder="Explique para quem e o curso, qual problema resolve e como as aulas estao organizadas."><?= e((string) $value('description')) ?></textarea>
            </label>
        </fieldset>

        <fieldset class="form-section">
            <legend>Midia e apresentacao</legend>
            <div class="grid two">
                <label>
                    URL da capa do curso
                    <input name="cover_image_url" type="url" value="<?= e((string) $value('cover_image_url')) ?>" placeholder="https://.../capa.jpg">
                </label>
                <label>
                    Video de apresentacao do curso
                    <input name="promo_video_url" type="url" value="<?= e((string) $value('promo_video_url')) ?>" placeholder="https://.../video.mp4 ou YouTube">
                    <small>Este trailer aparece no detalhe do curso antes do aluno comprar.</small>
                </label>
            </div>
            <label>
                Cor alternativa da capa
                <input name="cover_color" type="color" value="<?= e((string) $value('cover_color', '#0f766e')) ?>">
            </label>
        </fieldset>

        <fieldset class="form-section">
            <legend>Preco e campanha</legend>
            <div class="grid three">
            <label>
                Preco
                <select name="pricing_type">
                    <option value="paid" <?= empty($course['is_free']) ? 'selected' : '' ?>>Pago</option>
                    <option value="free" <?= !empty($course['is_free']) ? 'selected' : '' ?>>Gratuito</option>
                </select>
            </label>
            <label>
                Valor MZN
                <input name="price" type="number" min="0" step="0.01" value="<?= e((string) $value('price', '0')) ?>">
            </label>
            <label>
                Preco promocional MZN
                <input name="discount_price" type="number" min="0" step="0.01" value="<?= e((string) $value('discount_price', '0')) ?>" placeholder="Opcional">
            </label>
            </div>
        </fieldset>

        <fieldset class="form-section">
            <legend>Detalhes academicos</legend>
            <div class="grid three">
            <label>
                Nivel
                <select name="level">
                    <option value="all" <?= $value('level', 'all') === 'all' ? 'selected' : '' ?>>Todos</option>
                    <option value="beginner" <?= $value('level') === 'beginner' ? 'selected' : '' ?>>Iniciante</option>
                    <option value="intermediate" <?= $value('level') === 'intermediate' ? 'selected' : '' ?>>Intermedio</option>
                    <option value="advanced" <?= $value('level') === 'advanced' ? 'selected' : '' ?>>Avancado</option>
                </select>
            </label>
            <label>
                Idioma
                <input name="language" value="<?= e((string) $value('language', 'Portugues')) ?>">
            </label>
            <label>
                Carga horaria
                <input name="workload_hours" type="number" min="0" value="<?= e((string) $value('workload_hours', '0')) ?>">
            </label>
            </div>
            <label>
                Duracao estimada em minutos
                <input name="duration_minutes" type="number" min="0" value="<?= e((string) $value('duration_minutes', '0')) ?>">
            </label>
        </fieldset>

        <fieldset class="form-section">
            <legend>Acesso e certificado</legend>
            <div class="grid two">
            <label>
                Tipo de acesso
                <select name="access_type">
                    <option value="lifetime" <?= $value('access_type', 'lifetime') === 'lifetime' ? 'selected' : '' ?>>Vitalicio</option>
                    <option value="limited" <?= $value('access_type') === 'limited' ? 'selected' : '' ?>>Limitado</option>
                </select>
            </label>
            <label>
                Dias de acesso
                <input name="access_duration_days" type="number" min="0" value="<?= e((string) $value('access_duration_days', '0')) ?>">
            </label>
            </div>

            <div class="grid two">
                <label class="check-row">
                    <input type="checkbox" name="certificate_enabled" value="1" <?= !empty($course['certificate_enabled']) ? 'checked' : '' ?>>
                    Emitir certificado quando o aluno concluir o curso
                </label>
                <label>
                    Percentagem minima para certificado
                    <input name="completion_percentage_required" type="number" min="1" max="100" value="<?= e((string) $value('completion_percentage_required', '100')) ?>">
                </label>
            </div>
            <div class="grid two">
                <label class="check-row">
                    <input type="checkbox" name="final_quiz_required" value="1" <?= !empty($course['final_quiz_required']) ? 'checked' : '' ?>>
                    Exigir teste final para certificado
                </label>
                <label>
                    Nota minima no teste final (%)
                    <input name="final_quiz_pass_score" type="number" min="1" max="100" value="<?= e((string) $value('final_quiz_pass_score', '70')) ?>">
                </label>
            </div>
        </fieldset>

        <fieldset class="form-section">
            <legend>Resultados e publico</legend>
            <div class="grid two">
            <label>
                O que o aluno vai aprender
                <textarea name="learning_outcomes" rows="5" placeholder="Um resultado por linha. Ex:&#10;Criar uma loja online simples&#10;Configurar pagamentos manuais&#10;Organizar entregas e atendimento"><?= e((string) $value('learning_outcomes')) ?></textarea>
            </label>
            <label>
                Requisitos
                <textarea name="requirements" rows="5" placeholder="Um requisito por linha."><?= e((string) $value('requirements')) ?></textarea>
            </label>
            </div>

            <div class="grid two">
                <label>
                    Este curso inclui
                    <textarea name="course_includes" rows="4" placeholder="Ex:&#10;Videos gravados&#10;Materiais em PDF&#10;Certificado digital"><?= e((string) $value('course_includes')) ?></textarea>
                </label>
                <label>
                    Publico-alvo
                    <textarea name="target_audience" rows="4" placeholder="Para quem este curso foi criado?"><?= e((string) $value('target_audience')) ?></textarea>
                </label>
            </div>

            <label>
                Mensagem de boas-vindas
                <textarea name="welcome_message" rows="3" placeholder="Mensagem curta que o aluno vera ao iniciar o curso."><?= e((string) $value('welcome_message')) ?></textarea>
            </label>
        </fieldset>

        <?php if (has_role('admin')): ?>
            <label class="check-row">
                <input type="checkbox" name="is_featured" value="1" <?= !empty($course['is_featured']) ? 'checked' : '' ?>>
                Destacar na plataforma
            </label>
        <?php endif; ?>

        <div class="actions">
            <button class="button" type="submit">Guardar curso</button>
            <a class="ghost-button" href="/manage/courses">Voltar</a>
        </div>
    </form>
</section>

<?php include app()->basePath('app/Views/partials/footer.php'); ?>
