<?php
/**
 * Ce script définit la classe 'emplacement_archive'.
 *
 * @package opencimetiere
 * @version SVN : $Id$
 */

require_once "../gen/obj/emplacement_archive.class.php";
require_once dirname(__DIR__)."/vendor/autoload.php";

/**
 * Définition de la classe 'emplacement_archive' (om_dbform).
 */
class emplacement_archive extends emplacement_archive_gen {

    /**
     * Définition des actions disponibles sur la classe.
     *
     * @return void
     */
    function init_class_actions() {
        parent::init_class_actions();
        // ACTION - 001 - modifier
        // -> modification impossible
        unset($this->class_actions[1]);
        // ACTION - 002 - supprimer
        // -> suppression impossible
        unset($this->class_actions[2]);
        // ACTION - 003 - consulter
        // Utilisation de la vue Twig personnalisée + vérification de collectivité
        $this->class_actions[3]['view'] = "view_consulter";
        $this->class_actions[3]['condition'][] = "is_user_from_allowed_collectivite";
    }

    /**
     *
     * @return array
     */
    function get_var_sql_forminc__champs() {
        return array(
            "emplacement",
            "numero",
            "complement",
            "emplacement_archive.voie as voie",
            "numerocadastre",
            //adresse
            "concat(
                trim(concat(
                    emplacement_archive.numero,
                    ' ',
                    emplacement_archive.complement
                )),
                ' ',
                voie_type.libelle,
                ' ',
                voie.voielib,
                ' [',
                zone_type.libelle,
                ' ',
                zone.zonelib,
                '][',
                cimetiere.cimetierelib,
                ']'
            ) as adresse",
            "famille",
            "numeroacte",
            "datevente",
            "terme",
            "duree",
            "dateterme",
            "nombreplace",
            "placeoccupe",
            "superficie",
            "placeconstat",
            "dateconstat",
            "observation",
            "plans",
            "positionx",
            "positiony",
            "photo",
            "libre",
            "sepulturetype",
            "emplacement_archive.geom as geom",
            "emplacement_archive.pgeom as pgeom",
            "daterenouvellement",
            "typeconcession",
            "videsanitaire",
            "semelle",
            "etatsemelle",
            "monument",
            "etatmonument",
            "largeur",
            "profondeur",
            "abandon",
            "date_abandon",
            "dateacte",
            "has_mort_pour_la_france",
            "emplacement_archive.om_collectivite as om_collectivite",
            "nature",
        );
    }


    /**
     * GETTER_FORMINC - tableSelect.
     *
     * @return string
     */
    function get_var_sql_forminc__tableSelect() {
        return DB_PREFIXE."emplacement_archive
            LEFT JOIN ".DB_PREFIXE."om_collectivite
                ON emplacement_archive.om_collectivite=om_collectivite.om_collectivite
            LEFT JOIN ".DB_PREFIXE."voie
                ON emplacement_archive.voie=voie.voie
            LEFT JOIN ".DB_PREFIXE."voie_type
                ON voie.voietype=voie_type.voie_type
            LEFT JOIN ".DB_PREFIXE."zone
                ON voie.zone=zone.zone
            LEFT JOIN ".DB_PREFIXE."zone_type
                ON zone.zonetype=zone_type.zone_type
            LEFT JOIN ".DB_PREFIXE."cimetiere
                ON zone.cimetiere=cimetiere.cimetiere
        ";
    }

    /**
     * SETTER_FORM - setType.
     *
     * @return void
     */
    function setType(&$form, $maj) {
        parent::setType($form, $maj);

        $form->setType("geom", "hidden");
        $form->setType("pgeom", "hidden");
    }

    /**
     * Affiche le contenu de la vue personnalisée (consultation via Twig).
     *
     * @return void
     */
    function display__view_consulter_content() {

        // Initialisation et paramétrage de twig
        $loader = new \Twig\Loader\FilesystemLoader('../app/views');
        $twig = new \Twig\Environment($loader, [
            'cache' => PATH_TWIG_CACHE,
        ]);
        $twig->enableAutoReload();

        // Récupération de la configuration des blocs depuis la base de données
        $nature_id = $this->getVal('nature');

        $qres = $this->f->get_all_results_from_db_query(
            sprintf(
                "SELECT
                    libelle,
                    bloc_acte,
                    bloc_bati,
                    bloc_place,
                    bloc_abandon
                FROM %snature_emplacement
                WHERE nature_emplacement = %d",
                DB_PREFIXE,
                intval($nature_id)
            )
        );

        // Composants toujours affichés
        $components = ['adresse', 'observations'];
        $nature_libelle = '';

        // Ajout des blocs conditionnels selon la configuration de la nature
        if ($qres['code'] === 'OK' && !empty($qres['result'])) {
            $nature_config = $qres['result'][0];
            $nature_libelle = $nature_config['libelle'];

            if ($nature_config['bloc_acte'] === 't') {
                $components[] = 'acte-concession';
            }
            if ($nature_config['bloc_bati'] === 't') {
                $components[] = 'bati';
            }
            if ($nature_config['bloc_abandon'] === 't') {
                $components[] = 'abandon';
            }
            if ($nature_config['bloc_place'] === 't') {
                $components[] = 'gestion-place';
            }
        }

        // Construction du tableau de valeurs pour le template
        $values = [];
        foreach ($this->champs as $key => $champ) {
            $values[$champ] = $this->val[$key];
        }
        $values["type"] = $nature_libelle;
        $values["reprise_sur_abandon"] = null;
        $values["reprise_etapes_labels"] = [];
        $values['reprise_etapes_visibles'] = '';
        $values["sepulture_libelle"] = $this->get_sepulture_libelle();
        $values["contrats"] = $this->get_contrats();
        $values["travaux"] = $this->get_travaux();
        $values["operations"] = $this->get_operations();
        $values["contacts"] = $this->get_contacts();
        $values["option_localisation"] = $this->f->getParameter("option_localisation");
        $values["om_collectivite"] = '';
        if ($_SESSION['niveau'] == 2) {
            $values["om_collectivite"] = $this->get_om_collectivite_libelle();
        }
        // Pas de carte SIG/plan pour une archive
        $values["map_sig"] = '';
        $values["map_plan"] = '';
        $values['lien_sig_externe'] = '';
        $values['components'] = $components;

        // Rendu Twig
        try {
            echo $twig->render('emplacement/emplacement.html', $values);
        } catch (\Twig\Error\Error $e) {
            echo "Erreur Twig : " . $e->getMessage();
        }
    }

    /**
     * Récupération des contrats archivés liés à cet emplacement.
     *
     * @return array
     */
    function get_contrats() {
        if ($this->getVal($this->clePrimaire) == NULL) {
            return [];
        }

        $sql = sprintf(
            'SELECT
                %1$s.contrat,
                %1$s.emplacement,
                %1$s.datedemande,
                %1$s.datevente,
                %1$s.origine,
                %1$s.dateterme,
                %1$s.terme,
                %1$s.duree,
                %1$s.montant,
                %1$s.monnaie,
                %1$s.valide,
                %1$s.observation
            FROM
                %2$s%1$s
            WHERE
                %1$s.emplacement = %3$s',
            'contrat_archive',
            DB_PREFIXE,
            $this->getVal("emplacement")
        );

        $res = $this->f->db->query($sql);
        $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
        $this->f->isDatabaseError($res);

        $contrats = [];
        while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $row['onclick'] = "";
            $contrats[] = $row;
        }
        return $contrats;
    }

    /**
     * Récupération des travaux archivés liés à cet emplacement.
     *
     * @return array
     */
    function get_travaux() {
        if ($this->getVal($this->clePrimaire) == NULL) {
            return [];
        }

        $sql = sprintf(
            'SELECT
                %1$s.travaux,
                entreprise.nomentreprise as entreprise,
                %1$s.datedebinter,
                %1$s.datefininter,
                %1$s.naturedemandeur,
                travaux_nature.libelle as naturetravaux,
                CONCAT(autorisation_archive.prenom, \' \', autorisation_archive.nom) as demandeur
            FROM
                %2$s%1$s
            LEFT JOIN
                %2$sentreprise ON entreprise.entreprise = %1$s.entreprise
            LEFT JOIN
                %2$stravaux_nature ON travaux_nature.travaux_nature = %1$s.naturetravaux
            LEFT JOIN
                %2$sautorisation_archive ON autorisation_archive.autorisation = %1$s.demandeur
            WHERE
                %1$s.emplacement = %3$s',
            'travaux_archive',
            DB_PREFIXE,
            $this->getVal("emplacement")
        );

        $res = $this->f->db->query($sql);
        $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
        $this->f->isDatabaseError($res);

        $travaux = [];
        while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $travaux[] = $row;
        }
        return $travaux;
    }

    /**
     * Récupération des opérations archivées liées à cet emplacement.
     *
     * @return array
     */
    function get_operations() {
        if ($this->getVal($this->clePrimaire) == NULL) {
            return [];
        }

        $sql = sprintf(
            'SELECT
                %1$s.operation,
                %1$s.numdossier,
                %1$s.date,
                %1$s.heure,
                %1$s.emplacement,
                %1$s.societe_coordonnee,
                %1$s.pf_coordonnee,
                %1$s.etat,
                %1$s.categorie,
                %1$s.particulier,
                %1$s.emplacement_transfert,
                %1$s.observation,
                %1$s.consigne_acces,
                %1$s.prive,
                %1$s.edition_operation,
                %1$s.consigne_acces_transfert,
                %1$s.demandeur
            FROM
                %2$s%1$s
            WHERE
                %1$s.emplacement = %3$s',
            'operation_archive',
            DB_PREFIXE,
            $this->getVal("emplacement")
        );

        $res = $this->f->db->query($sql);
        $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
        $this->f->isDatabaseError($res);

        $operations = [];
        while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $operations[] = $row;
        }
        return $operations;
    }

    /**
     * Récupération des contacts archivés liés à cet emplacement.
     *
     * @return array
     */
    function get_contacts() {
        if ($this->getVal($this->clePrimaire) == NULL) {
            return [];
        }

        $sql = sprintf(
            'SELECT
                %1$s.autorisation,
                %1$s.emplacement,
                %1$s.nature,
                titre_de_civilite.libelle as titre,
                %1$s.nom,
                %1$s.marital,
                %1$s.prenom,
                %1$s.adresse1,
                %1$s.adresse2,
                %1$s.cp,
                %1$s.ville,
                %1$s.telephone1,
                %1$s.telephone2,
                %1$s.courriel
            FROM
                %2$s%1$s
            LEFT JOIN
                %2$stitre_de_civilite ON titre_de_civilite.titre_de_civilite = %1$s.titre
            WHERE
                %1$s.emplacement = %3$s',
            'autorisation_archive',
            DB_PREFIXE,
            $this->getVal("emplacement")
        );

        $res = $this->f->db->query($sql);
        $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
        $this->f->isDatabaseError($res);

        $contacts = [];
        while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $contacts[] = $row;
        }
        return $contacts;
    }

    /**
     * Récupère le libellé du type de sépulture.
     *
     * @return string|null
     */
    function get_sepulture_libelle() {
        if ($this->getVal("sepulturetype") == NULL) {
            return null;
        }

        $sql = sprintf(
            'SELECT sepulture_type.libelle FROM %ssepulture_type WHERE sepulture_type = %s',
            DB_PREFIXE,
            $this->getVal("sepulturetype")
        );

        $res = $this->f->db->query($sql);
        $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
        $this->f->isDatabaseError($res);

        $sepulture_libelle = "";
        while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $sepulture_libelle = $row['libelle'];
        }
        return $sepulture_libelle;
    }

    /**
     * Récupère le libellé de la collectivité.
     *
     * @param int $om_collectivite_id Identifiant de la collectivité.
     * @return string
     */
    function get_om_collectivite_libelle($om_collectivite_id = null) {
        if ($om_collectivite_id === null) {
            $om_collectivite_id = $this->getVal('om_collectivite');
        }
        if (empty($om_collectivite_id)) {
            return '';
        }

        $sql = sprintf(
            "SELECT libelle FROM %som_collectivite WHERE om_collectivite = %s",
            DB_PREFIXE,
            intval($om_collectivite_id)
        );

        $qres = $this->f->get_one_result_from_db_query(
            $sql,
            array('force_return' => false, 'origin' => __METHOD__)
        );

        if ($qres['code'] === 'OK' && !empty($qres['result'])) {
            return $qres['result'];
        }

        return '';
    }
}
