educar_escola_serie_cad.php 36.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
<?php

/**
 * i-Educar - Sistema de gestão escolar
 *
 * Copyright (C) 2006  Prefeitura Municipal de Itajaí
 *                     <ctima@itajai.sc.gov.br>
 *
 * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo
 * sob os termos da Licença Pública Geral GNU conforme publicada pela Free
 * Software Foundation; tanto a versão 2 da Licença, como (a seu critério)
 * qualquer versão posterior.
 *
 * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM
 * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU
 * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral
 * do GNU para mais detalhes.
 *
 * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto
 * com este programa; se não, escreva para a Free Software Foundation, Inc., no
 * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
 *
 * @author    Prefeitura Municipal de Itajaí <ctima@itajai.sc.gov.br>
 * @category  i-Educar
 * @license   @@license@@
 * @package   iEd_Pmieducar
 * @since     Arquivo disponível desde a versão 1.0.0
 * @version   $Id$
 */

use App\Process;
use App\Services\SchoolLevelsService;
use Illuminate\Support\Arr;

require_once 'include/clsBase.inc.php';
require_once 'include/clsCadastro.inc.php';
require_once 'include/clsBanco.inc.php';
require_once 'include/pmieducar/geral.inc.php';
require_once 'ComponenteCurricular/Model/AnoEscolarDataMapper.php';
require_once 'ComponenteCurricular/Model/ComponenteDataMapper.php';
require_once 'RegraAvaliacao/Model/RegraDataMapper.php';
require_once 'Avaliacao/Fixups/CleanComponentesCurriculares.php';
require_once 'include/modules/clsModulesAuditoriaGeral.inc.php';

/**
 * clsIndexBase class.
 *
 * @author    Prefeitura Municipal de Itajaí <ctima@itajai.sc.gov.br>
 * @category  i-Educar
 * @license   @@license@@
 * @package   iEd_Pmieducar
 * @since     Classe disponível desde a versão 1.0.0
 * @version   @@package_version@@
 */
class clsIndexBase extends clsBase
{
    function Formular()
    {
        $this->SetTitulo($this->_instituicao . ' i-Educar - Escola S&eacute;rie');
        $this->processoAp = 585;
    }
}

/**
 * indice class.
 *
 * @author    Prefeitura Municipal de Itajaí <ctima@itajai.sc.gov.br>
 * @category  i-Educar
 * @license   @@license@@
 * @package   iEd_Pmieducar
 * @since     Classe disponível desde a versão 1.0.0
 * @todo      Ver a questão de formulários que tem campos dinamicamente
 *   desabilitados de acordo com a requisição (GET, POST ou erro de validação).
 *   A forma atual de usar valores em campos hidden leva a diversos problemas
 *   como aumento da lógica de pré-validação nos métodos Novo() e Editar().
 * @version   @@package_version@@
 */
class indice extends clsCadastro
{
    var $pessoa_logada;
    var $ref_cod_escola;
    var $ref_cod_escola_;
    var $ref_cod_serie;
    var $ref_cod_serie_;
    var $ref_usuario_exc;
    var $ref_usuario_cad;
    var $hora_inicial;
    var $hora_final;
    var $data_cadastro;
    var $data_exclusao;
    var $ativo;
    var $hora_inicio_intervalo;
    var $hora_fim_intervalo;
    var $hora_fim_intervalo_;
    var $ref_cod_instituicao;
    var $ref_cod_curso;
    var $escola_serie_disciplina;
    var $ref_cod_disciplina;
    var $incluir_disciplina;
    var $excluir_disciplina;
    var $disciplinas;
    var $carga_horaria;
    var $etapas_especificas;
    var $etapas_utilizadas;
    var $definirComponentePorEtapa;
    var $anos_letivos;
    var $componente_anos_letivos;

    /**
     * @var SchoolLevelsService
     */
    private $escolaSerieService;

    function Inicializar()
    {
        $retorno = 'Novo';



        $this->ref_cod_serie = $_GET['ref_cod_serie'];
        $this->ref_cod_escola = $_GET['ref_cod_escola'];

        $obj_permissoes = new clsPermissoes();
        $obj_permissoes->permissao_cadastra(585, $this->pessoa_logada, 7, 'educar_escola_serie_lst.php');

        if (is_numeric($this->ref_cod_escola) && is_numeric($this->ref_cod_serie)) {
            $tmp_obj = new clsPmieducarEscolaSerie();
            $lst_obj = $tmp_obj->lista($this->ref_cod_escola, $this->ref_cod_serie);
            $registro = array_shift($lst_obj);

            if ($registro) {
                // passa todos os valores obtidos no registro para atributos do objeto
                foreach ($registro as $campo => $val) {
                    $this->$campo = $val;
                }
                $this->anos_letivos = json_decode($registro['anos_letivos']);

                $this->fexcluir = $obj_permissoes->permissao_excluir(585, $this->pessoa_logada, 7);
                $retorno = 'Editar';
            }
        }

        $this->url_cancelar = ($retorno == 'Editar') ? sprintf('educar_escola_serie_det.php?ref_cod_escola=%d&ref_cod_serie=%d', $registro['ref_cod_escola'], $registro['ref_cod_serie']) : 'educar_escola_serie_lst.php';

        $nomeMenu = $retorno == "Editar" ? $retorno : "Cadastrar";

        $this->breadcrumb($nomeMenu . ' vínculo entre escola e série', [
            url('intranet/educar_index.php') => 'Escola',
        ]);

        $this->nome_url_cancelar = 'Cancelar';

        return $retorno;
    }

    function Gerar()
    {
        if ($_POST) {
            foreach ($_POST as $campo => $val) {
                $this->$campo = ($this->$campo) ? $this->$campo : $val;
            }
        }

        $this->escolaSerieService = app(SchoolLevelsService::class);

        $regrasAvaliacao = $this->escolaSerieService->getEvaluationRules($this->ref_cod_serie);
        $anosLetivos = [];
        foreach ($regrasAvaliacao as $regraAvaliacao) {
            $anosLetivos[$regraAvaliacao->pivot->ano_letivo] = $regraAvaliacao->pivot->ano_letivo;
        }

        arsort($anosLetivos);
        $anoLetivoSelected = max($anosLetivos);

        if (request('ano_letivo')) {
            $anoLetivoSelected = request('ano_letivo');
        }

        $this->definirComponentePorEtapa = $this->escolaSerieService->levelAllowDefineDisciplinePerStage(
            $this->ref_cod_serie, $anoLetivoSelected);

        if (is_numeric($this->ref_cod_escola) && is_numeric($this->ref_cod_serie)) {
            $instituicao_desabilitado = true;
            $escola_desabilitado = true;
            $curso_desabilitado = true;
            $serie_desabilitado = true;
            $escola_serie_desabilitado = true;

            $this->campoOculto('ref_cod_instituicao_', $this->ref_cod_instituicao);
            $this->campoOculto('ref_cod_escola_', $this->ref_cod_escola);
            $this->campoOculto('ref_cod_curso_', $this->ref_cod_curso);
            $this->campoOculto('ref_cod_serie_', $this->ref_cod_serie);
        }

        $obrigatorio = true;
        $get_escola = true;
        $get_curso = true;
        $get_serie = false;
        $get_escola_serie = true;

        include 'include/pmieducar/educar_campo_lista.php';

        if ($this->ref_cod_escola_) {
            $this->ref_cod_escola = $this->ref_cod_escola_;
        }

        if ($this->ref_cod_serie_) {
            $this->ref_cod_serie = $this->ref_cod_serie_;
        }

        $opcoes_serie = array('' => 'Selecione');

        // Editar
        if ($this->ref_cod_curso) {
            $obj_serie = new clsPmieducarSerie();
            $obj_serie->setOrderby('nm_serie ASC');
            $lst_serie = $obj_serie->lista(
                array(
                    'ref_cod_curso' => $this->ref_cod_curso,
                    'ativo' => 1
                )
            );

            if (is_array($lst_serie) && count($lst_serie)) {
                foreach ($lst_serie as $serie) {
                    $opcoes_serie[$serie['cod_serie']] = $serie['nm_serie'];
                }
            }
        }

        $this->campoLista(
            'ref_cod_serie',
            'Série',
            $opcoes_serie,
            $this->ref_cod_serie,
            '',
            false,
            '',
            '',
            $this->ref_cod_serie ? true : false
        );

        $helperOptions = [
            'objectName' => 'anos_letivos'
        ];

        $this->anos_letivos = array_values(array_intersect($this->anos_letivos, $this->getAnosLetivosDisponiveis()));

        $options = [
            'label' => 'Anos letivos',
            'required' => true,
            'size' => 50,
            'options' => [
                'values' => $this->anos_letivos,
                'all_values' => $this->getAnosLetivosDisponiveis()
            ]
        ];
        $this->inputsHelper()->multipleSearchCustom('', $options, $helperOptions);

        $this->hora_inicial = substr($this->hora_inicial, 0, 5);
        $this->hora_final = substr($this->hora_final, 0, 5);
        $this->hora_inicio_intervalo = substr($this->hora_inicio_intervalo, 0, 5);
        $this->hora_fim_intervalo = substr($this->hora_fim_intervalo, 0, 5);

        // hora
        $this->campoHora('hora_inicial', 'Hora Inicial', $this->hora_inicial, false);
        $this->campoHora('hora_final', 'Hora Final', $this->hora_final, false);
        $this->campoHora('hora_inicio_intervalo', 'Hora In&iacute;cio Intervalo', $this->hora_inicio_intervalo, false);
        $this->campoHora('hora_fim_intervalo', 'Hora Fim Intervalo', $this->hora_fim_intervalo, false);
        $this->campoCheck("bloquear_enturmacao_sem_vagas", "Bloquear enturmação após atingir limite de vagas", $this->bloquear_enturmacao_sem_vagas);
        $this->campoCheck("bloquear_cadastro_turma_para_serie_com_vagas", "Bloquear cadastro de novas turmas antes de atingir limite de vagas (no mesmo turno)", $this->bloquear_cadastro_turma_para_serie_com_vagas);
        $this->campoQuebra();

        // Inclui disciplinas
        if (is_numeric($this->ref_cod_escola) && is_numeric($this->ref_cod_serie)) {
            $obj = new clsPmieducarEscolaSerieDisciplina();
            $registros = $obj->lista($this->ref_cod_serie, $this->ref_cod_escola, null, 1);

            if ($registros) {
                $registros = array_map(function ($item) {
                    foreach ($item as $k => $v) {
                        if (is_numeric($k)) {
                            unset($item[$k]);
                        }
                    }

                    $item['anos_letivos'] = json_decode($item['anos_letivos']);
                    $item['carga_horaria'] = floatval($item['carga_horaria']);

                    return $item;
                }, $registros);

                $this->campoOculto('componentes_sombra', json_encode($registros));

                foreach ($registros as $campo) {
                    $this->escola_serie_disciplina[$campo['ref_cod_disciplina']] = $campo['ref_cod_disciplina'];
                    $this->escola_serie_disciplina_carga[$campo['ref_cod_disciplina']] = $campo['carga_horaria'];
                    $this->escola_serie_disciplina_anos_letivos[$campo['ref_cod_disciplina']] = $campo['anos_letivos'] ?: [];

                    if ($this->definirComponentePorEtapa) {
                        $this->escola_serie_disciplina_etapa_especifica[$campo['ref_cod_disciplina']] = intval($campo['etapas_especificas']);
                        $this->escola_serie_disciplina_etapa_utilizada[$campo['ref_cod_disciplina']] = $campo['etapas_utilizadas'];
                    }
                }
            }
        }

        // Editar
        $disciplinas = 'Nenhum ano letivo selecionado';

        if ($this->ref_cod_serie) {
            $disciplinas = '';
            $conteudo = '';

            // Instancia o mapper de ano escolar
            $anoEscolar = new ComponenteCurricular_Model_AnoEscolarDataMapper();
            $lista = $anoEscolar->findComponentePorSerie($this->ref_cod_serie);

            if (is_array($lista) && count($lista)) {
                $conteudo .= '<div style="margin-bottom: 10px; float: left">';
                $conteudo .= '  <span style="display: block; float: left; width: 250px;">Nome</span>';
                $conteudo .= '  <span style="display: block; float: left; width: 100px;">Nome abreviado</span>';
                $conteudo .= '  <span style="display: block; float: left; width: 100px;">Carga horária</span>';
                $conteudo .= '  <span style="display: block; float: left; width: 180px;" >Usar padrão do componente?</span>';
                $conteudo .= '  <span style="display: block; float: left; width: 150px;">Anos letivos</span>';

                if ($this->definirComponentePorEtapa) {
                    $conteudo .= '  <span style="display: block; float: left; margin-left: 30px;">Usado em etapas específicas?(Exemplo: 1,2 / 1,3)</span>';
                }

                $conteudo .= '</div>';
                $conteudo .= '<br style="clear: left" />';
                $conteudo .= '<div style="margin-bottom: 10px; float: left">';
                $conteudo .= "  <label style='display: block; float: left; width: 450px;'><input type='checkbox' name='CheckTodos' onClick='marcarCheck(" . '"disciplinas[]"' . ");'/>Marcar Todos</label>";
                $conteudo .= "  <label style='display: block; float: left; width: 330px;'><input type='checkbox' name='CheckTodos2' onClick='marcarCheck(" . '"usar_componente[]"' . ");';/>Marcar Todos</label>";

                if ($this->definirComponentePorEtapa) {
                    $conteudo .= "  <label style='display: block; float: left; width: 100px; margin-left: 84px;'><input type='checkbox' name='CheckTodos3' onClick='marcarCheck(" . '"etapas_especificas[]"' . ");';/>Marcar Todos</label>";
                }

                $conteudo .= '</div>';
                $conteudo .= '<br style="clear: left" />';

                foreach ($lista as $registro) {
                    $checked = '';
                    $checkedEtapaEspecifica = '';
                    $usarComponente = false;
                    $anosLetivosComponente = [];

                    if ($this->escola_serie_disciplina[$registro->id] == $registro->id) {
                        $checked = 'checked="checked"';

                        if ($this->escola_serie_disciplina_etapa_especifica[$registro->id] == "1") {
                            $checkedEtapaEspecifica = 'checked="checked"';
                        }
                    }

                    if (is_null($this->escola_serie_disciplina_carga[$registro->id]) || 0 == $this->escola_serie_disciplina_carga[$registro->id]) {
                        $usarComponente = true;
                    } else {
                        $cargaHoraria = $this->escola_serie_disciplina_carga[$registro->id];
                    }

                    if (!empty($this->escola_serie_disciplina_anos_letivos[$registro->id])) {
                        $anosLetivosComponente = $this->escola_serie_disciplina_anos_letivos[$registro->id];
                    }

                    $cargaComponente = $registro->cargaHoraria;
                    $etapas_utilizadas = $this->escola_serie_disciplina_etapa_utilizada[$registro->id];

                    $conteudo .= '<div style="margin-bottom: 10px; float: left">';
                    $conteudo .= "  <label style='display: block; float: left; width: 250px'><input type=\"checkbox\" $checked name=\"disciplinas[$registro->id]\" id=\"disciplinas[]\" value=\"{$registro->id}\">{$registro}</label>";
                    $conteudo .= "  <span style='display: block; float: left; width: 100px'>{$registro->abreviatura}</span>";
                    $conteudo .= "  <label style='display: block; float: left; width: 100px;'><input type='text' name='carga_horaria[$registro->id]' value='{$cargaHoraria}' size='5' maxlength='7'></label>";
                    $conteudo .= "  <label style='display: block; float: left;  width: 180px;'><input type='checkbox' id='usar_componente[]' name='usar_componente[$registro->id]' value='1' " . ($usarComponente == true ? $checked : '') . ">($cargaComponente h)</label>";

                    $conteudo .= "
                            <select name='componente_anos_letivos[{$registro->id}][]'
                                style='width: 150px;'
                                multiple='multiple'> ";

                    foreach ($this->anos_letivos as $anoLetivo) {
                        $seletected = in_array($anoLetivo, $anosLetivosComponente) ? 'selected=selected' : '';
                        $conteudo .= "<option value='{$anoLetivo}' {$seletected}>{$anoLetivo}</option>";
                    }
                    $conteudo .= " </select>";

                    if ($this->definirComponentePorEtapa) {
                        $conteudo .= "  <input style='margin-left:140px; float:left;' type='checkbox' id='etapas_especificas[]' name='etapas_especificas[$registro->id]' value='1' " . $checkedEtapaEspecifica . "></label>";
                        $conteudo .= "  <label style='display: block; float: left; width: 100px;'>Etapas utilizadas: <input type='text' class='etapas_utilizadas' name='etapas_utilizadas[$registro->id]' value='{$etapas_utilizadas}' size='5' maxlength='7'></label>";
                    }

                    $conteudo .= '</div>';
                    $conteudo .= '<br style="clear: left" />';

                    $cargaHoraria = '';
                }

                $disciplinas = '<table cellspacing="0" cellpadding="0" border="0">';
                $disciplinas .= sprintf('<tr align="left"><td>%s</td></tr>', $conteudo);
                $disciplinas .= '</table>';
            } else {
                $disciplinas = 'A série/ano escolar não possui componentes curriculares cadastrados.';
            }

            $this->campoLista(
                'ano_letivo',
                'Ano letivo',
                $anosLetivos,
                $anoLetivoSelected,
                '',
                false,
                'Usado para recuperar a regra de avalição que será usada para verificações dos campos abaixo',
                '',
                false,
                false
            );
        }

        $this->campoRotulo("disciplinas_", "Componentes curriculares", "<div id='disciplinas'>$disciplinas</div>");
        $this->campoQuebra();

        $obj_permissoes = new clsPermissoes();
        $permissaoConsultaDispensas = $obj_permissoes->permissao_cadastra(Process::EXEMPTION_LIST, $this->pessoa_logada, null);
        $this->campoOculto('permissao_consulta_dispensas', intval($permissaoConsultaDispensas));
    }

    function Novo()
    {


        /*
         * Se houve erro na primeira tentativa de cadastro, irá considerar apenas
         * os valores enviados de forma oculta.
         */
        if (isset($this->ref_cod_instituicao_)) {
            $this->ref_cod_instituicao = $this->ref_cod_instituicao_;
            $this->ref_cod_escola = $this->ref_cod_escola_;
            $this->ref_cod_curso = $this->ref_cod_curso_;
            $this->ref_cod_serie = $this->ref_cod_serie_;
        }

        $this->bloquear_enturmacao_sem_vagas = is_null($this->bloquear_enturmacao_sem_vagas) ? 0 : 1;
        $this->bloquear_cadastro_turma_para_serie_com_vagas = is_null($this->bloquear_cadastro_turma_para_serie_com_vagas) ? 0 : 1;

        $obj = new clsPmieducarEscolaSerie(
            $this->ref_cod_escola,
            $this->ref_cod_serie,
            $this->pessoa_logada,
            $this->pessoa_logada,
            $this->hora_inicial,
            $this->hora_final,
            null,
            null,
            1,
            $this->hora_inicio_intervalo,
            $this->hora_fim_intervalo,
            $this->bloquear_enturmacao_sem_vagas,
            $this->bloquear_cadastro_turma_para_serie_com_vagas,
            $this->anos_letivos ?: []
        );

        if ($obj->existe()) {
            $detalheAntigo = $obj->detalhe();
            $cadastrou = $obj->edita();
            $auditoria = new clsModulesAuditoriaGeral("escola_serie", $this->pessoa_logada);
            $auditoria->alteracao($detalheAntigo, $obj->detalhe());
        } else {
            $cadastrou = $obj->cadastra();

            $auditoria = new clsModulesAuditoriaGeral("escola_serie", $this->pessoa_logada);
            $auditoria->inclusao($obj->detalhe());
        }

        if ($cadastrou) {
            if ($this->disciplinas) {
                foreach ($this->disciplinas as $key => $campo) {
                    $obj = new clsPmieducarEscolaSerieDisciplina(
                        $this->ref_cod_serie,
                        $this->ref_cod_escola,
                        $campo,
                        1,
                        $this->carga_horaria[$key],
                        $this->etapas_especificas[$key],
                        $this->etapas_utilizadas[$key],
                        $this->componente_anos_letivos[$key] ?: []
                    );

                    if ($obj->existe()) {
                        $cadastrou1 = $obj->edita();
                    } else {
                        $cadastrou1 = $obj->cadastra();
                    }

                    if (!$cadastrou1) {
                        $this->mensagem = 'Cadastro n&atilde;o realizado.<br>';

                        return false;
                    }
                }
            }

            $this->mensagem .= 'Cadastro efetuado com sucesso.<br>';
            $this->simpleRedirect('educar_escola_serie_lst.php');
        }

        $this->mensagem = 'Cadastro n&atilde;o rrealizado.<br>';

        return false;
    }

    function Editar()
    {
        /*
         * Atribui valor para atributos usados em Gerar(), senão o formulário volta
         * a liberar os campos Instituição, Escola e Curso que devem ser read-only
         * quando em modo de edição
         */
        $this->ref_cod_instituicao = $this->ref_cod_instituicao_;
        $this->ref_cod_escola = $this->ref_cod_escola_;
        $this->ref_cod_curso = $this->ref_cod_curso_;
        $this->ref_cod_serie = $this->ref_cod_serie_;

        $this->bloquear_enturmacao_sem_vagas = is_null($this->bloquear_enturmacao_sem_vagas) ? 0 : 1;
        $this->bloquear_cadastro_turma_para_serie_com_vagas = is_null($this->bloquear_cadastro_turma_para_serie_com_vagas) ? 0 : 1;

        $obj = new clsPmieducarEscolaSerie(
            $this->ref_cod_escola,
            $this->ref_cod_serie,
            $this->pessoa_logada,
            null,
            $this->hora_inicial,
            $this->hora_final,
            null,
            null,
            1,
            $this->hora_inicio_intervalo,
            $this->hora_fim_intervalo,
            $this->bloquear_enturmacao_sem_vagas,
            $this->bloquear_cadastro_turma_para_serie_com_vagas,
            $this->anos_letivos ?: []
        );

        $sombra = json_decode(urldecode($this->componentes_sombra), true);
        $disciplinas = $this->montaDisciplinas();
        $analise = $this->analisaAlteracoes($sombra, $disciplinas);

        try {
            $this->validaAlteracoes($analise);
        } catch (Exception $e) {
            $msgs = explode("\n", $e->getMessage());

            $this->mensagem = $msgs;

            return $this->simpleRedirect(\Request::getRequestUri());
        }

        $detalheAntigo = $obj->detalhe();
        $editou = $obj->edita();

        $auditoria = new clsModulesAuditoriaGeral("escola_serie", $this->pessoa_logada);
        $auditoria->alteracao($detalheAntigo, $obj->detalhe());

        $obj = new clsPmieducarEscolaSerieDisciplina(
            $this->ref_cod_serie,
            $this->ref_cod_escola,
            $campo,
            1
        );

        $obj->excluirNaoSelecionados($this->disciplinas);

        if ($editou) {
            if ($this->disciplinas) {
                foreach ($this->disciplinas as $key => $campo) {
                    if (isset($this->usar_componente[$key])) {
                        $carga_horaria = null;
                    } else {
                        $carga_horaria = $this->carga_horaria[$key];
                    }

                    $etapas_especificas = $this->etapas_especificas[$key];
                    $etapas_utilizadas = $this->etapas_utilizadas[$key];

                    $obj = new clsPmieducarEscolaSerieDisciplina(
                        $this->ref_cod_serie,
                        $this->ref_cod_escola,
                        $campo,
                        1,
                        $carga_horaria,
                        $etapas_especificas,
                        $etapas_utilizadas,
                        $this->componente_anos_letivos[$key] ?: []
                    );

                    $existe = $obj->existe();

                    if ($existe) {
                        $editou1 = $obj->edita();

                        if (!$editou1) {
                            $this->mensagem = 'Edi&ccedil;&atilde;o n&atilde;o realizada.<br>';

                            return false;
                        }
                    } else {
                        $cadastrou = $obj->cadastra();

                        if (!$cadastrou) {
                            $this->mensagem = 'Cadastro n&atilde;o realizada.<br>';

                            return false;
                        }
                    }
                }
            }

            $this->mensagem .= 'Edi&ccedil;&atilde;o efetuada com sucesso.<br>';
            $this->simpleRedirect('educar_escola_serie_lst.php');
        }

        $this->mensagem = 'Edi&ccedil;&atilde;o n&atilde;o realizada.<br>';
        return false;
    }

    function Excluir()
    {


        $obj = new clsPmieducarEscolaSerie(
            $this->ref_cod_escola_,
            $this->ref_cod_serie_,
            $this->pessoa_logada,
            null,
            null,
            null,
            null,
            null,
            0
        );

        $detalhe = $obj->detalhe();
        $excluiu = $obj->excluir();
        $auditoria = new clsModulesAuditoriaGeral("escola_serie", $this->pessoa_logada);
        $auditoria->exclusao($detalhe);

        if ($excluiu) {
            $obj = new clsPmieducarEscolaSerieDisciplina($this->ref_cod_serie_, $this->ref_cod_escola_, null, 0);
            $excluiu1 = $obj->excluirTodos();

            if ($excluiu1) {
                $this->mensagem .= "Exclus&atilde;o efetuada com sucesso.<br>";
                $this->simpleRedirect('educar_escola_serie_lst.php');
            }
        }

        $this->mensagem = "Exclus&atilde;o n&atilde;o realizada.<br>";

        return false;
    }

    public function __construct()
    {
        parent::__construct();
        $this->loadAssets();
    }

    public function loadAssets()
    {
        $scripts = array(
            '/modules/Portabilis/Assets/Javascripts/ClientApi.js',
            '/modules/Cadastro/Assets/Javascripts/EscolaSerie.js',
            '/modules/Cadastro/Assets/Javascripts/ModalDispensas.js'
        );

        Portabilis_View_Helper_Application::loadJavascript($this, $scripts);
    }

    private function getAnosLetivosDisponiveis()
    {
        $anosLetivosDisponiveis = [];

        if (is_numeric($this->ref_cod_escola) && is_numeric($this->ref_cod_curso)) {
            $objEscolaCurso = new clsPmieducarEscolaCurso($this->ref_cod_escola, $this->ref_cod_curso);
            if ($escolaCurso = $objEscolaCurso->detalhe()) {
                $anosLetivosDisponiveis = json_decode($escolaCurso['anos_letivos']) ?: [];
            }
        }

        return array_combine($anosLetivosDisponiveis, $anosLetivosDisponiveis);
    }

    private function montaDisciplinas()
    {
        $disciplinas = [];

        foreach ($this->disciplinas as $componenteId) {
            if (isset($this->usar_componente[$componenteId])) {
                $carga_horaria = null;
            } else {
                $carga_horaria = $this->carga_horaria[$componenteId];
            }

            $anosLetivos = $this->componente_anos_letivos[$componenteId] ?: [];
            $anosLetivos = array_map(function ($ano) {
                return (int) $ano;
            }, $anosLetivos);

            $disciplinas[] = [
                'ref_ref_cod_serie' => $this->ref_cod_serie,
                'ref_ref_cod_escola' => $this->ref_cod_escola,
                'ref_cod_disciplina' => $componenteId,
                'carga_horaria' => $carga_horaria,
                'etapas_especificas' => $this->etapas_especificas[$componenteId],
                'etapas_utilizadas' => $this->etapas_utilizadas[$componenteId],
                'anos_letivos' => $anosLetivos
            ];
        }

        return $disciplinas;
    }

    private function analisaAlteracoes($originais, $novos)
    {
        $remover = [];
        $inserir = [];
        $atualizar = [];

        foreach ($novos as $novo) {
            $original = Arr::where($originais, function ($v, $k) use ($novo) {
                return (int) $v['ref_cod_disciplina'] === (int) $novo['ref_cod_disciplina'];
            });

            if ($original) {
                $key = array_keys($original)[0];
                $original = $original[$key];
            } else {
                $original = null;
            }

            if (is_null($original)) {
                $inserir[] = $novo;

                continue;
            }

            $novo['anos_letivos_acrescentar'] = array_diff($novo['anos_letivos'], $original['anos_letivos']);
            $novo['anos_letivos_remover'] = array_diff($original['anos_letivos'], $novo['anos_letivos']);

            $atualizar[] = $novo;
        }

        $idsOriginais = Arr::pluck($originais, 'ref_cod_disciplina');
        $idsNovos = Arr::pluck($novos, 'ref_cod_disciplina');
        $remover = array_diff($idsOriginais, $idsNovos);

        return compact('remover', 'inserir', 'atualizar');
    }

    private function validaAlteracoes($analise)
    {
        $erros = [];

        if ($analise['inserir']) {
            foreach ($analise['inserir'] as $insert) {
                $anos = $insert['anos_letivos'] ?? [];
                $componente = Portabilis_Utils_Database::fetchPreparedQuery(
                    'SELECT nome FROM modules.componente_curricular WHERE id = $1',
                    ['params' => [(int) $insert['ref_cod_disciplina']]]
                )[0]['nome'];

                foreach ($anos as $ano) {
                    $info = Portabilis_Utils_Database::fetchPreparedQuery('
                        SELECT COUNT(*)
                        FROM modules.componente_curricular_ano_escolar
                        WHERE TRUE
                            AND componente_curricular_id = $1
                            AND ano_escolar_id = $2
                            AND $3 = ANY(anos_letivos)
                    ', ['params' => [
                        (int) $insert['ref_cod_disciplina'],
                        $this->ref_cod_serie,
                        $ano
                    ]]);

                    $count = (int) $info[0]['count'] ?? 0;

                    if ($count < 1) {
                        $erros[] = sprintf('O ano %d de "%s" precisa estar devidamente cadastrado nesta série em Componentes da série (Escola > Cadastros > Tipos > Séries > Componentes da série).', $ano, $componente);
                    }
                }
            }
        }

        if ($analise['remover']) {
            foreach ($analise['remover'] as $componenteId) {
                $info = Portabilis_Utils_Database::fetchPreparedQuery('
                    SELECT COUNT(cct.*), cc.nome
                    FROM modules.componente_curricular_turma cct
                    INNER JOIN modules.componente_curricular cc ON cc.id = cct.componente_curricular_id
                    WHERE TRUE
                        AND cct.componente_curricular_id = $1
                        AND cct.ano_escolar_id = $2
                        AND cct.escola_id = $3
                    GROUP BY cc.nome
                ', ['params' => [
                    (int) $componenteId,
                    $this->ref_cod_serie,
                    $this->ref_cod_escola
                ]]);

                $count = (int) $info[0]['count'] ?? 0;

                if ($count > 0) {
                    $erros[] = sprintf('Não é possível desvincular "%s" pois existem turmas vinculadas a este componente.', $info[0]['nome']);
                }

                $info = Portabilis_Utils_Database::fetchPreparedQuery('
                    SELECT COUNT(ncc.*), cc.nome
                    FROM modules.nota_componente_curricular ncc
                    INNER JOIN modules.nota_aluno na on na.id = ncc.nota_aluno_id
                    INNER JOIN pmieducar.matricula m on m.cod_matricula = na.matricula_id
                    INNER JOIN modules.componente_curricular cc on cc.id = ncc.componente_curricular_id
                    WHERE TRUE
                        AND ncc.componente_curricular_id = $1
                        AND m.ref_ref_cod_serie = $2
                        AND m.ref_ref_cod_escola = $3
                    GROUP BY cc.nome
                ', ['params' => [
                    (int) $componenteId,
                    $this->ref_cod_serie,
                    $this->ref_cod_escola
                ]]);

                $count = (int) $info[0]['count'] ?? 0;

                if ($count > 0) {
                    $erros[] = sprintf('Não é possível desvincular "%s" pois já existem notas lançadas para este componente nesta série e escola.', $info[0]['nome']);
                }
            }
        }

        if ($analise['atualizar']) {
            foreach ($analise['atualizar'] as $update) {
                if (!empty($update['anos_letivos_remover'])) {
                    foreach ($update['anos_letivos_remover'] as $ano) {
                        $info = Portabilis_Utils_Database::fetchPreparedQuery("
                            SELECT COUNT(ncc.*), cc.nome
                            FROM modules.nota_componente_curricular ncc
                            INNER JOIN modules.nota_aluno na on na.id = ncc.nota_aluno_id
                            INNER JOIN pmieducar.matricula m on m.cod_matricula = na.matricula_id
                            INNER JOIN modules.componente_curricular cc on cc.id = ncc.componente_curricular_id
                            WHERE TRUE
                                AND ncc.componente_curricular_id = $1
                                AND m.ref_ref_cod_serie = $2
                                AND m.ano = $3
                                AND m.ref_ref_cod_escola = $4
                            GROUP BY cc.nome
                        ", ['params' => [
                            (int) $update['ref_cod_disciplina'],
                            $this->ref_cod_serie,
                            $ano,
                            $this->ref_cod_escola
                        ]]);

                        $count = (int) $info[0]['count'] ?? 0;

                        if ($count > 0) {
                            $erros[] = sprintf('Não é possível desvincular o ano %d de "%s" pois já existem notas lançadas para este componente nesta série, ano e escola.', $ano, $info[0]['nome']);
                        }
                    }
                }

                if (!empty($update['anos_letivos_acrescentar'])) {
                    $componente = Portabilis_Utils_Database::fetchPreparedQuery(
                        'SELECT nome FROM modules.componente_curricular WHERE id = $1',
                        ['params' => [(int) $update['ref_cod_disciplina']]]
                    )[0]['nome'];

                    foreach ($update['anos_letivos_acrescentar'] as $ano) {
                        $info = Portabilis_Utils_Database::fetchPreparedQuery('
                            SELECT COUNT(*)
                            FROM modules.componente_curricular_ano_escolar
                            WHERE TRUE
                                AND componente_curricular_id = $1
                                AND ano_escolar_id = $2
                                AND $3 = ANY(anos_letivos)
                        ', ['params' => [
                            (int) $update['ref_cod_disciplina'],
                            $this->ref_cod_serie,
                            $ano
                        ]]);

                        $count = (int) $info[0]['count'] ?? 0;

                        if ($count < 1) {
                            $erros[] = sprintf('O ano %d de "%s" precisa estar devidamente cadastrado nesta série em Componentes da série (Escola > Cadastros > Tipos > Séries > Componentes da série).', $ano, $componente);
                        }
                    }
                }
            }
        }

        if ($erros) {
            $msg = join("\n", $erros);

            throw new \Exception($msg);
        }

        return true;
    }
}

// Instancia objeto de página
$pagina = new clsIndexBase();

// Instancia objeto de conteúdo
$miolo = new indice();

// Atribui o conteúdo à  página
$pagina->addForm($miolo);

// Gera o código HTML
$pagina->MakeAll();
?>