<?php

/**
 * 	\file       htdocs/core/modules/facture/mod_facture_simplex_fisk.php
 * 	\ingroup    facture
 * 	\brief      File containing class for numbering module Simplex
 */
require_once(DOL_DOCUMENT_ROOT . "/core/modules/facture/modules_facture.php");

/** 	    \class      mod_facture_simplex_fisk
 *          \brief      Classe du modele de numerotation de reference de facture Simplex
 */
class mod_facture_simplex_fisk extends ModeleNumRefFactures {

    var $version = 'dolibarr';  // 'development', 'experimental', 'dolibarr'
    var $prefixinvoice = '';
    var $prefixcreditnote = '';
    var $error = '';
    var $nom = "Simplex Fisk";
    /**
     *  Renvoi la description du modele de numerotation
     *
     *  @return     string      Texte descripif
     */
    function info() {
        global $langs;
        $langs->load("bills");
        return $langs->trans('SimplexFiskNumRefModelDesc', $this->prefixinvoice);
    }

    /**
     *  Renvoi un exemple de numerotation
     *
     *  @return     string      Example
     */
    function getExample() {
        
        return $this->prefixinvoice . '1-1-1';
    }

    /**
     *  Test si les numeros deja en vigueur dans la base ne provoquent pas de
     *  de conflits qui empechera cette numerotation de fonctionner.
     *
     *  @return     boolean     false si conflit, true si ok
     */
    function canBeActivated() {
        global $langs, $conf;
      
        $fayymm = '';
        $max = '';

        $posindice = 8;
        $sql = "SELECT MAX(SUBSTRING(facnumber FROM " . $posindice . ")) as max"; // This is standard SQL
        $sql.= " FROM " . MAIN_DB_PREFIX . "facture";
        $sql.= " WHERE facnumber LIKE '" . $this->prefixinvoice . "_-%'";
        $sql.= " AND entity = " . $conf->entity;

        $resql = $db->query($sql);
        if ($resql) {
            $row = $db->fetch_row($resql);
            if ($row) {
                $fayymm = substr($row[0], 0, 6);
                $max = $row[0];
            }
        }
        if ($fayymm || preg_match('/' . $this->prefixinvoice . '[0-9][0-9][0-9][0-9]/i', $fayymm)) {
            return true;
        } else {
            $langs->load("errors");
            $this->error = $langs->trans('ErrorNumRefModel', $max);
            return false;
        }        
    }

    /**
     * Return next value not used or last value used
     *
     * @param	Societe		$objsoc		Object third party
     * @param   Facture		$facture	Object invoice
     * @param   string		$mode          'next' for next value or 'last' for last value
     * @return  string       			Value
     */
    function getNextValue($objsoc,$facture) {
        global $db, $conf;

        $PoslovnaJedinica = '1';
        $ProdajnoMjesto = '1';
        
        if ($facture->type == 2)
            $prefix = $this->prefixcreditnote;
        else
            $prefix = $this->prefixinvoice;

        // First aplication gets max value
        $sql = "SELECT facnumber as facnumber FROM " . MAIN_DB_PREFIX . "facture";
        $sql.= " WHERE facnumber LIKE '" . $prefix . "%'";
        $sql.= " AND entity = " . $conf->entity;
        $sql.= " AND date_valid >= '".date('Y')."-1-1'";

        $result = array();
        $keywords = array();
        $LastElement = '';

        $resql = $db->query($sql);

        if ($resql) {
            $num = $db->num_rows($resql);
            $i = 0;
            while ($i < $num) {
                $found = 1;
                $obj = $db->fetch_object($resql);
                $result[] = $obj->facnumber;
                $i++;
            }
        } else {
            dol_syslog("mod_facture_simplex_fisk::getNextValue sql=" . $sql, LOG_ERR);
            return -1;
        }        
        natsort($result);
        $LastElement = end($result);
        $keywords=explode('-',$LastElement);
        $max = intval($keywords[0]);
        $num = sprintf("%s", $max + 1);

        dol_syslog("mod_facture_simplex_fisk::getNextValue return " . $prefix . $num . "-" . $PoslovnaJedinica . "-" . $ProdajnoMjesto);
        return $num . "-" . $PoslovnaJedinica . "-" . $ProdajnoMjesto." (".date('Y').")";
    }

    /**
     * Return next free value
     *
     * @param	Societe		$objsoc     	Object third party
     * @param	string		$objforref	Object for number to search
     * @param   string		$mode       	'next' for next value or 'last' for last value
     * @return  string      			Next free value
     */
    function getNumRef($objsoc, $objforref) {
        return $this->getNextValue($objsoc, $objforref);
    }

}

?>
