<?php
class NsuControllerHelper{
    const EMAIL_TEMPLATE = 'invoiceemail';
	const GLOBAL_CONF_SEND_TO_EMAIL = 'BBUS_INVOICE_PRINTING_ALERT_EMAIL';
	
	const GLOBAL_CONF_EMAIL_FROM = 'GLOBAL_CONF_EMAIL_FROM';
	const INVOICE_SUBJECT = 'INVOICE_SUBJECT';
	const INVOICE_DESCRIPTION = 'INVOICE_DESCRIPTION';

    public function getObject($sql){
        global $db;
        $array = [];
        $result = $db->query($sql);
        if($db->num_rows($result) > 0){
            while($row = $db->fetch_object($result)){
                $array[] = $row;
            }
        }
        return  $array;
    }

    public function generateTransactionID($sendId){
        $DBARTransactionID = substr(bin2hex(random_bytes(16)), 0, 16);
        ApiNSULog::invoiceLog("{$sendId}: DBAR Transaction ID: {$DBARTransactionID}");
        return $DBARTransactionID;
    }

    public function getProductLines($product_id)
	{
        global $db;
        $lines = [];
		$productObj = new Product($db);
		$result = $productObj->fetch($product_id);
        if($db->num_rows($result) > 0){
            $lines[] = (array) $productObj;
        }
		return $lines;
	}

    public function emailSender($note, $createdInvoiceArray)
	{
		foreach ($createdInvoiceArray as $invoice) {
			$note_array = [];
			ApiNSULog::invoiceLog("Start E-mail sending");
			$note_array = json_decode($note, true);
			$emailAddress = $note_array['email'];

			$const = new GlobalConst;
			$emailFrom = $const->load(self::GLOBAL_CONF_EMAIL_FROM);
			$recipients = $emailAddress;
			//$recipients = 'szollosi.laszlo@urbanms.hu';
			if (!empty($recipients) && !empty($emailFrom)) {
				$emailTemplateHandler = new EmailTemplateHandler;
				$template = $emailTemplateHandler->load(self::EMAIL_TEMPLATE);
				$templateObject = new stdClass();
				foreach ($template as $key => $value) {
					$templateObject->$key = $value;
				}
				if ($templateObject) {
					$varsInvoice = [
						'__SUBJECT__' => $const->load(self::INVOICE_SUBJECT),
						'__DESCRIPTION__' => $const->load(self::INVOICE_DESCRIPTION),
					];
					$template = $emailTemplateHandler->prepareTemplate($templateObject, $varsInvoice);
					$attachment = [DOL_DOCUMENT_ROOT . '/documents/facture/' . $invoice['invoice']['ref'] . '/' . $invoice['invoice']['ref'] . '.pdf'];
					$mimetype = ['application/pdf'];
					$mimefilename = [$invoice['invoice']['ref'] . '.pdf'];
					$mail = new CMailFile(
						$template->topic,
						$recipients,
						$emailFrom,
						$template->content,
						$attachment,
						$mimetype,
						$mimefilename,
						//null,
						//null,
						//null,
						'',
						'',
						0,
						1
					);
					// Send Email
					$mail->sendfile();
					ApiNSULog::invoiceLog('E-mail address: ' . $emailAddress);

					if ($mail->error) {
						ApiNSULog::invoiceLog($mail->error);
						// do something...
						dol_syslog('CRON ALERT EMAIL ERROR: ' . $mail->error, LOG_ERR);
					} else {
						ApiNSULog::invoiceLog("E-mail sent");
					}
				}
			}
		}
	}
}