<?php
/*
 *  This file is part of open3A.

 *  open3A 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.

 *  open3A 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 <http://www.gnu.org/licenses/>.
 *
 *  2007 - 2020, open3A GmbH - Support@open3A.de
 */

if(!isset($argv[1]))
	die("Bitte geben Sie die E-Mail-Adresse des Steuerberaters als ersten Parameter an!\n");

if(isset($argv[2]))
	$_GET["cloud"] = $argv[2];

if(isset($argv[3]))
	$_SERVER["HTTP_HOST"] = $argv[3];

session_name("ExtConnDatev");

require_once realpath(dirname(__FILE__)."/../../system/connect.php");

register_shutdown_function('cronShutdownHandler');
function cronShutdownHandler() {
	$last_error = error_get_last();
	if ($last_error['type'] !== E_ERROR) 
		return;
	
	print_r(SysMessages::i()->getMessages());
}
$absolutePathToPhynx = realpath(dirname(__FILE__)."/../../")."/";
$e = new ExtConn($absolutePathToPhynx);

$e->loadPlugin("open3A", "Auftraege");
$e->loadPlugin("open3A", "exportDatev");
$e->loadPlugin("open3A", "Stammdaten");
$e->loadPlugin("open3A", "Kunden");
$e->loadPlugin("open3A", "Adressen");
$e->loadPlugin("open3A", "Textbausteine");
$e->loadPlugin("open3A", "Brief");
#$e->loadPlugin("open3A", "Belegdownload");
$e->loadPlugin("open3A", "Export");

$e->addClassPath($absolutePathToPhynx."specifics");
$e->addClassPath(FileStorage::getFilesDir());


$e->useDefaultMySQLData();

$e->useUser();

$D = new Datum();
$D->setToMonth1st();
$D->subMonth();

mUserdata::setUserdataS("exportDatev", $D->Y().$D->m());
mUserdata::setUserdataS("exportDatevBS", "1");

$B = new exportDatevGUI();
ob_start();
$B->getExportData("ACSVExport");
$r = ob_get_clean();

$filename = "Ausgangsbelege_".Util::CLDateParser(time()).".csv";

$tempFile = Util::getTempDir().$filename;
file_put_contents($tempFile, $r);

$S = Stammdaten::getActiveStammdaten();

$mail = new phynxMailer($argv[1], "Buchhaltungsdaten ".$S->A("firmaLang"), "Siehe Anhang");
$mail->attach($tempFile);
$mail->from($S->A("email"), $S->A("firmaLang"));
$mail->send();

$e->cleanUp();
?>