<?php
/**
 * Ce script définit la classe 'contrat'.
 *
 * @package opencimetiere
 * @version SVN : $Id: contrat.class.php 812 2018-10-21 18:25:18Z fmichon $
 */

require_once "../gen/obj/contrat.class.php";

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

    /**
     * GETTER_FORMINC - champs.
     *
     * @return array
     */
    function get_var_sql_forminc__champs() {
        return array(
            "contrat",
            "emplacement",
            "datedemande",
            "origine",
            "terme",
            "duree",
            "datevente",
            "dateterme",
            "montant",
            "monnaie",
            "valide",
            "observation",
        );
    }

    /**
     * Définition des actions disponibles sur la classe.
     *
     * @return void
     */
    function init_class_actions() {
        parent::init_class_actions();
        //
        $this->class_actions[21] = array(
            "identifier" => "view_overlay_contrat_montant",
            "view" => "view_overlay_contrat_montant",
            "permission_suffix" => "consulter",
        );
        $this->class_actions[22] = array(
            "identifier" => "valider",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => __("valider"),
                "class" => "contrat-valider-16",
                ),
            "permission_suffix" => "valider",
            "method" => "valider",
            "condition" => array(
                "exists",
                "is_not_valid",
            ),
        );
    }

    /**
     *
     * @return string
     */
    function get_default_libelle() {
        return _("id")." ".$this->getVal($this->clePrimaire)." - ".$this->getVal("origine")." du ".$this->dateDBToForm($this->getVal("datedemande"));
    }

    /**
     * CONDITION - is_not_valid.
     *
     * @return boolean
     */
    function is_not_valid() {
        if ($this->getVal("valide") === 't') {
            return false;
        }
        return true;
    }

    /**
     * TREATMENT - valider.
     *
     * @return boolean
     */
    function valider() {
        $this->begin_treatment(__METHOD__);
        //
        $valF = array("valide" => true);
        //
        $res_update = $this->f->db->autoexecute(
            sprintf('%1$s%2$s', DB_PREFIXE, $this->table),
            $valF,
            DB_AUTOQUERY_UPDATE,
            $this->getCle($this->getVal($this->clePrimaire))
        );
        $this->addToLog(
            __METHOD__."(): db->autoexecute(\"".sprintf('%1$s%2$s', DB_PREFIXE, $this->table)."\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($this->getVal($this->clePrimaire))."\");",
            VERBOSE_MODE
        );
        if ($this->f->isDatabaseError($res_update, true) !== false) {
            $this->correct = false;
            return $this->end_treatment(__METHOD__, false);
        };
        $this->addToMessage(__("Le contrat a bien été validé."));
        return $this->end_treatment(__METHOD__, true);
    }

    /**
     * Configuration du widget de formulaire autocomplete du champ 'emplacement'.
     *
     * @return array
     */
    function get_widget_config__emplacement__autocomplete() {
        return  array(
            // Surcharge visée pour l'ajout
            'obj' => "emplacement",
            // Table de l'objet
            'table' => "emplacement",
            // Permission d'ajouter
            'droit_ajout' => false,
            // Critères de recherche
            'criteres' => array(
                "'n°'||emplacement.emplacement" => __("n° de l'emplacement (ex : n°12)"),
                "emplacement.emplacement" => __("identifiant de l'emplacement (ex : 12)"),
                "emplacement.famille" => __("famille (ex : DUPONT)"),
            ),
            // Tables liées
            'jointures' => array(
            ),
            // Colonnes ID et libellé du champ
            // (si plusieurs pour le libellé alors une concaténation est faite)
            'identifiant' => "emplacement.emplacement",
            //
            'libelle' => array(
                "(emplacement.nature||' - n°'||emplacement.emplacement||' - Famille : '||emplacement.famille)",
            ),
            //
            'where' => "(nature='concession' or nature='colombarium' or nature='enfeu')",
            //
            'group_by' => array(
            ),
            //
            'link_selection' => false,
        );
    }

    /**
     * CHECK_TREATMENT - verifier.
     */
    function verifier($val = array(), &$dnu1 = null, $dnu2 = null) {
        parent::verifier($val);
        //
        if ($val["terme"] == "perpetuite"
            && $val["duree"] != 0) {
            //
            $this->correct = false;
            $this->addToMessage(_("La durée doit être égale à 0 sur un terme perpétuité."));
        } elseif($val["terme"] == "temporaire"
            && $val["duree"] <= 0) {
            //
            $this->correct = false;
            $this->addToMessage(_("La durée doit être supérieur à 0 sur un terme temporaire."));
        }
        //
        $datevente = DateTime::createFromFormat('d/m/Y', $val["datevente"]);
        $dateterme = DateTime::createFromFormat('d/m/Y', $val["dateterme"]);
        if ($val["terme"] == "temporaire"
            && $val["duree"] != 0
            && $datevente != null
            && $datevente->add(new DateInterval("P".intval($val["duree"])."Y")) != $dateterme) {
            //
            $this->correct = false;
            $this->addToMessage(_("La date de terme ne correspond pas à la date de vente + la durée."));
        }
    }

    /**
     * SETTER_FORM - setType.
     *
     * @return void
     */
    function setType(&$form, $maj) {
        parent::setType($form, $maj);
        // Affichage de l'id de la table dans tous les cas
        $form->setType('contrat', 'hiddenstatic');
        // $form->setType("dateterme", "hiddenstaticdate");
        //
        if ($this->is_in_context_of_foreign_key("emplacement", $this->getParameter("retourformulaire"))) {
            $form->setType('emplacement', 'hidden');
        } else {
            if ($maj == 0 || $maj == 1) {
                $form->setType('emplacement', 'autocomplete');
            }
            if ($maj == 3){
                $form->setType('emplacement', 'link');
            }
        }
        if ($maj == 0) {
            $form->setType('origine', 'select');
        } else {
            $form->setType('origine', 'hiddenstatic');
        }
        if ($maj == 0 || $maj == 1) {
            $form->setType('montant', 'contrat_montant');
            $form->setType('monnaie', 'select');
            $form->setType('terme', 'select');
        } else {
            $form->setType('terme', 'selectstatic');
            $form->setType('monnaie', 'selectstatic');
        }
        // Pour les actions appelée en POST en Ajax, il est nécessaire de
        // qualifier le type de chaque champs (Si le champ n'est pas défini un
        // PHP Notice:  Undefined index dans core/om_formulaire.class.php est
        // levé). On sélectionne donc les actions de portlet de type
        // action-direct ou assimilé et les actions spécifiques avec le même
        // comportement.
        if ($this->get_action_param($maj, "portlet_type") == "action-direct"
            || $this->get_action_param($maj, "portlet_type") == "action-direct-with-confirmation") {
            //
            foreach ($this->champs as $key => $value) {
                $form->setType($value, 'hidden');
            }
            // $form->setType($this->clePrimaire, "hiddenstatic");
        }
    }

    /**
     * SETTER_FORM - setLib.
     *
     * @return void
     */
    function setLib(&$form, $maj) {
        parent::setLib($form, $maj);
        //
        $form->setLib($this->clePrimaire, __("id"));
        $form->setLib("datedemande", __("date de demande"));
    }

    /**
     * SETTER_FORM - setSelect.
     *
     * @return void
     */
    function setSelect(&$form, $maj, &$dnu1 = null, $dnu2 = null) {
        parent::setSelect($form, $maj);
        // MODE AJOUTER & MODE MODIFIER
        if ($maj == 0 || $maj == 1) {
            // AUTOCOMPLETE emplacement
            $form->setSelect(
                "emplacement",
                $this->get_widget_config__emplacement__autocomplete()
            );
        } 
	// MODE CONSULTER
	if ($maj == 3) {
            $inst_emplacement = $this->f->get_inst__om_dbform(array(
                "obj" => "emplacement",
                "idx" => $form->val['emplacement'],
            ));

            $params = array();
            $params['obj'] = $inst_emplacement->getVal('nature');
            $params['libelle'] = $inst_emplacement->getVal('nature').' - n°'.$form->val['emplacement'].' - Famille : '.$inst_emplacement->getval('famille');
            $params['title'] = "Consulter l'emplacement";
            $params['idx'] = $form->val['emplacement'];
            $form->setSelect("emplacement", $params);
        }
        // MODE ALL
        // origine
        $contenu = array();
        $contenu [0] = array ("", "achat", "renouvellement", "transformation");
        $contenu [1] = array (__("Choisir origine"), __("Achat"), __("Renouvellement"), __("Transformation"));
        if ($maj == 999) {
            $contenu[1][0] = __("Tous");
        }
        $form->setSelect("origine", $contenu);
        // Terme
        $contenu = array ();
        $contenu[0]=array('',"perpetuite",'temporaire');
        $contenu[1]=array('',__("perpetuite"),__("temporaire"));
        if ($maj == 999) {
            $contenu[1][0] = __("Tous");
        }
        $form->setSelect("terme", $contenu);
        // monnaie
        $contenu = array ();
        $contenu[0]=array("euro", "franc", "ancien_franc");
        $contenu[1]=array("Euros", "Francs", "Anciens Francs");
        $form->setSelect("monnaie", $contenu);
    }

    /**
     * SETTER_FORM - set_form_default_values (setVal).
     *
     * @return void
     */
    function set_form_default_values(&$form, $maj, $validation) {
        parent::set_form_default_values($form, $maj, $validation);
        //
        if ($validation == 0 && $maj == 0) {
            $form->setVal($this->clePrimaire, "[...]");

            $inst_emplacement = $this->f->get_inst__om_dbform(array(
                "obj" => "emplacement",
                "idx" => $this->getParameter("idxformulaire"),
            ));
            $form->setVal("datevente", $inst_emplacement->getVal("dateterme"));
        }
    }

    /**
     * SETTER_FORM - setMax.
     *
     * @return void
     */
    function setMax(&$form, $maj) {
        parent::setMax($form, $maj);
        //
        $form->setMax("montant", 12);
    }

    /**
     * SETTER_FORM - setLayout.
     *
     * @return void
     */
    function setLayout(&$form, $maj) {
        parent::setLayout($form, $maj);
        //
        $bloc_global_width_full = "span12";
        $bloc_global_width_half = "span6";
        //// CONTAINER GLOBAL - START
        $this->form->setBloc("contrat", "D", "", "contrat-form form-action-".$maj);
        //// LIGNE ID - START
        $this->form->setBloc("contrat", "D", "", "row-fluid");
            //// BLOC ID - START
            $this->form->setBloc("contrat", "D", "", $bloc_global_width_full." emplacement-bloc emplacement-bloc-identification ");
                //// BLOC ID - START
                $this->form->setBloc("contrat", "D", "", "span12");
                $this->form->setBloc("emplacement", "F");
                //// BLOC ID - END
            $this->form->setBloc("emplacement", "F");
            //// BLOC ID - END
        $this->form->setBloc("emplacement", "F");
        //// LIGNE ID - END
        //// CONTAINER GLOBAL - END
        $this->form->setBloc("observation", "F");
    }

    /**
     * MERGE_FIELDS - merge_fields_to_avoid_obj.
     * @var array
     */
    var $merge_fields_to_avoid_obj = array(
        "emplacement",
    );

    /**
     * MERGE_FIELDS - get_labels_merge_fields.
     *
     * @return array
     */
    function get_labels_merge_fields() {
        $labels = parent::get_labels_merge_fields();
        //
        $date_fields_to_format = array("datedemande", "datevente", "dateterme", );
        foreach ($date_fields_to_format as $date_field_to_format) {
            $labels[$this->table][$this->table.".".$date_field_to_format."_format_jj_mois_aaaa"] = $labels[$this->table][$this->table.".".$date_field_to_format]." (Format : 14 janvier 1978)";
        }
        //
        $labels["contrat"]["contrat.duree_lettre"] = __("durée en lettres");
        $labels["contrat"]["contrat.annee"] = __("année de vente");
        $labels["contrat"]["contrat.origine_code"] = __("origine code (A R ou T)");
        $labels["contrat"]["contrat.montant_lettre"] = __("montant en lettres");
        $labels["contrat"]["contrat.montant_part_communale"] = __("montant de la part communale");
        $labels["contrat"]["contrat.montant_autre_part"] = __("montant de l'autre part");
        $labels["contrat"]["contrat.monnaie_sigle"] = __("monnaie sigle (€ ou F)");
        //
        return $labels;
    }

    /**
     * MERGE_FIELDS - get_values_merge_fields.
     *
     * @return array
     */
    function get_values_merge_fields() {
        $values = parent::get_values_merge_fields();
        //
        $date_fields_to_format = array("datedemande", "datevente", "dateterme", );
        foreach ($date_fields_to_format as $date_field_to_format) {
            $values[$this->table.".".$date_field_to_format."_format_jj_mois_aaaa"] = '';
            $date_value_as_string = $this->getVal($date_field_to_format);
            if (!empty($date_value_as_string)
                && preg_match('|^[0-9]{4}-[0-9]{2}-[0-9]{2}$|', $date_value_as_string)) {
                //
                $date_value_as_object = DateTime::createFromFormat('Y-m-d', $date_value_as_string);
                $values[$this->table.".".$date_field_to_format."_format_jj_mois_aaaa"] = strftime('%d %B %Y', $date_value_as_object->getTimestamp());
            }
        }
        //
        function decompose($somme) {
            $pos = array("","");
            $virgule = 0;
            for($cp=0;$cp<strlen($somme);$cp++)
            {
                $lettre = substr($somme,$cp,1);
                if($lettre=="."){ $virgule = 1; $lettre=""; }
                $pos[$virgule] .= $lettre;
            }
            return $pos;
        }
        require_once "../app/php/misc/chiffreenlettre.class.php";
        $lettre = new ChiffreEnLettre();
        //
        $lettre->init();
        $values["contrat.duree_lettre"] = trim(strtolower($lettre->Conversion($this->getVal("duree"))));
        //
        $values["contrat.montant_part_communale"] = "";
        $values["contrat.montant_lettre"] = "";
        $values["contrat.montant_autre_part"] = "";
        if ($this->getVal("montant") != "") {
            $lettre->init();
            $somme = decompose($this->getVal("montant"));
            $values["contrat.montant_lettre"] .= strtolower($lettre->Conversion($somme[0]));
            if ($somme[0] > 1) {
                if ($this->getVal("monnaie") == "euro" || $this->getVal("monnaie") == "franc") {
                    $values["contrat.montant_lettre"] .= " ".$this->getVal("monnaie")."s";
                } elseif ($this->getVal("monnaie") == "ancien_franc") {
                    $values["contrat.montant_lettre"] .= " anciens francs";
                }
            } else {
                if ($this->getVal("monnaie") == "euro" || $this->getVal("monnaie") == "franc") {
                    $values["contrat.montant_lettre"] .= " ".$this->getVal("monnaie");
                } elseif ($this->getVal("monnaie") == "ancien_franc") {
                    $values["contrat.montant_lettre"] .= " ancien franc";
                }
            }
            $lettre->init();
            if (isset($somme[1]) && $somme[1] > 0) {
                $values["contrat.montant_lettre"] .= " ".strtolower($lettre->Conversion($somme[1]));
                if ($somme[1] > 1) {
                    $values["contrat.montant_lettre"] .= " centimes";
                } else {
                    $values["contrat.montant_lettre"] .= " centime";
                }
            }
            //
            $values["contrat.montant"] = str_replace(".", ",", $this->getVal("montant"));
            $taux_part_communale = floatval($this->f->getParameter("contrat_part_communale"));
            if ($taux_part_communale <= 0 || $taux_part_communale > 1) {
                $taux_part_communale = 1;
            }
            $part_communale = round($this->getVal("montant") * $taux_part_communale, 2);
            $values["contrat.montant_part_communale"] = str_replace(".", ",", $part_communale);
            $autre_part = $this->getVal("montant") - $part_communale;
            $values["contrat.montant_autre_part"] = str_replace(".", ",", $autre_part);
        }
        //
        $values["contrat.monnaie_sigle"] = "";
        if ($this->getVal("monnaie") == "euro") {
            $values["contrat.monnaie_sigle"] = "€";
        } elseif ($this->getVal("monnaie") == "franc" || $this->getVal("monnaie") == "ancien_franc") {
            $values["contrat.monnaie_sigle"] = "F";
        } else {
            $values["contrat.monnaie_sigle"] = "";
        }
        //
        $values["contrat.annee"] = substr($this->getVal("datevente"), 0, 4);
        //
        $values["contrat.origine_code"] = "";
        switch($this->getVal("origine")) {
            case "achat": $values["contrat.origine_code"] = "A"; break;
            case "renouvellement": $values["contrat.origine_code"] = "R"; break;
            case "transformation": $values["contrat.origine_code"] = "T"; break;
        }
        $values["contrat.observation"] = str_replace("\n", "<br/>", $values["contrat.observation"]);
        //
        return $values;
    }

    /**
     * TRIGGER - triggerajouterapres.
     *
     * @return boolean
     */
    function triggerajouterapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
        $inst_emplacement = $this->f->get_inst__om_dbform(array(
            "obj" => "emplacement",
            "idx" => $this->valF["emplacement"],
        ));
        $ret = $inst_emplacement->update_contrat_info_from_contrats();
        if ($ret !== true) {
            $this->addToMessage("Erreur lors de la mise à jour des informations de l'emplacement.");
            return $this->end_treatment(__METHOD__, false);
        }
        return $this->end_treatment(__METHOD__, true);
    }

    /**
     * TRIGGER - triggermodifierapres.
     *
     * @return boolean
     */
    function triggermodifierapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
        $inst_emplacement = $this->f->get_inst__om_dbform(array(
            "obj" => "emplacement",
            "idx" => $this->getVal("emplacement"),
        ));
        $ret = $inst_emplacement->update_contrat_info_from_contrats();
        if ($ret !== true) {
            $this->addToMessage("Erreur lors de la mise à jour des informations de l'emplacement.");
            return $this->end_treatment(__METHOD__, false);
        }
        return $this->end_treatment(__METHOD__, true);
    }

    /**
     * TRIGGER - triggersupprimerapres.
     *
     * @return boolean
     */
    function triggersupprimerapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
        $inst_emplacement = $this->f->get_inst__om_dbform(array(
            "obj" => "emplacement",
            "idx" => $this->getVal("emplacement"),
        ));
        $ret = $inst_emplacement->update_contrat_info_from_contrats();
        if ($ret !== true) {
            $this->addToMessage("Erreur lors de la mise à jour des informations de l'emplacement.");
            return $this->end_treatment(__METHOD__, false);
        }
        return $this->end_treatment(__METHOD__, true);
    }

    /**
     * Calcule la différence en mois entre deux dates.
     *
     * @param string $dateDebut Date au format d/m/Y.
     * @param string $dateFin Date au format d/m/Y.
     *
     * @return int
     */
    function diffMois($dateDebut, $dateFin) {
        $dtDeb = DateTime::createFromFormat('d/m/Y', $dateDebut);
        $dtFin = DateTime::createFromFormat('d/m/Y', $dateFin);
        $interval = $dtDeb->diff($dtFin);
        $nbmonth= $interval->format('%m');
        $nbyear = $interval->format('%y');
        return 12 * $nbyear + $nbmonth;
    }

    /**
     * VIEW - view_overlay_contrat_montant.
     *
     * @return void
     */
    function view_overlay_contrat_montant() {
        //
        $this->checkAccessibility();
        //
        $this->f->displayStartContent();
        //
        $origine = null;
        $origine_initiale = null;
        if (isset($_GET["origine"]) === true
            and in_array($_GET["origine"], array("achat", "renouvellement", "transformation")) === true) {
            $origine = $_GET["origine"];
            $origine_initiale = $_GET["origine"];
        }
        //
        $datevente = $this->f->formatDate($_GET["datevente"]);
        if ($datevente == false) {
            $this->f->displayMessage("error", "Recherche de tarif impossible sans date de vente.");
            $this->f->displayEndContent();
            return;
        }
        //
        if ($origine == "transformation") {
            $query = sprintf(
                'SELECT *
                FROM %1$scontrat
                WHERE
                    emplacement=%2$s
                    AND contrat<>%3$s
                    AND datevente<=\'%4$s\'
                    AND origine<>\'transformation\'
                ORDER BY datevente DESC LIMIt 1
                ',
                DB_PREFIXE,
                intval($_GET["emplacement"]),
                intval($_GET["contrat"]),
                $datevente
            );
            $res = $this->f->db->query($query);
            $this->addToLog(__METHOD__."(): db->query(\"".$query."\");", VERBOSE_MODE);
            $this->f->isDatabaseError($res);
            $contrat_reference = array();
            while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
                $contrat_reference[] = $row;
            }
            if (count($contrat_reference) == 0) {
                $this->f->displayMessage("error", "Aucun contrat (achat ou renouvellement) à transformer.");
                $this->f->displayEndContent();
                return;
            }
            $origine = $contrat_reference[0]["origine"];
        }
        //
        $inst_emplacement = $this->f->get_inst__om_dbform(array(
            "obj" => "emplacement",
            "idx" => intval($_GET["emplacement"]),
        ));
        $query = sprintf(
            'SELECT * 
            FROM %1$starif 
            WHERE
                nature=\'%2$s\'
                AND origine=\'%3$s\'
                AND terme=\'%4$s\'
                AND duree=%5$s
                AND annee=%6$s
                AND (sepulture_type=%7$s OR sepulture_type IS NULL)
            ORDER BY sepulture_type NULLS LAST
            LIMIT 1
            ',
            DB_PREFIXE,
            $inst_emplacement->getVal("nature"),
            $origine,
            $_GET["terme"],
            intval($_GET["duree"]),
            intval(substr($_GET["datevente"], 6, 4)),
            intval($inst_emplacement->getVal("sepulturetype"))
        );
        $res = $this->f->db->query($query);
        $this->addToLog(__METHOD__."(): db->query(\"".$query."\");", VERBOSE_MODE);
        $this->f->isDatabaseError($res);
        $result = array();
        while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $result = $row;
        }
        //
        if (count($result) == 0) {
            $this->f->displayMessage("error", "Aucun tarif ne correspond.");
            $this->f->displayEndContent();
            return;
        }
        //
        if ($origine_initiale === "transformation") {
            $datevente_show = $this->f->formatDate($contrat_reference[0]["datevente"], true);
            $datedemande_show = $this->f->formatDate($_GET["datedemande"], true);
            $prix_paye = $contrat_reference[0]["montant"];
            $ancienne_duree_en_mois = (intval($contrat_reference[0]["duree"])*12);
            $nouvelle_duree_en_mois = (intval($_GET["duree"])*12);
            $duree_payee_ecoulee_en_mois = $this->diffMois(
                $this->f->formatDate($contrat_reference[0]["datevente"]),
                $this->f->formatDate($_GET["datedemande"])
            );
            $duree_restante = $ancienne_duree_en_mois - $duree_payee_ecoulee_en_mois;
            $result_reste_a_payer = number_format(($prix_paye * $duree_restante) / $ancienne_duree_en_mois, 2);
            printf(
                '<b>Détail de la transformation</b><br/>
                <p id="info_contrat">Contrat transformé : %s du %s<\p><br/>
                <table>
                <tr><td>Ancienne date</td><td id="ancienne_date">%s (année %s / mois %s)</td></tr>
                <tr><td>Nouvelle date</td><td id="new_date">%s (année %s / mois %s)</td></tr>
                <tr><td>Durée initiale</td><td id="duree_initiale">%s mois (%s ans)</td></tr>
                <tr><td>Nombre de mois écoulés</td><td id="mois_ecoule">%s mois</td></tr>
                <tr><td>Nouvelle durée</td><td id="new_duree">%s mois (%s ans)</td></tr>
                <tr><td>Tarif payé initialement</td><td id="tarif_initial">%s %s(s)</td></tr>
                <tr><td>Nouveau tarif</td><td id="new_tarif">%s %s(s)</td></tr>
                <tr><td>Somme déjà payée</td><td id="already_paid">%s %s(s)</td></tr>
                </table>
                ',
                $contrat_reference[0]["origine"],
                $this->f->formatDate($contrat_reference[0]["datevente"], true),
                $datevente_show,
                intval(substr($_GET["datevente"], 6, 4)),
                intval(substr($_GET["datevente"], 3, 2)),
                $datedemande_show,
                intval(substr($_GET["datedemande"], 6, 4)),
                intval(substr($_GET["datedemande"], 3, 2)),
                $ancienne_duree_en_mois,
                intval($contrat_reference[0]["duree"]),
                $duree_payee_ecoulee_en_mois,
                $nouvelle_duree_en_mois,
                intval($_GET["duree"]),
                $prix_paye,
                $contrat_reference[0]["monnaie"],
                $result["montant"],
                $result["monnaie"],
                $result_reste_a_payer,
                $result["monnaie"]
            );
            $montant = number_format($result["montant"] - $result_reste_a_payer, 2);
            $monnaie = $result["monnaie"];
            echo "<p id=\"new_montant\"> Nouveau montant => ".$montant." ".$monnaie."(s)</p>";
        } else {
            $montant = $result["montant"];
            $monnaie = $result["monnaie"];
            echo "<p id=\"new_montant\">".$montant." ".$monnaie."(s)</p>";
        }
        echo "\n<p class=\"linkjsclosewindow\">";
        echo "<a class=\"linkjsclosewindow\" href=\"#\" ";
        echo "onclick=\"recup();\">";
        echo __("Valider");
        echo "</a>";
        echo "</p>\n";
        printf(
            '
        <script type="text/javascript">
        function recup() {
            $("#montant").val("%s");
            $("#monnaie").val("%s");
            $("#overlay-contrat-montant").dialog("close").remove();
        }
        </script>
            ',
            $montant,
            $monnaie
        );
        $this->f->displayEndContent();
    }
}
