<!-- ╔══════════════════════════════════════════════════════╗ -->
<!-- ║   MODAL — REGISTO DE PROPONENTE                     ║ -->
<!-- ╚══════════════════════════════════════════════════════╝ -->
<div class="modal fade" id="modalRegisto" tabindex="-1" aria-labelledby="modalRegistoLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable" style="max-width:900px;">
    <div class="modal-content border-0 overflow-hidden" style="border-radius:24px;box-shadow:0 32px 80px rgba(0,0,0,.30);">

      <div style="height:3px;background:linear-gradient(90deg,var(--verde-300) 0% 33%,var(--t300,#B87B42) 33% 66%,var(--azul-300,#2090C8) 66% 100%);"></div>

      <div class="modal-header border-0 pb-0 px-4 pt-3">
        <div class="d-flex align-items-center gap-3">
          <div style="width:42px;height:42px;border-radius:10px;background:linear-gradient(135deg,#24571A,#5B8C20);display:flex;align-items:center;justify-content:center;box-shadow:0 4px 14px rgba(36,87,26,.30);">
            <i class="fas fa-user-plus" style="color:#fff;font-size:.95rem;"></i>
          </div>
          <div>
            <h5 class="modal-title mb-0 fw-bold" id="modalRegistoLabel" style="font-size:1rem;color:#24571A;">Registo de Proponente</h5>
            <small style="font-size:.62rem;color:rgba(36,87,26,.50);">MAAP &mdash; Sistema de Gestão de Licenciamento Ambiental</small>
          </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
      </div>

      <div class="modal-body px-4 pt-3 pb-0">
        <div id="reg-alert" class="d-none mb-3"></div>

        <!-- Steps -->
        <div class="d-flex align-items-center gap-0 mb-4 p-2" style="background:rgba(36,87,26,.04);border:1px solid rgba(36,87,26,.08);border-radius:10px;">
          <div class="reg-step active" id="rs1"><div class="rs-num">1</div><span>Empresa</span></div>
          <div style="flex:1;height:1.5px;background:rgba(36,87,26,.12);margin:0 .5rem;max-width:80px;"></div>
          <div class="reg-step" id="rs2"><div class="rs-num">2</div><span>Responsável</span></div>
          <div style="flex:1;height:1.5px;background:rgba(36,87,26,.12);margin:0 .5rem;max-width:80px;"></div>
          <div class="reg-step" id="rs3"><div class="rs-num">3</div><span>Confirmação</span></div>
        </div>

        <form id="formRegisto" enctype="multipart/form-data" novalidate>
          <div class="row g-3">

            <!-- COL ESQUERDA -->
            <div class="col-lg-6">
              <div class="reg-section-lbl"><div class="rs-badge">1</div><i class="fas fa-building"></i>Informações da Empresa</div>

              <div class="mb-3">
                <label class="reg-label">Nome completo da empresa <span class="text-danger">*</span></label>
                <div class="reg-input-wrap"><i class="fas fa-building reg-ico"></i>
                  <input type="text" class="reg-input" name="nome_empresa" id="rg_nome_empresa" placeholder="Ex: Techcontrol Moçambique, LDA" maxlength="500" required>
                </div>
                <div class="reg-err d-none" id="err_nome_empresa"></div>
              </div>

              <div class="row g-2">
                <div class="col-7">
                  <label class="reg-label">NUIT <span class="text-danger">*</span> <small style="color:rgba(36,87,26,.45);font-weight:400;">(9 dígitos)</small></label>
                  <div class="reg-input-wrap"><i class="fas fa-id-card reg-ico"></i>
                    <input type="text" class="reg-input" name="nuit" id="rg_nuit" placeholder="000000000" maxlength="9" pattern="[0-9]{9}" required>
                  </div>
                  <div class="reg-err d-none" id="err_nuit"></div>
                </div>
                <div class="col-5">
                  <label class="reg-label">Tipo de Actividade <span class="text-danger">*</span></label>
                  <div class="reg-input-wrap"><i class="fas fa-industry reg-ico"></i>
                    <select class="reg-input reg-select" name="setor_atividade" id="rg_setor" required>
                      <option value="">Seleccionar&hellip;</option>
                      <option value="Agrícola">Agrícola</option>
                      <option value="Industrial">Industrial</option>
                      <option value="Energia">Energia</option>
                      <option value="Habitacional">Habitacional</option>
                      <option value="Mineração">Mineração</option>
                      <option value="Hidrocarbonetos">Hidrocarbonetos</option>
                      <option value="Florestal">Florestal</option>
                      <option value="Turístico">Turístico</option>
                      <option value="Pescas">Pescas</option>
                      <option value="Infraestrutura">Infraestrutura</option>
                      <option value="Pecuária">Pecuária</option>
                      <option value="Transportes">Transportes</option>
                      <option value="Aquacultura">Aquacultura</option>
                      <option value="Prestação de serviços">Prestação de serviços</option>
                      <option value="Outros">Outros</option>
                    </select>
                  </div>
                  <div class="reg-err d-none" id="err_setor"></div>
                </div>
              </div>

              <div class="mt-3">
                <label class="reg-label"><i class="fas fa-file-pdf" style="color:#d93025;"></i> Comprovativo NUIT (PDF) <span class="text-danger">*</span></label>
                <div class="reg-upload-area" id="uploadArea">
                  <input type="file" name="nuit_ficheiro" id="rg_nuit_file" accept=".pdf,application/pdf" required>
                  <i class="fas fa-cloud-upload-alt reg-upload-ico"></i>
                  <div class="reg-upload-text"><strong id="uploadLabel">Clique para seleccionar PDF</strong><span>Apenas PDF &middot; máx. 5 MB</span></div>
                </div>
                <div class="reg-err d-none" id="err_pdf"></div>
              </div>
            </div>

            <!-- COL DIREITA -->
            <div class="col-lg-6">
              <div class="d-none d-lg-block" style="position:absolute;left:50%;top:48px;bottom:24px;width:1px;background:rgba(36,87,26,.08);"></div>
              <div class="reg-section-lbl"><div class="rs-badge">2</div><i class="fas fa-user-tie"></i>Responsável / Representante Legal</div>

              <div class="mb-3">
                <label class="reg-label">Nome completo <span class="text-danger">*</span></label>
                <div class="reg-input-wrap"><i class="fas fa-user reg-ico"></i>
                  <input type="text" class="reg-input" name="nome_responsavel" id="rg_nome_resp" placeholder="Nome do representante legal" maxlength="350" required>
                </div>
                <div class="reg-err d-none" id="err_nome_resp"></div>
              </div>

              <div class="mb-3">
                <label class="reg-label">Telefone <span class="text-danger">*</span></label>
                <div class="reg-input-wrap"><i class="fas fa-phone reg-ico"></i>
                  <input type="tel" class="reg-input" name="telefone" id="rg_tel" placeholder="+258 84 000 0000" maxlength="20" required>
                </div>
                <div class="reg-err d-none" id="err_tel"></div>
              </div>

              <div class="mb-3">
                <label class="reg-label">Email <span class="text-danger">*</span> <small style="color:rgba(36,87,26,.45);font-weight:400;">&mdash; será o seu utilizador SGLA</small></label>
                <div class="reg-input-wrap"><i class="fas fa-envelope reg-ico"></i>
                  <input type="email" class="reg-input" name="email" id="rg_email" placeholder="responsavel@empresa.co.mz" maxlength="150" required>
                </div>
                <div class="reg-err d-none" id="err_email"></div>
              </div>

              <div style="padding:.85rem 1rem;background:rgba(32,144,200,.06);border:1px solid rgba(32,144,200,.18);border-radius:10px;margin-top:.5rem;">
                <div style="font-size:.68rem;font-weight:700;color:#085090;margin-bottom:.35rem;"><i class="fas fa-info-circle me-1"></i> Como funciona?</div>
                <ul style="font-size:.65rem;color:rgba(36,87,26,.60);margin:0;padding-left:1rem;line-height:1.8;">
                  <li>O registo fica <strong>pendente de aprovação</strong> pelo MAAP</li>
                  <li>Receberá uma <strong>senha temporária</strong> por email após aprovação</li>
                  <li>Poderá então <strong>submeter projectos AIA</strong> no sistema</li>
                </ul>
              </div>
            </div>

          </div>

          <!-- Termos -->
          <div class="d-flex align-items-start gap-2 mt-4 p-3" style="background:rgba(36,87,26,.04);border:1px solid rgba(36,87,26,.10);border-radius:10px;">
            <div class="form-check mb-0 d-flex align-items-center gap-2 w-100">
              <input type="checkbox" class="form-check-input" name="aceita_termos" id="rg_termos" required style="width:16px;height:16px;margin-top:0;accent-color:#45752E;">
              <label for="rg_termos" class="form-check-label" style="font-size:.68rem;color:rgba(36,87,26,.65);cursor:pointer;">
                Declaro que as informações prestadas são verdadeiras e autorizo o <strong>MAAP/SGLA</strong> a processar os dados para efeitos de licenciamento ambiental, nos termos da legislação moçambicana vigente.
              </label>
            </div>
          </div>
        </form>
      </div>

      <div class="modal-footer border-0 px-4 pt-3 pb-4 d-flex justify-content-between align-items-center flex-wrap gap-2">
        <a href="admin/login" style="font-size:.72rem;color:rgba(36,87,26,.50);text-decoration:none;display:flex;align-items:center;gap:.35rem;">
          <i class="fas fa-sign-in-alt"></i> Já tenho conta &mdash; Entrar
        </a>
        <div class="d-flex gap-2">
          <button type="button" class="btn btn-light btn-sm px-4" data-bs-dismiss="modal">Cancelar</button>
          <button type="button" class="btn btn-sm px-4 fw-bold" id="btnRegSubmit"
                  style="background:linear-gradient(135deg,#24571A,#5B8C20);color:#fff;border:none;border-radius:8px;position:relative;overflow:hidden;">
            <i class="fas fa-eye me-1" id="regBtnIco"></i><span id="regBtnTxt">Rever e Submeter</span>
            <span class="reg-shimmer"></span>
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- MODAL CONFIRMAÇÃO -->
<div class="modal fade" id="modalConfirmarRegisto" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0" style="border-radius:20px;box-shadow:0 24px 70px rgba(0,0,0,.22);">
      <div style="height:3px;background:linear-gradient(90deg,#75A636 0% 33%,#B87B42 33% 66%,#2090C8 66% 100%);border-radius:20px 20px 0 0;"></div>
      <div class="modal-header border-0 pb-0 px-4 pt-3">
        <div class="d-flex align-items-center gap-3">
          <div style="width:42px;height:42px;border-radius:11px;background:linear-gradient(135deg,#24571A,#5B8C20);display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-clipboard-check" style="color:#fff;font-size:1rem;"></i>
          </div>
          <div>
            <h5 class="modal-title mb-0 fw-bold" style="font-size:1rem;color:#24571A;">Confirmar Dados do Registo</h5>
            <small style="font-size:.60rem;color:rgba(36,87,26,.50);">Verifique todos os dados antes de submeter o pedido.</small>
          </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body px-4 pt-3 pb-0" id="modalConfirmarRegistoBody"></div>
      <div class="modal-footer border-0 px-4 pb-4 pt-3 d-flex justify-content-between">
        <button type="button" class="btn btn-light btn-sm px-4" data-bs-dismiss="modal"><i class="fas fa-arrow-left me-1"></i> Voltar e Corrigir</button>
        <button type="button" class="btn btn-sm px-4 fw-bold" id="btnConfirmarRegisto"
                style="background:linear-gradient(135deg,#24571A,#5B8C20);color:#fff;border:none;border-radius:8px;">
          <i class="fas fa-paper-plane me-1"></i> Confirmar e Submeter
        </button>
      </div>
    </div>
  </div>
</div>

<!-- TOAST -->
<div class="toast-container position-fixed top-0 start-50 translate-middle-x p-3" style="z-index:9999;">
  <div id="toastRegisto" class="toast align-items-center border-0 text-white"
       style="background:linear-gradient(135deg,#24571A,#45752E);border-radius:12px;min-width:320px;"
       role="alert" aria-live="assertive" aria-atomic="true">
    <div class="d-flex">
      <div class="toast-body d-flex align-items-center gap-2" style="font-size:.80rem;">
        <i class="fas fa-check-circle fa-lg"></i><span id="toastMsg">Pedido submetido com sucesso!</span>
      </div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
    </div>
  </div>
</div>

<style>
.reg-step{display:flex;align-items:center;gap:.4rem;font-size:.64rem;font-weight:600;color:rgba(36,87,26,.36);transition:color .25s;}
.reg-step.active{color:#45752E;}.reg-step.done{color:#8FC96B;}
.rs-num{width:22px;height:22px;border-radius:50%;background:rgba(36,87,26,.10);display:flex;align-items:center;justify-content:center;font-size:.60rem;font-weight:700;flex-shrink:0;transition:all .25s;}
.reg-step.active .rs-num{background:#45752E;color:#fff;box-shadow:0 2px 8px rgba(69,117,46,.35);}
.reg-step.done .rs-num{background:#8FC96B;color:#24571A;}
.reg-section-lbl{display:flex;align-items:center;gap:.45rem;font-size:.72rem;font-weight:700;color:#24571A;padding-bottom:.5rem;margin-bottom:.85rem;border-bottom:2px solid rgba(36,87,26,.07);}
.rs-badge{width:20px;height:20px;border-radius:5px;flex-shrink:0;background:linear-gradient(135deg,#24571A,#5B8C20);color:#fff;font-size:.58rem;font-weight:700;display:flex;align-items:center;justify-content:center;}
.reg-label{display:block;font-size:.66rem;font-weight:600;color:#24571A;margin-bottom:.26rem;}
.reg-input-wrap{position:relative;}
.reg-ico{position:absolute;left:.72rem;top:50%;transform:translateY(-50%);color:rgba(36,87,26,.28);font-size:.66rem;pointer-events:none;}
.reg-input,.reg-select{width:100%;padding:.58rem .78rem .58rem 2.1rem;background:rgba(255,255,255,.80);border:1.5px solid rgba(36,87,26,.14);border-radius:9px;font-size:.76rem;color:#24571A;outline:none;font-family:inherit;transition:all .20s ease;appearance:none;-webkit-appearance:none;}
.reg-select{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%2345752E' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right .8rem center;padding-right:2rem;}
.reg-input::placeholder{color:rgba(36,87,26,.25);}
.reg-input:focus,.reg-select:focus{border-color:#75A636;background:#fff;box-shadow:0 0 0 3px rgba(117,166,54,.14);}
.reg-input.is-invalid,.reg-select.is-invalid{border-color:#d93025;box-shadow:0 0 0 2px rgba(217,48,37,.12);}
.reg-err{font-size:.63rem;color:#d93025;margin-top:.22rem;padding-left:.2rem;}
.reg-upload-area{position:relative;border:2px dashed rgba(36,87,26,.20);border-radius:9px;padding:.85rem;background:rgba(255,255,255,.55);display:flex;align-items:center;justify-content:center;gap:.7rem;cursor:pointer;transition:all .20s ease;}
.reg-upload-area:hover{border-color:#75A636;background:rgba(117,166,54,.05);}
.reg-upload-area.has-file{border-color:#75A636;border-style:solid;background:rgba(117,166,54,.06);}
.reg-upload-area input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%;}
.reg-upload-ico{color:#5B8C20;font-size:1.1rem;flex-shrink:0;}
.reg-upload-text{font-size:.65rem;color:rgba(36,87,26,.50);}
.reg-upload-text strong{display:block;font-size:.70rem;color:#24571A;font-weight:600;margin-bottom:1px;}
.reg-shimmer{position:absolute;top:0;height:100%;width:45%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.22),transparent);animation:regShim 3s ease-in-out infinite;}
@keyframes regShim{0%{left:-60%;}100%{left:120%;}}
.confirm-row{display:flex;justify-content:space-between;align-items:flex-start;padding:.45rem 0;border-bottom:1px solid rgba(36,87,26,.06);font-size:.76rem;}
.confirm-label{color:rgba(36,87,26,.55);font-weight:500;flex-shrink:0;margin-right:.5rem;}
.confirm-val{color:#24571A;font-weight:600;text-align:right;}
</style>


<!-- Footer -->
<div class="maap-tricolor-bar"></div>
<footer class="sgla-footer mt-5">
    <div class="footer-main">
        <div class="container">
            <div class="row g-5">

                <!-- Sobre -->
                <div class="col-lg-4 col-md-6">
                    <div class="footer-brand">
                        <div class="d-flex align-items-center gap-2 mb-3">
                            <i class="fa fa-leaf fa-2x text-white"></i>
                            <h4 class="text-white mb-0 fw-bold">SGLA</h4>
                        </div>
                        <p class="footer-text">
                            Sistema de Gestão de Licenciamento Ambiental. O processo inicia no Serviço Provincial do Ambiente ou na Direcção Nacional do Ambiente, conforme o Decreto 54/2015, de 31 de Dezembro.
                        </p>
                        <div class="d-flex gap-2 mt-3">
                            <a href="#" class="footer-social" aria-label="Twitter"><i class="fab fa-twitter"></i></a>
                            <a href="#" class="footer-social" aria-label="Facebook"><i class="fab fa-facebook-f"></i></a>
                            <a href="#" class="footer-social" aria-label="LinkedIn"><i class="fab fa-linkedin-in"></i></a>
                            <a href="#" class="footer-social" aria-label="YouTube"><i class="fab fa-youtube"></i></a>
                        </div>
                    </div>
                </div>

                <!-- Links Rápidos -->
                <div class="col-lg-2 col-md-6 col-6">
                    <h5 class="footer-heading">Links Rápidos</h5>
                    <ul class="footer-links">
                        <li><a href="index.php">Início</a></li>
                        <li><a href="projectos_aia.php">Projectos AIA</a></li>
                        <li><a href="contrabalancos.php">Projectos PCGB</a></li>
                        <li><a href="consulta_publica.php">Consultas Públicas</a></li>
                        <li><a href="documento_aia.php">Documentos AIA</a></li>
                        <li><a href="ficha_inscricao.php">Fichas de Inscrição</a></li>
                    </ul>
                </div>

                <!-- Serviços -->
                <div class="col-lg-2 col-md-6 col-6">
                    <h5 class="footer-heading">Profissionais</h5>
                    <ul class="footer-links">
                        <li><a href="consultor_individual.php">Consultor Individual</a></li>
                        <li><a href="consultor_empresa.php">Consultor Empresa</a></li>
                        <li><a href="auditor_individual.php">Auditor Individual</a></li>
                        <li><a href="auditor_empresa.php">Auditor Empresa</a></li>
                        <li><a href="contact.php">Contactos</a></li>
                    </ul>
                </div>

                <!-- Contacto -->
                <div class="col-lg-4 col-md-6">
                    <h5 class="footer-heading">Contactos</h5>
                    <ul class="footer-contact">
                        <li>
                            <i class="bi bi-geo-alt-fill"></i>
                            <span>Rua da Resistência, 174/47, C.P. 2029, Maputo</span>
                        </li>
                        <li>
                            <i class="bi bi-telephone-fill"></i>
                            <span>+258 842 391 327</span>
                        </li>
                        <li>
                            <i class="bi bi-envelope-fill"></i>
                            <span>info@ambiente.gov.mz</span>
                        </li>
                        <li>
                            <i class="bi bi-clock-fill"></i>
                            <span>Seg – Sex: 07h30 – 15h30</span>
                        </li>
                    </ul>
                </div>

            </div>
        </div>
    </div>

    <!-- Footer Bottom -->
    <div class="footer-bottom">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6 text-center text-md-start">
                    <p class="mb-0">
                        &copy; <?= date('Y') ?> <strong>SGLA</strong> — Todos os direitos reservados.
                    </p>
                </div>
                <div class="col-md-6 text-center text-md-end mt-2 mt-md-0">
                    <p class="mb-0">
                        Desenvolvido por <a href="#" class="footer-dev-link">TECHCONTROL</a>
                    </p>
                </div>
            </div>
        </div>
    </div>
</footer>

<!-- Back to Top -->
<a href="#" class="back-to-top" aria-label="Voltar ao topo">
    <i class="bi bi-arrow-up"></i>
</a>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="lib/wow/wow.min.js"></script>
<script src="lib/easing/easing.min.js"></script>
<script src="lib/waypoints/waypoints.min.js"></script>
<script src="lib/counterup/counterup.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="js/main.js"></script>

<script>
(function(){
'use strict';

function setErr(id,msg){var el=document.getElementById('err_'+id);var inp=document.getElementById('rg_'+id)||document.getElementById(id);if(el){el.textContent=msg;el.classList.toggle('d-none',!msg);}if(inp){inp.classList.toggle('is-invalid',!!msg);}}
function clearErr(id){setErr(id,'');}

function setStep(n){for(var i=1;i<=3;i++){var s=document.getElementById('rs'+i);s.classList.remove('active','done');if(i<n)s.classList.add('done');else if(i===n)s.classList.add('active');}}

function updateSteps(){
    var ok1=!!(document.getElementById('rg_nome_empresa').value&&document.getElementById('rg_nuit').value&&document.getElementById('rg_setor').value&&document.getElementById('rg_nuit_file').files.length);
    var ok2=!!(document.getElementById('rg_nome_resp').value&&document.getElementById('rg_tel').value&&document.getElementById('rg_email').value);
    if(ok1&&ok2)setStep(3);else if(ok1)setStep(2);else setStep(1);
}

document.querySelectorAll('#formRegisto input,#formRegisto select').forEach(function(el){
    el.addEventListener('input',function(){clearErr(this.id.replace('rg_',''));updateSteps();});
    el.addEventListener('change',function(){updateSteps();});
});

document.getElementById('rg_nuit_file').addEventListener('change',function(){
    var f=this.files[0],area=document.getElementById('uploadArea');
    if(f){
        if(f.size>5*1024*1024){setErr('pdf','O ficheiro excede 5 MB.');this.value='';return;}
        if(f.type!=='application/pdf'&&!f.name.match(/\.pdf$/i)){setErr('pdf','Apenas PDF são aceites.');this.value='';return;}
        clearErr('pdf');
        document.getElementById('uploadLabel').textContent=f.name;
        area.classList.add('has-file');
        area.querySelector('.reg-upload-ico').className='fas fa-check-circle reg-upload-ico';
        area.querySelector('.reg-upload-ico').style.color='#45752E';
    }
    updateSteps();
});

document.getElementById('rg_nuit').addEventListener('input',function(){this.value=this.value.replace(/\D/g,'').slice(0,9);clearErr('nuit');});
document.getElementById('rg_tel').addEventListener('input',function(){
    var v=this.value.replace(/\D/g,'').slice(0,12);
    this.value=v;clearErr('tel');
});

function validate(){
    var ok=true,errs=[];
    var ne=document.getElementById('rg_nome_empresa').value.trim();
    if(!ne||ne.length<3){setErr('nome_empresa',!ne?'Campo obrigatório.':'Mínimo 3 caracteres.');ok=false;errs.push('Nome da empresa');}else clearErr('nome_empresa');
    var nu=document.getElementById('rg_nuit').value.trim();
    if(!/^\d{9}$/.test(nu)){setErr('nuit',!nu?'NUIT é obrigatório.':'NUIT deve ter 9 dígitos.');ok=false;errs.push('NUIT');}else clearErr('nuit');
    var se=document.getElementById('rg_setor').value;
    if(!se){setErr('setor','Seleccione o tipo de actividade.');ok=false;errs.push('Tipo de actividade');}else clearErr('setor');
    if(!document.getElementById('rg_nuit_file').files.length){setErr('pdf','Comprovativo NUIT é obrigatório.');ok=false;errs.push('PDF NUIT');}else clearErr('pdf');
    var nr=document.getElementById('rg_nome_resp').value.trim();
    if(!nr||nr.length<3){setErr('nome_resp',!nr?'Campo obrigatório.':'Mínimo 3 caracteres.');ok=false;errs.push('Nome responsável');}else clearErr('nome_resp');
    var tel=document.getElementById('rg_tel').value.replace(/\D/g,'');
    if(tel.length<9){setErr('tel',!tel?'Campo obrigatório.':'Número inválido.');ok=false;errs.push('Telefone');}else clearErr('tel');
    var em=document.getElementById('rg_email').value.trim();
    if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em)){setErr('email',!em?'Campo obrigatório.':'Email inválido.');ok=false;errs.push('Email');}else clearErr('email');
    if(!document.getElementById('rg_termos').checked){var al=document.getElementById('reg-alert');al.className='alert alert-warning rounded mb-3 d-block';al.textContent='Deve aceitar os termos para submeter o pedido.';ok=false;}else{document.getElementById('reg-alert').classList.add('d-none');}
    return ok;
}

function preencherConf(){
    function row(l,v){return '<div class="confirm-row"><span class="confirm-label">'+l+'</span><span class="confirm-val">'+v+'</span></div>';}
    var sel=document.getElementById('rg_setor');
    var pdf=document.getElementById('rg_nuit_file').files[0];
    var html='<div class="row g-3"><div class="col-md-6"><small style="font-size:.62rem;text-transform:uppercase;letter-spacing:.8px;color:rgba(36,87,26,.45);font-weight:700;display:block;margin-bottom:.5rem;">Empresa</small>'
        +row('Nome',document.getElementById('rg_nome_empresa').value.trim())
        +row('NUIT','<span style="font-family:monospace;font-weight:700;">'+document.getElementById('rg_nuit').value.trim()+'</span>')
        +row('Tipo de Actividade',sel.options[sel.selectedIndex].text)
        +row('PDF NUIT',pdf?'<i class="fas fa-file-pdf text-danger me-1"></i>'+pdf.name:'&mdash;')
        +'</div><div class="col-md-6"><small style="font-size:.62rem;text-transform:uppercase;letter-spacing:.8px;color:rgba(36,87,26,.45);font-weight:700;display:block;margin-bottom:.5rem;">Responsável</small>'
        +row('Nome',document.getElementById('rg_nome_resp').value.trim())
        +row('Telefone',document.getElementById('rg_tel').value.trim())
        +row('Email',document.getElementById('rg_email').value.trim())
        +'</div></div>'
        +'<div style="margin-top:1rem;padding:.75rem 1rem;background:rgba(255,180,0,.08);border:1px solid rgba(255,180,0,.25);border-radius:10px;font-size:.72rem;color:#b45309;">'
        +'<i class="fas fa-exclamation-triangle me-1"></i><strong>Atenção:</strong> Após a submissão o pedido ficará pendente de aprovação pelo MAAP. Receberá confirmação por email.'
        +'</div>';
    document.getElementById('modalConfirmarRegistoBody').innerHTML=html;
}

document.getElementById('btnRegSubmit').addEventListener('click',function(){
    if(!validate()){var e=document.querySelector('#formRegisto .is-invalid');if(e)e.scrollIntoView({behavior:'smooth',block:'center'});return;}
    preencherConf();
    new bootstrap.Modal(document.getElementById('modalConfirmarRegisto')).show();
});

document.getElementById('btnConfirmarRegisto').addEventListener('click',function(){
    var btn=this;btn.disabled=true;btn.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i> A submeter...';
    var fd=new FormData(document.getElementById('formRegisto'));
    fetch('processar_registo.php',{method:'POST',body:fd})
    .then(function(r){return r.json();})
    .then(function(res){
        if(res.ok){
            bootstrap.Modal.getInstance(document.getElementById('modalConfirmarRegisto')).hide();
            bootstrap.Modal.getInstance(document.getElementById('modalRegisto')).hide();
            document.getElementById('toastMsg').textContent=res.msg||'Pedido submetido! Receberá confirmação por email em breve.';
            new bootstrap.Toast(document.getElementById('toastRegisto'),{delay:8000}).show();
            document.getElementById('formRegisto').reset();
            document.getElementById('uploadLabel').textContent='Clique para seleccionar PDF';
            document.getElementById('uploadArea').classList.remove('has-file');
            var ico=document.querySelector('#uploadArea .reg-upload-ico');
            if(ico){ico.className='fas fa-cloud-upload-alt reg-upload-ico';ico.style.color='#5B8C20';}
            setStep(1);
        }else{
            var al=document.getElementById('reg-alert');al.className='alert alert-danger rounded mb-3 d-block';al.textContent=res.msg||'Erro ao submeter. Tente novamente.';
            bootstrap.Modal.getInstance(document.getElementById('modalConfirmarRegisto')).hide();
        }
    })
    .catch(function(){
        var al=document.getElementById('reg-alert');al.className='alert alert-warning rounded mb-3 d-block';al.textContent='Erro de ligação. Verifique a sua internet e tente novamente.';
        bootstrap.Modal.getInstance(document.getElementById('modalConfirmarRegisto')).hide();
    })
    .finally(function(){btn.disabled=false;btn.innerHTML='<i class="fas fa-paper-plane me-1"></i> Confirmar e Submeter';});
});

document.getElementById('modalRegisto').addEventListener('hidden.bs.modal',function(){
    document.getElementById('reg-alert').classList.add('d-none');
    document.querySelectorAll('#formRegisto .is-invalid').forEach(function(el){el.classList.remove('is-invalid');});
    document.querySelectorAll('#formRegisto .reg-err').forEach(function(el){el.classList.add('d-none');});
    setStep(1);
});

})();
</script>
