<?php
/* Copyright (C) 2010-2011 	Juanjo Menent		<jmenent@2byte.es>
 * Copyright (C) 2010		Laurent Destailleur	<eldy@users.sourceforge.net>
 * Copyright (C) 2011      	Regis Houssin		<regis.houssin@inodbox.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 * or see https://www.gnu.org/
 */

/**
 *	\file       custom/lib/prelevementpf.lib.php
 *	\brief      Ensemble de fonctions de base pour le module prelevementpf
 *	\ingroup    propal
 */


/**
 * Prepare array with list of tabs
 *
 * @param   BonPrelevementPF	$object		Object related to tabs
 * @return  array				Array of tabs to show
 */
function prelevementpf_prepare_head(BonPrelevementPF $object)
{
	global $langs, $conf, $user;
	$langs->load("withdrawals");

	$h = 0;
	$head = array();

	$titleoftab = "WithdrawalsReceipts";
	if ($object->type == 'bank-transfer') {
		$titleoftab = "BankTransferReceipts";
	}

	$head[$h][0] = dol_buildpath('/prelevementpf/card.php',1).'?id='.$object->id;
	$head[$h][1] = $langs->trans($titleoftab);
	$head[$h][2] = 'prelevementpf';
	$h++;

	$head[$h][0] = dol_buildpath('/prelevementpf/factures.php',1).'?id='.$object->id;
	$head[$h][1] = $langs->trans("Bills");
	$head[$h][2] = 'invoices';
	$h++;

	$head[$h][0] = dol_buildpath('/prelevementpf/fiche-rejet.php',1).'?id='.$object->id;
	$head[$h][1] = $langs->trans("Rejects");
	$head[$h][2] = 'rejects';
	$h++;

	$head[$h][0] = dol_buildpath('/prelevementpf/fiche-stat.php',1).'?id='.$object->id;
	$head[$h][1] = $langs->trans("Statistics");
	$head[$h][2] = 'statistics';
	$h++;

	// Show more tabs from modules
	// Entries must be declared in modules descriptor with line
	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
	// $this->tabs = array('entity:-tabname);   												to remove a tab
	complete_head_from_modules($conf, $langs, $object, $head, $h, 'prelevementpf');

	complete_head_from_modules($conf, $langs, $object, $head, $h, 'prelevementpf', 'remove');

	return $head;
}

/**
 *	Check need data to create standigns orders receipt file
 *
 *	@return    	int		-1 if ko 0 if ok
 */
function prelevementpf_check_config()
{
	global $conf;
	$t_prelevementbank = prelevementpf_getprelevementbank();

	// chaque banque est associee a un compte bancaire
	foreach( $t_prelevementbank as $pb ){
		if ( $pb->fk_bank_account<=0  ) return -1;
	}

	// numero d emetteur
	if( !$conf->global->PRELEVEMENTPF_NNE   ) return -1;


	return 0;
}


/**
 * Return head table for admin tabs screen
 *
 * @return array head table of tabs
 */
function prelevementpf_admin_prepare_head()
{
	global $langs, $conf;

	$langs->load("prelevementpf@prelevementpf");

	$h = 0;
	$head = array();

	$head [$h] [0] = dol_buildpath("/prelevementpf/admin/setup.php", 1);
	$head [$h] [1] = $langs->trans("Settings");
	$head [$h] [2] = 'settings';
	$h++;

	complete_head_from_modules($conf, $langs, $object, $head, $h, 'prelevementpf');

	return $head;
}

/**
 * Recupere les banques
 */
function prelevementpf_getbank(){
	global $db;
	$t_bank = array();

	$sql = "SELECT * "
		."FROM ".MAIN_DB_PREFIX."prelevementpf_bank "
		."ORDER BY name";
	$result = $db->query($sql);
	if ($result)
	{
		$num = $db->num_rows($result);
		$i = 0;
		while ($i < $num)
		{
			$obj = $db->fetch_object($result);
			$t_bank[ $obj->rowid ] = $obj;
			$i++;
		}
	}

	return $t_bank;
}

/**
 * Recupere la configuration des fichiers de prélèvement
 */
function prelevementpf_getprelevementbank(){
	global $db;
	$t_bank = array();

	$sql = "SELECT pb.rowid, pb.libelle_compte, pb.code_banque AS banque_prelevement, pb.filename_ap, pb.file_prelevement, pb.file_rejet, pb.fk_bank_account"
		." , b.code AS bank_code, b.name AS bank_name, b.shortname AS bank_shortname"
		." , ba.ref AS account_ref, ba.label AS account_label, ba.bank AS account_bank"
		." , ba.code_banque AS code_banque, ba.code_guichet AS code_guichet, ba.number AS account_number, ba.cle_rib AS cle_rib"
		." FROM ".MAIN_DB_PREFIX."prelevementpf_prelevementbank AS pb"
		." LEFT JOIN ".MAIN_DB_PREFIX."prelevementpf_bank AS b ON pb.rowid=b.fk_prelevementbank"
		." LEFT JOIN ".MAIN_DB_PREFIX."bank_account AS ba ON ba.rowid=pb.fk_bank_account";
	$result = $db->query($sql);
	if ($result)
	{
		$num = $db->num_rows($result);
		$i = 0;
		while ($i < $num)
		{
			$row = $db->fetch_object($result);

			$prelevementbank = (object) array(
				'code' => $row->bank_code,
				'name' => $row->bank_name,
				'shortname' => $row->bank_shortname,
			);
			unset($row->bank_code, $row->bank_name, $row->bank_shortname);

			$account_number = str_replace(' ', '', $row->account_number);
			if(preg_match("/^(\d{5})(\d{5})(\d{11})(\d{2})$/", $account_number, $t_match)){
				$row->code_banque = $t_match[1];
				$row->code_guichet = $t_match[2];
				$row->account_number = $t_match[3];
				$row->cle_rib = $t_match[4];
			}
			
			if( !isset($t_bank[ $row->rowid ]) ){
				$t_bank[ $row->rowid ] = $row;
				$t_bank[ $row->rowid ]->prelevementbank = array();
			}
			$t_bank[ $row->rowid ]->prelevementbank[ $prelevementbank->code ] = $prelevementbank;
			$i++;
		}
	}

	return $t_bank;
}

/**
 * Saisie le compte bancaire configure
 */
function prelevementpf_set_bank_account($fk_prelevementbank, $fk_bank_account){
	global $db;

	$sql = "UPDATE ".MAIN_DB_PREFIX."prelevementpf_prelevementbank"
		." SET fk_bank_account=".$fk_bank_account.""
		." WHERE rowid=".$fk_prelevementbank.";";
		
	$result = $db->query($sql);

}


/**
 * Verifie le compte bancaire du client
 */
function prelevementpf_checkBanForAccount($account){
	if (empty($account->number))
		$account->number = $account->num_compte;
	if (empty($account->cle))
		$account->cle = $account->cle_rib;
	
	$coef = array(62, 34, 3);
	// Concatenation des differents codes.
	$rib = strtolower(trim($account->code_banque).trim($account->code_guichet).trim($account->number).trim($account->cle));
	$rib = str_replace(' ','',$rib);

	$t_rib = prelevementpf_parseRIB($rib);
	// On remplace les eventuelles lettres par des chiffres.
	//$rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz","12345678912345678912345678");	//Ne marche pas
	$rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz", "12345678912345678923456789");
	// Separation du rib en 3 groupes de 7 + 1 groupe de 2.
	// Multiplication de chaque groupe par les coef du tableau
	
	for ($i = 0, $s = 0; $i < 3; $i++) {
		$code = substr($rib, 7 * $i, 7);
		$s += (0 + (int) $code) * $coef[$i];
	}
	// Soustraction du modulo 97 de $s a 97 pour obtenir la cle
	$cle_rib = 97 - ($s % 97);

	if ($cle_rib == $t_rib['cle_rib']) {
		return true;
	}
	return false;
}

/**
 * Extrait du RIB le code banque, code guichet, numero de compte et cle RIB
 */
function prelevementpf_parseRIB($rib){
	$t_rib = [];

	$rib = str_replace(' ','',$rib);
	if(preg_match("/^(\d{5})(\d{5})(\d{11})(\d{2})$/", $rib, $t_match)){
		$t_rib['code_banque'] = $t_match[1];
		$t_rib['code_guichet'] = $t_match[2];
		$t_rib['account_number'] = $t_match[3];
		$t_rib['cle_rib'] = $t_match[4];
	}

	return $t_rib;
}