<?php
// ini_set ( 'display_errors', 1 );

/*
 * Wyszukiwanie i tworzenie faktur okresowych z zamówień
 * Autor: Dominik 'DranZi' Brzóska
 */
class periodicInvoices {
	private $db;
	private $ask;
	private $reply;
	private $result;
	private $pos;
	private $id;
	private $val;
	private $document_list;
	private $position_list;
	private $c;
	public $return_id;
	public $multi_pdf_ids;
	
	/*
	 * Wyszukuje zamówienia miesięczne i roczne :)
	 *
	 */
	function searchSaleOrders() {
		$this->db = $GLOBALS ['superGlobalDb'];
		$this->ask = "select 
            id, status, document_no, invoice_date,stock_id,stock_name,ecmpaymentcondition_id,currency_id,created_by,modified_user_id,assigned_user_id,parent_id,parent_name,stock_id
                parent_address_street,
                parent_address_city,
                parent_address_postalcode,
                parent_address_country,
                parent_nip,
                payment_date_days,
                invoice_date_interval,
                type,
        		shipping_address_name,
    shipping_address_street,
       shipping_address_postalcode,
   shipping_address_city
                
                
        from
            ecmsales
        where
            deleted = 0
   and (type = 'inv_m' or type= 'inv_y')";
		
		$this->reply = $this->db->query ( $this->ask );
		echo $this->reply->num_rows . "\n";
		while ( $this->result = $this->db->fetchByAssoc ( $this->reply ) ) {
			
			$add = false;
			if ($this->result ['type'] == 'inv_m') {
				// miesieczne
				if ($this->result ['invoice_date_interval'] == 1 || $this->result ['invoice_date_interval'] == '') {
					// co miesiac lub nie wpisane
					if (date ( 'd', strtotime ( $this->result ['invoice_date'] ) ) == date ( 'd' )) {
						$add = true;
					}
				} else {
					$from = new DateTime ( date ( 'Y-m-d', strtotime ( $this->result ['invoice_date'] ) ) );
					$to = new DateTime ();
					for($a = 1; $from <= $to; $from->modify ( '+' . $this->result ['invoice_date_interval'] . ' month' )->format ( 'm' )) {
						if ($from->format ( 'm' ) == $to->format ( 'm' ) && $from->format ( 'd' ) == $to->format ( 'd' )) {
							$add = true;
						}
					}
				}
			} else {
				if ($this->result ['type'] == 'inv_y') {
					if (date ( 'd', strtotime ( $this->result ['invoice_date'] ) ) == date ( 'd' ) && date ( 'm', strtotime ( $this->result ['invoice_date'] ) ) == date ( 'm' )) {
						$add = true;
					}
				}
			}
			
			if ($add == true) {
				echo 'cos dodaje' . "\n";
				$this->document_list [] = $this->result;
			}
		}
	}
	
	/*
	 * Wyszukuje zbliżające się terminy rat
	 */
	function searchPayments() {
		$this->db = $GLOBALS ['db'];
		$this->ask = "select p.*,a.parent_id,a.id as docid,a.created_by from ecmagreementitems p 
	inner join ecmagreements a on p.ecmagreement_id=a.id
where
 p.deleted=0 and ((day(p.payment_date)-2) = day('2015-01-29')
                and month(p.payment_date) = month('2015-01-29')
                and year(p.payment_date) = year('2015-01-29')) limit 1";
		
		$this->reply = $this->db->query ( $this->ask );
		while ( $this->result = $this->db->fetchByAssoc ( $this->reply ) ) {
			$this->document_list [] = $this->result;
		}
	}
	function getParentEmail($parent) {
		$sea = new SugarEmailAddress ();
		$addresses = $sea->getAddressesByGUID ( $parent, 'Accounts' );
		$a = new Account ();
		$a->retrieve ( $parent );
		$check = 0;
		$email = array ();
		foreach ( $addresses as $address ) {
			if ($address ['email_address'] != '') {
				$email [$address ['email_address']] = $a->name;
				$check = 1;
			}
		}
		unset ( $sea );
		unset ( $a );
		return $check == 1 ? $email : $check;
	}
	function getUserEmail($user_id) {
		$user = BeanFactory::getBean ( 'Users', $user_id );
		$primary_email = $user->emailAddress->getPrimaryAddress ( $user );
		return $primary_email;
	}
	function stringToArray($char) {
		$this->return_id = explode ( $char, $this->return_id );
	}
	function CreateSinglePdf() {
		$_REQUEST ['pdf_type'] = 0;
		include_once "modules/EcmInvoiceOuts/createPDF.php";
		
		$_REQUEST ['pdf_type'] = 0;
		$EcmSysInfo = new EcmSysInfo ();
		if ($EcmSysInfo->getDatabaseName () == 'preDb_60b08fe051546309b61d2714d4a0438d') {
			$return = newPDFCreator ( $this->id, 'FILE', true );
		} else {
			$return = createEcmInvoiceOutPdf ( $this->id, 'FILE' );
		}
		
		return $return;
	}
	
	/*
	 * Wysyłanie emailu
	 */
	function sendSingleEmail($title, $text, $to, $filename, $id) {
		require_once ("include/phpmailer/class.phpmailer.php");
		require_once ("include/phpmailer/class.smtp.php");
		
		$mailClassS = new PHPMailer ();
		$mailClassS->isSMTP (); // Set mailer to use SMTP
		
		$EcmSysInfo = new EcmSysInfo ();
		$email = $EcmSysInfo->getEmailSettings ();
		$cc = explode ( ':', $email ['value1'] );
		if ($email ['value1'] != '' && $email ['value2'] != '' && $email ['value3'] != '') {
			global $sugar_config, $current_user;
			
			$mailClassS->Host = $cc [0]; // Specify main and backup server
			$mailClassS->SMTPAuth = true; // Enable SMTP authentication
			$mailClassS->Username = $email ['value2'];
			$mailClassS->Password = $email ['value3'];
			$mailClassS->SMTPSecure = $email ['value5']; // Enable encryption, 'ssl' also accepted
			$EcmSysInfo = new EcmSysInfo ();
			
			if ($EcmSysInfo->getDatabaseName () == 'preDb_60b08fe051546309b61d2714d4a0438d') {
				$mailClassS->AddCC ( 'faktura@matinstal.pl', 'Faktury matinstall' );
			}
			$mailClassS->Port = $cc [1]; // Set the SMTP port number - 587 for
			if ($email ['value4'] != '') {
				$mailClassS->Sender = $email ['value4'];
				$mailClassS->From = $email ['value4'];
			} else {
				$mailClassS->Sender = $email ['value2'];
				$mailClassS->From = $email ['value2'];
			}
			
			$mailClassS->FromName = $EcmSysInfo->getName ();
			$mailClassS->WordWrap = 50; // Set word wrap to 50 characters
		} else {
			$mailClassS->Host = 'smtp.gmail.com'; // Specify main and backup server
			
			$mailClassS->SMTPAuth = true; // Enable SMTP authentication
			$mailClassS->Username = 'biuro@saascrm.pl'; // SMTP username
			$mailClassS->Password = 'test5555'; // SMTP password
			$mailClassS->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
			$mailClassS->Port = 587; // Set the SMTP port number - 587 for
				                         // authenticated TLS
		}
		
		foreach ( $to as $ad => $tit ) {
			$mailClassS->addAddress ( $ad, $tit ); // Add a
		}
		
		$mailClassS->WordWrap = 50; // Set word wrap to 50 characters
		
		$mailClassS->isHTML ( true ); // Set email format to HTML
		$title = 'Nowa faktura od ' . $EcmSysInfo->getShortName ();
		$text = "Witam,<br> w załączniku przesyłam fakturę, proszę o potwierdzenie dostarczenia dokumentu ";
		$mailClassS->Subject = $title;
		$mailClassS->Body = $text;
		
		if (file_exists ( '/var/www/html/system/' . $filename )) {
			
			$mailClassS->addAttachment ( '/var/www/html/system/' . $filename );
		}
		
		if (! $mailClassS->send ()) {
			return false;
		}
		$db = $GLOBALS ['superGlobalDb'];
		$db->query ( "update ecminvoiceouts set sended=1 where id='" . $id . "'" );
		return true;
	}
	
	/*
	 * Tworzy faktury z wyszukanych zamówień
	 *
	 */
	function createInvoiceList() {
		if (count ( $this->document_list ) > 0) {
			
			foreach ( $this->document_list as $this->pos => $this->value ) {
				
				$this->createInvoice ( $this->document_list [$this->pos] );
				if ($this->getParentEmail ( $this->document_list [$this->pos] ['parent_id'] ) != 0) {
					
					$this->sendSingleEmail ( '', '', $this->getParentEmail ( $this->document_list [$this->pos] ['parent_id'] ), $this->CreateSinglePdf ( $this->id ), $this->id );
				}
			}
		}
	}
	
	/*
	 * Tworzy faktury z wyszukanych terminów płatności
	 *
	 */
	function createInvoicePaymentList() {
		if (! (count ( $this->document_list ) > 0)) {
			foreach ( $this->document_list as $this->pos => $this->value ) {
				if ($this->getParentEmail ( $this->document_list [$this->pos] ['parent_id'] ) != 0) {
					
					$this->createInvoicePayment ( $this->document_list [$this->pos] );
				} else {
					$this->getUserEmail ( $this->document_list [$this->pos] ['created_by'] );
					$this->createInvoicePayment ( $this->document_list [$this->pos] );
				}
			}
		}
	}
	
	/*
	 * Tworzy pojedyńczą fakturę, z podanego zamówienia
	 *
	 */
	function createInvoice($values) {
		$inv = new EcmInvoiceOut ();
		$inv->pdf_type = 'K';
		$inv->type = 'normal';
		$inv->register_date = date ( "d.m.Y" );
		$inv->sell_date = date ( "d.m.Y" );
		$inv->ecmlanguage = 'pl_pl';
		
		$values ['currency_id'] != 'PLN' ? $inv->currency_value_nbp = $this->getNBPCurrencyExchange ( $values ['currency_id'], date ( "d.m.Y" ) ) : $inv->currency_value_nbp = '';
		$inv->currency_id = $values ['currency_id'];
		
		$stock = new EcmStock ();
		$stock->retrieve ( $values ['stock_id'] );
		$inv->stock_id = $values ['stock_id'];
		$st = new EcmStock ();
		$st->retrieve ( $values ['stock_id'] );
		$dbs = $GLOBALS ['superGlobalDb'];
		$zapps = $dbs->query ( "select value9 from operating_values where id='" . $st->default_bank_id . "'" );
		$row2 = $dbs->fetchByAssoc ( $zapps );
		$inv->bankaccount = $row2 ['value9'];
		$inv->stock_name = $stock->name;
		unset ( $stock );
		$inv->category = 'f29423eb-7bb1-5727-b900-55151722bc67';
		$inv->assigned_user_id = $values ['assigned_user_id'];
		$inv->modified_user_id = $values ['modified_user_id'];
		$inv->modified_user_id = $values ['modified_user_id'];
		
		$payc = new EcmPaymentCondition ();
		
		$inv->payment_date_days = $values ['payment_date_days'];
		$payc->retrieve ( $values ['ecmpaymentcondition_id'] );
		$inv->payment_date = date ( 'd.m.Y', strtotime ( "+" . $values ['payment_date_days'] . " day", strtotime ( date ( "d.m.Y" ) ) ) );
		
		$inv->payment_method = 'PRZELEW';
		$inv->payment_method_paid = 0;
		unset ( $payc );
		
		$a = new Account ();
		$a->retrieve ( $values ['parent_id'] );
		
		$inv->parent_id = $values ['parent_id'];
		$inv->parent_name = $a->name;
		$inv->parent_shipping_address_name = $values ['shipping_address_name'];
		$inv->parent_shipping_address_street = $values ['shipping_address_street'];
		$inv->parent_shipping_address_postalcode = $values ['shipping_address_postalcode'];
		$inv->parent_shipping_address_city = $values ['shipping_address_city'];
		$inv->parent_address_street = $a->register_address_street;
		$inv->parent_address_city = $a->register_address_city;
		$inv->parent_address_postalcode = $a->register_address_postalcode;
		$inv->parent_address_country = $a->register_address_country;
		$inv->parent_nip = $values ['parent_nip'];
		
		$this->getPositionList ( $values ['id'] );
		$inv->position_list = $this->position_list;
		$inv->save ();
		$this->id = $inv->id;
		unset ( $inv );
	}
	
	/*
	 * Tworzy pojedyńczą fakturę, z podanego terminu płatności
	 *
	 */
	function createInvoicePayment($values) {
		
		// faktura prowizja
		$inv = new EcmInvoiceOut ();
		$inv->pdf_type = 'K';
		$inv->type = 'normal';
		$inv->register_date = date ( "d.m.Y" );
		$inv->sell_date = date ( "d.m.Y" );
		$inv->ecmlanguage = 'pl_pl';
		
		$values ['currency_id'] != 'PLN' ? $inv->currency_value_nbp = $this->getNBPCurrencyExchange ( $values ['currency_id'], date ( "d.m.Y" ) ) : $inv->currency_value_nbp = '';
		$inv->currency_id = $values ['currency_id'];
		
		$stock = new EcmStock ();
		$stock->retrieve ( '3da5fb18-fdfe-f878-b7e5-53ce0d41c4b9' );
		$inv->stock_id = '3da5fb18-fdfe-f878-b7e5-53ce0d41c4b9';
		$inv->stock_name = $stock->name;
		unset ( $stock );
		
		$inv->assigned_user_id = $values ['assigned_user_id'];
		$inv->modified_user_id = $values ['modified_user_id'];
		$inv->modified_user_id = $values ['modified_user_id'];
		
		$payc = new EcmPaymentCondition ();
		$inv->ecmpaymentcondition_id = 'f194e75a-14a6-ecbe-db89-54c0b2863837';
		$payc->retrieve ( 'f194e75a-14a6-ecbe-db89-54c0b2863837' );
		$inv->payment_date = date ( 'd.m.Y', strtotime ( "+" . $payc->days . " day", strtotime ( date ( "d.m.Y" ) ) ) );
		$inv->payment_method = 'PRZELEW';
		$inv->payment_method_paid = 0;
		unset ( $payc );
		
		$a = new Account ();
		$a->retrieve ( $values ['parent_id'] );
		
		$inv->parent_id = $values ['parent_id'];
		$inv->parent_name = $a->name;
		$inv->parent_address_street = $a->register_address_street;
		$inv->parent_address_city = $a->register_address_city;
		$inv->parent_address_postalcode = $a->register_address_postalcode;
		$inv->parent_address_country = $a->register_address_country;
		$inv->parent_nip = $a->vatid;
		unset ( $a );
		
		$this->getPositionListPayment ( $values, 1 );
		$inv->position_list = $this->position_list;
		$this->return_id = $inv->save ();
		unset ( $inv );
		
		// faktura odstetki
		$inv = new EcmInvoiceOut ();
		$inv->pdf_type = 'K';
		$inv->type = 'normal';
		$inv->register_date = date ( "d.m.Y" );
		$inv->sell_date = date ( "d.m.Y" );
		$inv->ecmlanguage = 'pl_pl';
		
		$values ['currency_id'] != 'PLN' ? $inv->currency_value_nbp = $this->getNBPCurrencyExchange ( $values ['currency_id'], date ( "d.m.Y" ) ) : $inv->currency_value_nbp = '';
		$inv->currency_id = $values ['currency_id'];
		
		$stock = new EcmStock ();
		$stock->retrieve ( '3da5fb18-fdfe-f878-b7e5-53ce0d41c4b9' );
		$inv->stock_id = '3da5fb18-fdfe-f878-b7e5-53ce0d41c4b9';
		$inv->stock_name = $stock->name;
		unset ( $stock );
		
		$inv->assigned_user_id = $values ['assigned_user_id'];
		$inv->modified_user_id = $values ['modified_user_id'];
		$inv->modified_user_id = $values ['modified_user_id'];
		
		$payc = new EcmPaymentCondition ();
		$inv->ecmpaymentcondition_id = 'f194e75a-14a6-ecbe-db89-54c0b2863837';
		$payc->retrieve ( 'f194e75a-14a6-ecbe-db89-54c0b2863837' );
		$inv->payment_date = date ( 'd.m.Y', strtotime ( "+" . $payc->days . " day", strtotime ( date ( "d.m.Y" ) ) ) );
		$inv->payment_method = 'PRZELEW';
		$inv->payment_method_paid = 0;
		unset ( $payc );
		
		$a = new Account ();
		$a->retrieve ( $values ['parent_id'] );
		
		$inv->parent_id = $values ['parent_id'];
		$inv->parent_name = $a->name;
		$inv->parent_address_street = $a->register_address_street;
		$inv->parent_address_city = $a->register_address_city;
		$inv->parent_address_postalcode = $a->register_address_postalcode;
		$inv->parent_address_country = $a->register_address_country;
		$inv->parent_nip = $a->vatid;
		unset ( $a );
		
		$this->getPositionListPayment ( $values, 2 );
		$inv->position_list = $this->position_list;
		$this->return_id .= ',' . $inv->save ();
		unset ( $inv );
	}
	
	/**
	 * Zrwaca id
	 */
	function getReturnId() {
		return $this->return_id;
	}
	
	/*
	 * Wybiera pozycje do faktury z zamówienia
	 *
	 */
	function getPositionList($id) {
		$sale = new EcmSale ();
		$sale->retrieve ( $id );
		$this->position_list = $sale->getPositionList ( true );
	}
	
	/*
	 * Wybiera pozycje do płatności
	 *
	 */
	function getPositionListPayment($values, $type) {
		if ($type == 1) {
			$prid = 'a0c0fff9-59e9-2ac1-40d6-54bfbd898819';
			$price = $values ['rate_of_commission'];
		} else {
			$prid = '16a48303-20e3-703e-46d6-54bfbd53ecd5';
			$price = $values ['interest_rate'];
		}
		$p = new EcmProduct ();
		$p->retrieve ( $prid );
		$arr [0] = array (
				'product_id' => $prid,
				'product_code' => $p->code,
				'name' => $p->name,
				'quantity' => '1.00',
				'price_start' => $price,
				'price_netto' => $price,
				'discount' => '0',
				'total_netto' => $price,
				'total_brutto' => $price,
				'total_vat' => '0',
				'price_brutto' => $price,
				'unit_id' => '1',
				'unit_name' => 'szt',
				'ecmvat_id' => '2f834337-a407-c5c0-0892-54bfbdbd952f',
				'ecmvat_name' => 'ZW',
				'ecmvat_value' => '0' 
		);
		
		$this->position_list = $arr;
		unset ( $p );
		unset ( $arr );
	}
	
	/*
	 * załaduj dane do zewnętrznej klasy
	 */
	function loader($klasa) {
		foreach ( $this as $key => $value ) {
			$rp = new ReflectionProperty ( $this, $key );
			if ($rp->isPrivate () == 1)
				continue;
			$klasa->$key = $this->$key;
		}
	}
	
	/*
	 * Pobiera kurs NBP
	 *
	 */
	function getNBPCurrencyExchange($c_id, $d) {
		global $timedate;
		$d = explode ( '-', reset ( explode ( " ", $timedate->to_db ( $d ) ) ) );
		$date = date ( "Y-m-d", @mktime ( 0, 0, 0, $d [1], $d [2], $d [0] ) + 3600 * 24 );
		
		// what day is it?
		$dn = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "SELECT DAYNAME('$date') as dayname" ) );
		
		if ($dn ['dayname'] == 'Sunday') // - 2 days
			$q = "SELECT value FROM currency_nbp_archive WHERE currency_id='$c_id' AND date = DATE_ADD('$date', INTERVAL -2 DAY)";
		elseif ($dn ['dayname'] == 'Saturday') // - 1 day
			$q = "SELECT value FROM currency_nbp_archive WHERE currency_id='$c_id' AND date = DATE_ADD('$date', INTERVAL -1 DAY)";
		else // any other day - just get exchange
			$q = "SELECT value FROM currency_nbp_archive WHERE currency_id='$c_id' AND date='$date'";
		
		$w = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( $q ) );
		
		echo $w ['value'];
		return;
	}
	function setReturnId($string) {
		$this->return_id = $string;
	}
}

?>