<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ asset('assets/images/logo3.png') }}" type="image/x-icon">
    <link rel="shortcut icon" href="{{ asset('assets/images/favicon.jpg') }}" type="image/x-icon">
    <title>@yield('title') - {{env('APP_NAME_SHORT')}}</title>
    <!-- Google font-->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link
        href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&amp;display=swap"
        rel="stylesheet">
    <link
        href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&amp;display=swap"
        rel="stylesheet">
    <link
        href="https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,400;0,500;0,600;0,700;0,800;0,900;1,300;1,400;1,500;1,600;1,700;1,800;1,900&amp;display=swap"
        rel="stylesheet">
    <!-- Font Awesome-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/fontawesome.css') }}">
    <!-- ico-font-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/icofont.css') }}">
    <!-- Themify icon-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/themify.css') }}">
    <!-- Flag icon-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/flag-icon.css') }}">
    <!-- Feather icon-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/feather-icon.css') }}">
    <!-- Plugins css start-->
    <!-- Plugins css Ends-->
    <!-- Bootstrap css-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/bootstrap.css') }}">
    <!-- App css-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/style.css') }}">
    <link id="color" rel="stylesheet" href="{{ asset('assets/css/color-1.css') }}" media="screen">
    <!-- Responsive css-->
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/responsive.css') }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/dropzone.css') }}">
</head>

<body>
    @php
        use App\Models\Escola;
        use App\Models\Turma;

        $escolas = Escola::all();
        $turmas = Turma::all();
    @endphp
    <!-- Loader starts-->
    <div class="loader-wrapper">
        <div class="theme-loader">
            <div class="loader-p"></div>
        </div>
    </div>
    <!-- Loader ends-->
    <!-- page-wrapper Start-->
    <div class="page-wrapper" id="pageWrapper">
        <!-- Page Header Start-->
        <div class="page-main-header">
            <div class="main-header-right row m-0">
                <div class="main-header-left">
                    <div class="toggle-sidebar"><i class="status_toggle middle" data-feather="align-center"
                            id="sidebar-toggle"></i></div>
                </div>
                <div class="left-menu-header col">
                    <ul>
                        <li>
                            <form class="form-inline search-form">
                                <div class="search-bg"><i class="fa fa-search"></i>
                                    <input class="form-control-plaintext" placeholder="Procure aqui">
                                </div>
                            </form><span class="d-sm-none mobile-search search-bg"><i class="fa fa-search"></i></span>
                        </li>
                    </ul>
                </div>
                <div class="nav-right col pull-right right-menu p-0 box-col-6">
                    <ul class="nav-menus">
                        <li><a class="text-dark" href="#!" onclick="javascript:toggleFullScreen()"><i
                                    data-feather="maximize"></i></a></li>
                        @role('super_admin')
                            <li>
                                <div class="dropdown-basic">
                                    <div class="dropdown">
                                        <div class="btn-group mb-0">
                                            <button class="dropbtn btn-primary btn-round" type="button">
                                                Novo <span><i class="icofont icofont-arrow-down"></i></span>
                                            </button>
                                            <div class="dropdown-content">
                                                <a href="#" data-bs-toggle="modal"
                                                    data-bs-target="#modalEscola">Escola</a>
                                                <a href="#" data-bs-toggle="modal"
                                                    data-bs-target="#modalTurma">Turma</a>
                                                <a href="#" data-bs-toggle="modal"
                                                    data-bs-target="#modalAluno">Aluno</a>
                                                <a href="#" data-bs-toggle="modal" data-bs-target="#modalEnvio">Envio
                                                    de
                                                    Mensagem</a>
                                                <a href="#" data-bs-toggle="modal"
                                                    data-bs-target="#modalEvento">Evento</a>
                                                <a href="#" data-bs-toggle="modal"
                                                    data-bs-target="#modalUsuario">Usuário</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        @endrole


                        <li class="onhover-dropdown p-0">
                            <form method="POST" action="{{ route('logout') }}">
                                @csrf
                                <button type="submit" class="btn btn-primary-light">
                                    <i data-feather="log-out"></i> Sair
                                </button>
                            </form>
                        </li>

                    </ul>
                </div>
                <div class="d-lg-none mobile-toggle pull-right w-auto"><i data-feather="more-horizontal"></i></div>
            </div>
        </div>
        <!-- Page Header Ends                              -->
        <!-- Page Body Start-->
        <div class="page-body-wrapper horizontal-menu">
            <!-- Page Sidebar Start-->
            <header class="main-nav">
                <div class="sidebar-user text-center"><a class="setting-primary" href="javascript:void(0)"><i
                            data-feather="settings"></i></a><img class="img-90 rounded-circle"
                        src="{{ asset('assets/images/logo3.png') }}" alt="">
                    <div class="badge-bottom"><span class="badge badge-primary">{{ Auth::user()->funcao() }}</span></div><a
                        href="user-profile.html">
                        <h6 class="mt-3 f-14 f-w-600">{{ Auth::user()->name }}</h6>
                    </a>
                </div>
                <nav>
                    <div class="main-navbar">
                        <div class="left-arrow" id="left-arrow"><i data-feather="arrow-left"></i></div>
                        <div id="mainnav">
                            <ul class="nav-menu custom-scrollbar">
                                <li class="back-btn">
                                    <div class="mobile-back text-end"><span>Back</span><i
                                            class="fa fa-angle-right ps-2" aria-hidden="true"></i></div>
                                </li>
                                <li class="sidebar-main-title">
                                    <div>
                                        <h6>Geral </h6>
                                    </div>
                                </li>
                                <li class="dropdown"><a class="nav-link menu-title link-nav"
                                        href="{{ route('dashboard') }}"><i
                                            data-feather="git-pull-request"></i><span>Dashboard</span></a></li>

                                @role(['admin', 'super_admin'])
                                    <li class="sidebar-main-title">
                                        <div>
                                            <h6>Administração </h6>
                                        </div>
                                    </li>
                                    <li class="dropdown"><a class="nav-link menu-title link-nav"
                                            href="{{ route('escolas') }}"><i
                                                data-feather="award"></i><span>Escolas</span></a></li>
                                    <li class="dropdown"><a class="nav-link menu-title link-nav"
                                            href="{{ route('turmas') }}"><i
                                                data-feather="award"></i><span>Turmas</span></a>
                                    </li>
                                    <li class="dropdown"><a class="nav-link menu-title link-nav"
                                            href="{{ route('alunos') }}"><i
                                                data-feather="award"></i><span>Alunos</span></a>
                                    </li>
                                    <li class="dropdown"><a class="nav-link menu-title link-nav"
                                            href="{{ route('usuarios') }}"><i
                                                data-feather="award"></i><span>Usuários</span></a>
                                    </li>
                                @endrole

                            </ul>
                        </div>
                        <div class="right-arrow" id="right-arrow"><i data-feather="arrow-right"></i></div>
                    </div>
                </nav>
            </header>
            <!-- Page Sidebar Ends-->
            <div class="page-body">
                <div class="container-fluid">
                    <div class="page-header">
                        <div class="row">
                            <div class="col-sm-6">
                                <h3>@yield('title.page')</h3>
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="index.html">@yield('title.page1')</a></li>
                                    <li class="breadcrumb-item">@yield('title.page2')</li>
                                    <li class="breadcrumb-item active">@yield('title.page3')</li>
                                </ol>
                            </div>
                            <div class="col-sm-6">
                                <!-- Bookmark Start-->

                                <!-- Bookmark Ends-->
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Container-fluid starts-->
                <div class="container-fluid">
                    @yield('content')
                </div>
                <!-- Container-fluid Ends-->
            </div>
            <!-- footer start-->
            <footer class="footer">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-6 footer-copyright">
                            <p class="mb-0">
                                Copyright 2026-{{ date('y') }} © Aquino All rights reserved.
                            </p>
                        </div>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <!-- Modal Escola -->
    <div class="modal fade" id="modalEscola" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Nova Escola</h4>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form class="form theme-form" action="{{ route('escola.novo') }}" method="POST">
                        @csrf
                        <div class="card-body">
                            <div class="row">
                                <div class="col-4">
                                    <div class="mb-3">
                                        <label class="form-label" for="cnoj">CNPJ</label>
                                        <input class="form-control" id="cnpj" name="cnpj" type="text">
                                    </div>
                                </div>
                                <div class="col-8">
                                    <div class="mb-3">
                                        <label class="form-label" for="razao_social">Razão Social</label>
                                        <input class="form-control" id="razao_social" name="razaosocial"
                                            type="text">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-6">
                                    <div class="mb-3">
                                        <label class="form-label" for="logradouro">Logradouro</label>
                                        <input class="form-control" id="logradouro" type="text" disabled>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="mb-3">
                                        <label class="form-label" for="numero">Número</label>
                                        <input class="form-control" id="numero" type="text" disabled>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="mb-3">
                                        <label class="form-label" for="cep">CEP</label>
                                        <input class="form-control" id="cep" type="text" disabled>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-4">
                                    <div class="mb-3">
                                        <label class="form-label" for="complemento">Complemento</label>
                                        <input class="form-control" id="complemento" type="text" disabled>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="mb-3">
                                        <label class="form-label" for="bairro">Bairro</label>
                                        <input class="form-control" id="bairro" type="text" disabled>
                                    </div>
                                </div>
                                <div class="col-2">
                                    <div class="mb-3">
                                        <label class="form-label" for="estado">Estado</label>
                                        <input class="form-control" id="estado" type="text" disabled>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="mb-3">
                                        <label class="form-label" for="cidade">Cidade</label>
                                        <input class="form-control" id="cidade" type="text" disabled>
                                        <input class="form-control" id="address" name="address" type="hidden">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer text-end">
                            <button class="btn btn-primary" type="submit">Salvar|Atualizar</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Turma -->
    <div class="modal fade" id="modalTurma" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Nova Turma</h4>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form class="form theme-form" action="{{ route('turma.novo') }}" method="POST">
                        @csrf
                        <div class="card-body">
                            <div class="row">
                                <div class="col">
                                    <div class="mb-3">
                                        <label class="form-label" for="escolas">Escola</label>
                                        <select class="form-select digits" id="escolas" name="id_escola">
                                            @foreach ($escolas as $escola)
                                                <option value="{{ $escola->id }}">{{ $escola->nome }}
                                                </option>
                                            @endforeach

                                        </select>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="mb-3">
                                        <label class="form-label" for="turma_nome">Nome</label>
                                        <input class="form-control" id="turma_nome" name="turma_nome"
                                            type="text">
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="mb-3">
                                        <label class="form-label" for="turma_descricao">Descrição</label>
                                        <input class="form-control" id="turma_descricao" name="turma_descricao"
                                            type="text">
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="mb-3">
                                        <label class="form-label" for="id_whatsapp">Whatsap Id</label>
                                        <input class="form-control" id="id_whatsapp" name="id_whatsapp"
                                            type="text">
                                    </div>
                                </div>
                            </div>

                        </div>
                        <div class="card-footer text-end">
                            <button class="btn btn-primary" type="submit">Salvar|Atualizar</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    {{-- MODAL NOVO ALUNO --}}
    <div class="modal fade" id="modalAluno" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">

                <form class="form theme-form" action="{{ route('alunos.add') }}" method="POST">
                    @csrf

                    <div class="modal-header">
                        <h4 class="modal-title">Novo Aluno</h4>
                        <button class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <div class="row">

                            {{-- Escola --}}
                            <div class="col-12">
                                <div class="mb-3">
                                    <label class="form-label">Escola</label>
                                    <select class="form-select" name="id_escola" id="id_escola" required>
                                        <option value="">Selecione...</option>
                                        @foreach ($escolas as $escola)
                                            <option value="{{ $escola->id }}" @selected(auth()->user()?->current_escola_id == $escola->id)>
                                                {{ $escola->nome }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            {{-- Turma --}}
                            <div class="col-12">
                                <div class="mb-3">
                                    <label class="form-label">Turma</label>
                                    <select class="form-select digits" name="id_turma" id="id_turma" required
                                        disabled>
                                        <option value="">Selecione uma escola primeiro...</option>
                                    </select>
                                </div>
                            </div>

                            {{-- Nome --}}
                            <div class="col-12 col-md-8">
                                <div class="mb-3">
                                    <label class="form-label">Nome do aluno</label>
                                    <input type="text" name="nome" class="form-control" required>
                                </div>
                            </div>

                            {{-- CPF --}}
                            <div class="col-12 col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">CPF</label>
                                    <input type="text" name="cpf" class="form-control">
                                </div>
                            </div>

                            {{-- Data de nascimento --}}
                            <div class="col-12 col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Data de nascimento *</label>
                                    <input type="date" name="data_nascimento" class="form-control" required>
                                </div>
                            </div>

                            {{-- Data de inscrição --}}
                            <div class="col-12 col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Data de inscrição *</label>
                                    <input type="date" name="data_inscricao" class="form-control"
                                        value="{{ now()->format('Y-m-d') }}" required>
                                </div>
                            </div>

                            {{-- Usuário do aluno --}}
                            <div class="col-12 col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Usuário do aluno (opcional)</label>
                                    <select class="form-select" name="user_id">
                                        <option value="">Não vincular</option>
                                        @foreach ($users ?? [] as $u)
                                            <option value="{{ $u->id }}">
                                                {{ $u->name }} ({{ $u->email }})
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            {{-- Usuário responsável --}}
                            <div class="col-12 col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Usuário responsável (opcional)</label>
                                    <select class="form-select" name="responsavel_user_id">
                                        <option value="">Não vincular</option>
                                        @foreach ($users ?? [] as $u)
                                            <option value="{{ $u->id }}">
                                                {{ $u->name }} ({{ $u->email }})
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                        </div>
                    </div>

                    <div class="modal-footer">
                        <button class="btn btn-secondary" data-bs-dismiss="modal">
                            Cancelar
                        </button>
                        <button class="btn btn-primary" type="submit">
                            Salvar Aluno
                        </button>
                    </div>

                </form>

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

    {{-- JS carregar turmas --}}
    <script>
        document.addEventListener('DOMContentLoaded', () => {

            const modalEl = document.getElementById('modalAluno');
            const escolaSelect = document.getElementById('id_escola');
            const turmaSelect = document.getElementById('id_turma');

            if (!modalEl || !escolaSelect || !turmaSelect) return;

            let controller = null; // abort fetch anterior

            function setTurmaOptions({
                message = null,
                turmas = []
            } = {}) {
                turmaSelect.innerHTML = '';

                if (message) {
                    const opt = document.createElement('option');
                    opt.value = '';
                    opt.textContent = message;
                    turmaSelect.appendChild(opt);
                    turmaSelect.disabled = true;
                    return;
                }

                const opt0 = document.createElement('option');
                opt0.value = '';
                opt0.textContent = 'Selecione...';
                turmaSelect.appendChild(opt0);

                turmas.forEach(t => {
                    const opt = document.createElement('option');
                    opt.value = t.id;
                    opt.textContent = t.nome;
                    turmaSelect.appendChild(opt);
                });

                turmaSelect.disabled = turmas.length === 0;
                if (turmas.length === 0) {
                    setTurmaOptions({
                        message: 'Nenhuma turma encontrada para esta escola.'
                    });
                }
            }

            async function loadTurmas(escolaId) {
                if (!escolaId) {
                    setTurmaOptions({
                        message: 'Selecione uma escola primeiro...'
                    });
                    return;
                }

                // cancela requisição anterior
                if (controller) controller.abort();
                controller = new AbortController();

                setTurmaOptions({
                    message: 'Carregando turmas...'
                });

                try {
                    const resp = await fetch(`/api/escolas/${escolaId}/turmas`, {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        signal: controller.signal,
                    });

                    // se deu redirect/403/500 etc, não tenta parsear json
                    if (!resp.ok) {
                        throw new Error(`HTTP ${resp.status}`);
                    }

                    const turmas = await resp.json();
                    setTurmaOptions({
                        turmas
                    });

                } catch (err) {
                    if (err.name === 'AbortError') return; // troca rápida de escola
                    console.error('Erro ao carregar turmas:', err);
                    setTurmaOptions({
                        message: 'Erro ao carregar turmas.'
                    });
                }
            }

            // 1) carrega sempre ao abrir o modal (garante estabilidade)
            modalEl.addEventListener('shown.bs.modal', () => {
                loadTurmas(escolaSelect.value);
            });

            // 2) recarrega ao trocar escola
            escolaSelect.addEventListener('change', () => {
                loadTurmas(escolaSelect.value);
            });

            // 3) opcional: ao fechar modal, reseta turmas (evita “ficar antigo”)
            modalEl.addEventListener('hidden.bs.modal', () => {
                setTurmaOptions({
                    message: 'Selecione uma escola primeiro...'
                });
            });

        });
    </script>

    <div class="modal fade" id="modalEnvio" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">

                <form class="form theme-form" action="{{ route('envio.wpp') }}" method="POST"
                    enctype="multipart/form-data">
                    @csrf

                    <div class="modal-header">
                        <h4 class="modal-title">Novo Envio</h4>
                        <button class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <div class="row">

                            <!-- ✅ NOVO DROPDOWN (primeiro item) -->
                            <div class="col-12">
                                <div class="mb-3">
                                    <label class="form-label">Tipo de Envio</label>
                                    <select class="form-select" name="tipo_envio" id="tipo_envio">
                                        <option value="texto">Somente Texto</option>
                                        <option value="imagem">Imagem + Texto</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Turma -->
                            <div class="col-12">
                                <div class="mb-3">
                                    <label class="form-label">Turma</label>
                                    <select class="form-select digits" name="id_turma">
                                        @foreach ($turmas as $turma)
                                            <option value="{{ $turma->id }}">
                                                {{ $turma->nome }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            <!-- Mensagem -->
                            <div class="col-12">
                                <div class="mb-3">
                                    <label class="form-label">Mensagem</label>
                                    <textarea id="editor" name="mensagem" class="form-control"></textarea>
                                </div>
                            </div>

                            <!-- Upload imagem (oculto inicialmente) -->
                            <div class="col-12 d-none" id="campoImagem">
                                <div class="mb-3">
                                    <label class="form-label">Imagem</label>
                                    <input type="file" name="imagem" class="form-control"
                                        accept="image/jpeg,image/png,image/webp">
                                </div>
                            </div>

                        </div>
                    </div>

                    <div class="modal-footer">
                        <button class="btn btn-secondary" data-bs-dismiss="modal">
                            Cancelar
                        </button>
                        <button class="btn btn-primary" type="submit">
                            Enviar Mensagem
                        </button>
                    </div>

                </form>

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

    <div class="modal fade" id="modalEvento" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Novo Evento</h4>
                    <button class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- formulário -->
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalUsuario" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">

            <div class="modal-header">
              <h4 class="modal-title">Novo Usuário</h4>
              <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
              <form action="{{ route('usuarios.add') }}" method="POST">
                @csrf

                <div class="mb-3">
                  <label class="form-label">Nome</label>
                  <input class="form-control" name="name" required>
                </div>

                <div class="mb-3">
                  <label class="form-label">Email</label>
                  <input class="form-control" type="email" name="email" required>
                </div>

                <div class="row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Senha</label>
                    <input class="form-control" type="password" name="password" required>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Confirmar senha</label>
                    <input class="form-control" type="password" name="password_confirmation" required>
                  </div>
                </div>

                <div class="form-check mb-3">
                  <input class="form-check-input" type="checkbox" value="1" id="is_super_admin" name="is_super_admin">
                  <label class="form-check-label" for="is_super_admin">Super Admin</label>
                </div>

                <div class="row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label">Escola</label>
                    <select class="form-select" name="escola_id" id="escola_id_user">
                      <option value="">Selecione...</option>
                      @foreach($escolas as $escola)
                        <option value="{{ $escola->id }}">{{ $escola->nome }}</option>
                      @endforeach
                    </select>
                  </div>

                  <div class="col-md-6 mb-3">
                    <label class="form-label">Cargo</label>
                    <select class="form-select" name="role_name" id="role_name" disabled>
                      <option value="">Selecione uma escola primeiro...</option>
                    </select>
                  </div>
                </div>

                {{-- ✅ ALUNO: vínculo 1 aluno --}}
                <div class="mb-3 d-none" id="box_aluno_unico">
                  <label class="form-label" id="label_aluno_unico">Qual aluno este usuário é?</label>
                  <select class="form-select" name="aluno_id" id="aluno_id" disabled>
                    <option value="">Selecione uma escola primeiro...</option>
                  </select>
                </div>

                {{-- ✅ RESPONSÁVEL: vínculo múltiplos alunos --}}
                <div class="mb-3 d-none" id="box_alunos_responsavel">
                  <label class="form-label">Quais alunos este responsável representa?</label>
                  <select class="form-select" name="aluno_ids[]" id="aluno_ids" multiple disabled>
                    <option value="">Selecione uma escola primeiro...</option>
                  </select>
                  <small class="text-muted">
                    Segure <b>Ctrl</b> (Windows) ou <b>Cmd</b> (Mac) para selecionar mais de um.
                  </small>
                </div>

                <button class="btn btn-primary" type="submit">Criar usuário</button>
              </form>

              <script>
              document.addEventListener('DOMContentLoaded', () => {

                const escolaSelect = document.getElementById('escola_id_user');
                const roleSelect   = document.getElementById('role_name');
                const superCheck   = document.getElementById('is_super_admin');

                const boxAlunoUnico = document.getElementById('box_aluno_unico');
                const alunoSelect   = document.getElementById('aluno_id');
                const labelAlunoUnico = document.getElementById('label_aluno_unico');

                const boxResp = document.getElementById('box_alunos_responsavel');
                const alunosMulti = document.getElementById('aluno_ids');

                const roleLabel = {
                  'coordenacao': 'Coordenação',
                  'secretaria': 'Secretaria',
                  'responsavel': 'Responsável',
                  'aluno': 'Aluno',
                  'representante_de_turma': 'Representante de Turma',
                };

                function resetSelect(select, msg) {
                  select.innerHTML = `<option value="">${msg}</option>`;
                  select.disabled = true;
                }

                function hideAllBindings() {
                  boxAlunoUnico.classList.add('d-none');
                  boxResp.classList.add('d-none');

                  alunoSelect.value = '';
                  alunosMulti.value = '';

                  resetSelect(alunoSelect, 'Selecione uma escola primeiro...');
                  resetSelect(alunosMulti, 'Selecione uma escola primeiro...');
                }

                async function loadRoles(escolaId) {
                  if (!escolaId) {
                    resetSelect(roleSelect, 'Selecione uma escola primeiro...');
                    return;
                  }

                  resetSelect(roleSelect, 'Carregando cargos...');

                  const resp = await fetch(`/api/escolas/${escolaId}/roles`, {
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                  });

                  if (!resp.ok) {
                    resetSelect(roleSelect, 'Erro ao carregar cargos');
                    return;
                  }

                  const roles = await resp.json();

                  roleSelect.innerHTML = `<option value="">Selecione...</option>`;
                  roles.forEach(r => {
                    const opt = document.createElement('option');
                    opt.value = r.name;
                    opt.textContent = roleLabel[r.name] ?? r.name;
                    roleSelect.appendChild(opt);
                  });

                  roleSelect.disabled = false;
                }

                async function loadAlunos(escolaId, targetSelect, multiple = false) {
                  if (!escolaId) {
                    resetSelect(targetSelect, 'Selecione uma escola primeiro...');
                    return;
                  }

                  resetSelect(targetSelect, 'Carregando alunos...');

                  const resp = await fetch(`/api/escolas/${escolaId}/alunos`, {
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                  });

                  if (!resp.ok) {
                    resetSelect(targetSelect, 'Erro ao carregar alunos');
                    return;
                  }

                  const alunos = await resp.json();

                  targetSelect.innerHTML = multiple
                    ? '' // multi select não precisa placeholder fixo
                    : `<option value="">Selecione...</option>`;

                  alunos.forEach(a => {
                    const opt = document.createElement('option');
                    opt.value = a.id;
                    opt.textContent = a.nome;
                    targetSelect.appendChild(opt);
                  });

                  targetSelect.disabled = alunos.length === 0;
                }

                function toggleSuperAdmin(isSuper) {
                  if (isSuper) {
                    escolaSelect.value = '';
                    roleSelect.value = '';
                    resetSelect(roleSelect, 'Super Admin não usa cargo');
                    escolaSelect.disabled = true;
                    roleSelect.disabled = true;

                    hideAllBindings();
                    alunoSelect.disabled = true;
                    alunosMulti.disabled = true;
                  } else {
                    escolaSelect.disabled = false;
                    resetSelect(roleSelect, 'Selecione uma escola primeiro...');
                    roleSelect.disabled = true;
                    hideAllBindings();
                  }
                }

                superCheck.addEventListener('change', () => toggleSuperAdmin(superCheck.checked));

                escolaSelect.addEventListener('change', async () => {
                  await loadRoles(escolaSelect.value);
                  hideAllBindings();
                });

                roleSelect.addEventListener('change', async () => {
                  const role = roleSelect.value;

                  // sempre reseta
                  hideAllBindings();

                  if (role === 'responsavel') {
                    boxResp.classList.remove('d-none');
                    await loadAlunos(escolaSelect.value, alunosMulti, true);
                    return;
                  }

                  if (role === 'aluno') {
                    labelAlunoUnico.textContent = 'Qual aluno este usuário é?';
                    boxAlunoUnico.classList.remove('d-none');
                    await loadAlunos(escolaSelect.value, alunoSelect, false);
                    return;
                  }

                  // (opcional) se representante também tiver vínculo com 1 aluno, habilite:
                  // if (role === 'representante_de_turma') { ... }

                });

                // estado inicial
                toggleSuperAdmin(superCheck.checked);
              });
              </script>

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






    <!-- latest jquery-->
    <script src="{{ asset('assets/js/jquery-3.5.1.min.js') }}"></script>
    <!-- feather icon js-->
    <script src="{{ asset('assets/js/icons/feather-icon/feather.min.js') }}"></script>
    <script src="{{ asset('assets/js/icons/feather-icon/feather-icon.js') }}"></script>
    <!-- Sidebar jquery-->
    <script src="{{ asset('assets/js/sidebar-menu.js') }}"></script>
    <script src="{{ asset('assets/js/config.js') }}"></script>
    <!-- Bootstrap js-->
    <script src="{{ asset('assets/js/bootstrap/popper.min.js') }}"></script>
    <script src="{{ asset('assets/js/bootstrap/bootstrap.min.js') }}"></script>
    <!-- Plugins JS start-->
    <!-- Plugins JS Ends-->
    <!-- Theme js-->
    <script src="{{ asset('assets/js/script.js') }}"></script>
    <!-- login js-->
    <!-- Plugin used-->
    <script src="{{ asset('assets/js/icons/icons-notify.js') }}"></script>
    <script src="{{ asset('assets/js/icons/icon-clipart.js') }}"></script>
    <script src="{{ asset('assets/js/icons/feather-icon/feather-icon.js') }}"></script>
    <script src="{{ asset('assets/js/icons/feather-icon/feather.min.js') }}"></script>
    <script src="{{ asset('assets/js/tooltip-init.js') }}"></script>
    <script src="{{ asset('assets/js/dropzone/dropzone.js') }}"></script>
    <script src="{{ asset('assets/js/dropzone/dropzone-script.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>

    @yield('scripts')

    <script>
        let ultimoCNPJ = '';
        let timeout = null;

        document.getElementById('cnpj').addEventListener('input', function() {
            let cnpj = this.value.replace(/\D/g, '');

            clearTimeout(timeout);

            if (cnpj.length !== 14 || cnpj === ultimoCNPJ) {
                return;
            }

            timeout = setTimeout(() => {
                ultimoCNPJ = cnpj;
                buscarCNPJ(cnpj);
            }, 400);
        });

        function buscarCNPJ(cnpj) {
            fetch(`https://open.cnpja.com/office/${cnpj}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Erro na consulta');
                    }
                    return response.json();
                })
                .then(data => {

                    // ===== RAZÃO SOCIAL =====
                    document.getElementById('razao_social').value =
                        data.company?.name ?? '';

                    const address = data.address ?? {};

                    // ===== ENDEREÇO =====
                    document.getElementById('logradouro').value = address.street ?? '';
                    document.getElementById('numero').value = address.number ?? '';
                    document.getElementById('complemento').value = address.details ?? '';
                    document.getElementById('bairro').value = address.district ?? '';
                    document.getElementById('estado').value = address.state ?? '';
                    document.getElementById('cidade').value = address.city ?? '';
                    document.getElementById('address').value = JSON.stringify(address ?? {});

                    // CEP formatado
                    document.getElementById('cep').value = formatarCEP(address.zip);
                })
                .catch(error => {
                    console.error(error);
                    alert('Erro ao consultar o CNPJ');
                });
        }

        function formatarCEP(cep) {
            if (!cep) return '';
            return cep.replace(/^(\d{5})(\d{3})$/, '$1-$2');
        }
    </script>


    <script>
        var simplemde = new SimpleMDE({
            element: document.getElementById("editor"),
            spellChecker: false,
            toolbar: ["bold", "italic", "strikethrough", "|", "unordered-list", "ordered-list", "|", "preview"]
        });
    </script>
    <script>
        document.getElementById('tipo_envio').addEventListener('change', function() {
            const campoImagem = document.getElementById('campoImagem');

            if (this.value === 'imagem') {
                campoImagem.classList.remove('d-none');
            } else {
                campoImagem.classList.add('d-none');
            }
        });
    </script>

</body>

</html>
