<?php

namespace MONTREAL;

use \Dcp\AttributeIdentifiers\MONTREAL_DOSSIER as MONTREAL_DOSSIER_Attributes;
use Dcp\Ui\RenderConfigManager;

Class MONTREAL_DOSSIER extends \Dcp\Family\MONTREAL_BASE implements
    \Dcp\Ui\IRenderConfigAccess
{


    protected static $_sequence_name = "dossier_sequence";

    public function postCreated()
    {
        $err = parent::postCreated();
        if ($this->initid == $this->id) {
            $err .= $this->setChrono();
        }
        return $err;
    }

    public function postStore()
    {
        $err =  parent::postStore();
        $this->synchronizeWithFinancier(true);
        return $err;
    }


    public function changeToRelecture() {
        error_log("try to change to relecture");
        if ($this->getATag("redactionDone") && $this->getATag("financeDone")) {
            $this->setState('mdwfl__e3', "", true, false);
            //$this->modify(true, "state", true);
        }
    }

    public function changeToValidated() {
        $valideur = $this->getAttributeValue(MONTREAL_DOSSIER_Attributes::mtd_valideur);
        foreach($valideur as $currentValideur) {
            error_log($currentValideur);
            if (!$this->getATag("validated" . $currentValideur)) {

                return;
            }
        }
        $this->setState('mdwfl__e6', "", true, false);
    }

    /**
     * @param string $mode
     * @param \Doc   $document
     *
     * @return \Dcp\Ui\IRenderConfig
     */
    public function getRenderConfig($mode, \Doc $document)
    {
        switch ($mode) {
        case RenderConfigManager::CreateMode:
        case RenderConfigManager::EditMode:
            return new dossier_edit($this);
        case RenderConfigManager::ViewMode:
            return new dossier_view($this);
        }

        return null;
    }

    public function getCustomTitle()
    {
        if (!$this->initid) {
            return ___("Created", "MONTREAL");
        }
        return "DOSSIER : " . str_pad(
            $this->getAttributeValue(
                MONTREAL_DOSSIER_Attributes::mtd_num_dossier
            ), 3, "0", STR_PAD_LEFT
        );
    }

    public function synchronizeWithFinancier($noStore = false, $noFinancierStore = false)
    {
        $searchDoc = new \SearchDoc("", "MONTREAL_DOSSIER_FINANCIER");
        $searchDoc->overrideViewControl();
        $searchDoc->setObjectReturn(true);
        $searchDoc->addFilter(
            "mdf_linked_dossier = '%d'", $this->initid
        );
        $searchDoc->slice = 1;
        $searchDoc->search();
        $dossierFinancier = $searchDoc->getNextDoc();

        if (!$dossierFinancier) {
            return;
        }

        error_log("FOUND");

        $this->disableEditControl();
        //get value from financier
        $this->setValue("mtd_financier",
            $dossierFinancier->getAttributeValue("mtd_financier")
        );
        $this->setValue(
            "mtd_finance_organisme",
            $dossierFinancier->getAttributeValue("mtd_finance_organisme")
        );
        $this->setValue(
            "mtd_finance_titre",
            $dossierFinancier->getAttributeValue("mtd_finance_titre")
        );
        $this->setValue(
            "mtd_finance_montant",
            $dossierFinancier->getAttributeValue("mtd_finance_montant")
        );
        $this->setValue(
            "mtd_finance_soutient",
            $dossierFinancier->getAttributeValue("mtd_finance_soutient")
        );
        $this->setValue(
            "mtd_finance_simon",
            $dossierFinancier->getAttributeValue("mtd_finance_simon")
        );
        if (!$noStore) {
            error_log("UPDATE DOSSIER");
            error_log($this->modify(true, true));
        }
        $this->enableEditControl();
        //set values to dossier financier
        $dossierFinancier->disableEditControl();
        $dossierFinancier->transfertValuesFrom($this);
        if (!$noFinancierStore) {
            error_log("UPDATE FINANCIER");
            $dossierFinancier->computeDProfil();
            $dossierFinancier->modify(true, "", true);

        }
        $dossierFinancier->enableEditControl();
    }

    public function checkConseilDate($date)
    {
        if ($this->state === "mdwfl__e1") {
            return $this->isFutureDate($date);
        }
    }

    public function generateODT() {
        $path = $this->viewDoc("MONTREAL:templateDossier.odt:B");
        error_log($path);
        $info = null;
        require_once "FDL/Lib.Vault.php";
        convertFile($path, 'pdfa', $path.".pdf", $info);
        $this->setFile("mtd_ordre_jour", $path.".pdf", "ordre_jour.pdf");
        $this->store();
    }


    protected function setChrono()
    {
        $err = "";
        $num = $this->getNextSequenceNumber();
        $this->disableEditControl();
        $this->setAttributeValue(
            MONTREAL_DOSSIER_Attributes::mtd_num_dossier, $num
        );
        $err .= $this->store();
        $this->enableEditControl();
        return $err;
    }

    /**
     * Get the next Sequence Number
     *
     * @return string or boolean return false if no sequence
     */
    protected function getNextSequenceNumber()
    {
        $number = false;
        $sequence = static::$_sequence_name;
        if ($sequence) {
            $res = pg_exec(
                $this->init_dbid(),
                "select nextval ('" . static::$_sequence_name . "');"
            );
            $arr = pg_fetch_array($res, 0);
            $number = sprintf("%03d", $arr[0]);
        }
        return $number;
    }

    /**
     * setSqlInit
     *
     */
    protected function setSQLInit()
    {
        $sequence = static::$_sequence_name;
        if ($sequence) {
            $this->sqlinit = "create sequence $sequence start 1;";
        }
    }

}