<?php 
if(!defined('sugarEntry') || !sugarEntry) die('-1');
if (!$_POST['job'] || $_POST['job']=='') die ('-1');
switch ($_POST['job']) {
	case 'getTransaction': getTransaction($_POST['id']); break;
	case 'createRelation': createRelation($_POST['id'], $_POST['value'], $_POST['payment']); break;
	case 'getDetails': getDetails($_POST['id']); break;
	case 'getRangeTransactions' : getRangeTransactions($_POST['parent_id'],$_POST['date_start'],$_POST['date_end'],$_POST['type']); break;
	case 'createMonit': createMonit($_POST['ids'],$_POST['parent_id']); break;
	case 'sendNote': sendNote($_POST['ids'],$_POST['parent_id']); break;
	case 'searchBadTransactions': searchBadTransactions($_POST['parent_id']); break;
}


function getRangeTransactions($parent_id,$date_start,$date_end,$type){
	$db=$GLOBALS['db'];
	
	if($date_start==181 && $date_end==0){
		$date_to = new DateTime ( date ( "Y-m-d" ) );
		$date_to->modify ( '-'.$date_start.' days' );
		$d_t = $date_to->format ( 'Y-m-d' );
		$date_from = new DateTime ( date ( "Y-m-d" ) );
		$date_from->modify ( '-'.$date_end.' days' );
		$d_f = $date_from->format ( 'Y-m-d' );
		$query="select * from ecmtransactions where parent_id='".$parent_id."' and settled=0 and payment_date <= '".$d_f."'";
	} else {
		$date_to = new DateTime ( date ( "Y-m-d" ) );
		$date_to->modify ( '-'.$date_start.' days' );
		$d_t = $date_to->format ( 'Y-m-d' );
		$date_from = new DateTime ( date ( "Y-m-d" ) );
		$date_from->modify ( '-'.$date_end.' days' );
		$d_f = $date_from->format ( 'Y-m-d' );
		$query="select * from ecmtransactions where parent_id='".$parent_id."' and settled=0 and payment_date >= '".$d_f."' and payment_date <='".$d_t."'";
	}


	$res=$db->query($query);
	
	$transakcje_ma=[];
	$transakcje_winien=[];
	
	while($dane=$db->fetchByAssoc($res)){
		if($dane['type']==0){
			if($dane['record_type']=='EcmInvoiceOuts'){
				$inv = new EcmInvoiceOut();
				$inv->retrieve($dane['record_id']);
				if($inv->parent_id!=$parent_id){
					$dane['parent_2_id']=$inv->parent_id;
					$dane['parent_2_name']=$inv->parent_name;
					
				}
			}
			$transakcje_winien[]=$dane;
		} else {
			$transakcje_ma[]=$dane;
		}
		
		
		
	}

	$ss = new Sugar_Smarty();
	$ss->assign("ma", $transakcje_winien);
	$ss->assign("ID", $parent_id);
	$ss->assign("winien", $transakcje_ma);
	$ss->assign("range", $date_end);
	$ss->assign("okres", $date_start.' - '. ($date_end ==0 ? '...' : $date_end));
		
	echo $ss->display('modules/EcmPaymentStates/tpls/AccountPaymentStatesDetail.tpl');
	return true;
	
	
}

function searchBadTransactions($parent_id){
	$db=$GLOBALS['db'];
	
	# ma
	$query="
SELECT
	t.id,
	t.name,
    t.value,
	t.parent_name,
	t.parent_id,
    sum(rel.value) as sum,
    t2.parent_id,
    t2.deleted
FROM
    ecmtransactions t
inner join ecmtransactions_rel rel on rel.ecmtransaction_b_id=t.id
left join ecmtransactions t2 on rel.ecmtransaction_a_id=t2.id
WHERE
    t.deleted = 0
        AND t.register_date > '2011-12-31'
		AND t.type=1 and t.parent_id='".$parent_id."' and t.settled=1
        group by t.id";
	
	$res= $db->query($query);
	$ma=[];
	while($dane=$db->fetchByAssoc($res)){
		if($dane['deleted']==1){
			$ma[$dane['id']]['id']=$dane['id'];
			$ma[$dane['id']]['name']=$dane['name'];
			$ma[$dane['id']]['why']='Powiązana transakcja nie istnieje';
		}
		if($dane['parent_id']==""){
			$ma[$dane['id']]['id']=$dane['id'];
			$ma[$dane['id']]['name']=$dane['name'];
			$ma[$dane['id']]['why']='Powiązana transakcja nie istnieje';
		}
		
		if($dane['sum']!=$dane['value']){
			$ma[$dane['id']]['id']=$dane['id'];
			$ma[$dane['id']]['name']=$dane['name'];
			$ma[$dane['id']]['why']='Kwoty się nie bilansują';
		}
	}
	
	# winien
	$query="
SELECT
	t.id,
	t.name,
    t.value,
	t.parent_name,
	t.parent_id,
    sum(rel.value) as sum,
    t2.parent_id,
    t2.deleted
FROM
    ecmtransactions t
inner join ecmtransactions_rel rel on rel.ecmtransaction_a_id=t.id
left join ecmtransactions t2 on rel.ecmtransaction_b_id=t2.id
WHERE
    t.deleted = 0
        AND t.register_date > '2011-12-31' and t.settled=1
		AND t.type=0 and t.parent_id='".$parent_id."'
group by t.id
";
	
	$res= $db->query($query);
	$winien=[];
	while($dane=$db->fetchByAssoc($res)){
		if($dane['deleted']==1){
			$winien[$dane['id']]['id']=$dane['id'];
			$winien[$dane['id']]['name']=$dane['name'];
			$winien[$dane['id']]['why']='Powiązana transakcja nie istnieje';
		}
		if($dane['parent_id']==""){
			$winien[$dane['id']]['id']=$dane['id'];
			$winien[$dane['id']]['name']=$dane['name'];
			$winien[$dane['id']]['why']='Powiązana transakcja nie istnieje';
		}
		
		if($dane['sum']!=$dane['value']){
			$winien[$dane['id']]['id']=$dane['id'];
			$winien[$dane['id']]['name']=$dane['name'];
			$winien[$dane['id']]['why']='Kwoty się nie bilansują';
		}
		#winien 2
		$query2="SELECT rel.*,t.id as ids,t.deleted from ecmtransactions_rel rel 
left join ecmtransactions t on t.id=rel.ecmtransaction_b_id
 where rel.ecmtransaction_a_id ='".$dane['id']."'";
		
		$res2= $db->query($query2);
		
		while($dane2=$db->fetchByAssoc($res2)){
			if($dane2['ecmtransaction_b_id']==""){
				$winien[$dane['id']]['id']=$dane['id'];
				$winien[$dane['id']]['name']=$dane['name'];
				$winien[$dane['id']]['why']='Powiązana transakcja nie istnieje';
			}
			if($dane2['deleted']!=0){
				$winien[$dane['id']]['id']=$dane['id'];
				$winien[$dane['id']]['name']=$dane['name'];
				$winien[$dane['id']]['why']='Powiązana transakcja nie istnieje';
			}
		}
	}

	
	
	$ss = new Sugar_Smarty();
	$ss->assign("winien", $winien);
	
	$ss->assign("ma", $ma);
	$ss->assign("parent_id", $parent_id);
	
	echo $ss->display('modules/EcmPaymentStates/tpls/Detail.tpl');
	return true;
}

function sendNote($ids,$parent_id){
    global $current_user;
    
    $db=$GLOBALS['db'];
    
    $uq=$db->query("select google_login,CAST(AES_DECRYPT(google_password, 'jakistamhash123') as CHAR)
AS google_password FROM users where id='".$current_user->id."'");
    $rul=$db->fetchByAssoc($uq);
     
    if($rul['google_login']!='' && $rul['google_password']!=''){
         
         
        require_once ("modules/EcmPaymentStates/createPDF.php");
        require_once ("include/phpmailer/class.phpmailer.php");
        require_once ("include/phpmailer/class.smtp.php");
    
        $mailClassS = new PHPMailer ();
    
        $mailClassS->isSMTP (); // Set mailer to use SMTP
    
        $mailClassS->Host = 'smtp.gmail.com'; // Specify main and backup server
         
        $mailClassS->SMTPAuth = true; // Enable SMTP authentication
        $mailClassS->Username = $rul['google_login']; // SMTP username
        $mailClassS->Password = $rul['google_password']; // SMTP password
        $mailClassS->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
        $mailClassS->Port = 587; // Set the SMTP port number - 587 for
    
        // get email from accounts
        $sea = new SugarEmailAddress;
        // Grab the array of addresses
        $addresses = $sea->getAddressesByGUID($parent_id, 'Accounts');
    
        foreach ( $addresses as $address ) {
            if($address['email_address']!='' && $address['opt_out']==1){
                $mailClassS->addAddress ($address['email_address']); // Add address
            }
        }
        // set sender
        $mailClassS->Sender=$rul['google_login'];
        $mailClassS->From =$rul['google_login'];
        $mailClassS->FromName =$current_user->first_name.' '.$current_user->last_name;
    
        $mailClassS->WordWrap = 50; // Set word wrap to 50 characters
    
        $mailClassS->isHTML ( true ); // Set email format to HTML
    
        $mailClassS->Subject = 'Dokument od E5 Polska sp. z o.o.';
       $path=createEcmPaymentStatePdf('null','FILE','null',$ids);
    
        $mailClassS->Body = 'Witam,<br><br>Nota odsetkowa';
        // załącznik
       
         
        if(file_exists('/var/www/html/crm/'.$path)){
    
            $mailClassS->addAttachment($path);
    
        }
        // Read an HTML message body from an external file, convert
        // referenced images to embedded,
        // convert HTML into a basic plain-text alternative body
        // $mailClassS->msgHTML(file_get_contents('contents.html'),
        // dirname(__FILE__));
         
         
        if(count($mailClassS->to)>0){
    
            if (! $mailClassS->send ()) {
                 
                unlink('/var/www/html/crm/'.$path);
                echo '-1';
            } else {
                unlink('/var/www/html/crm/'.$path);
                echo '1';
            }
        } else {
            echo '-1';
             
        }
    } else {
        echo '-1';
    }
}

function createMonit($ids,$parent_id){
   //ini_set('display_errors',1);
    include 'modules/EcmPaymentStates/interestModel.php';
    $m= new interestModel(); 

    
    global $current_user;
    
    $db=$GLOBALS['db'];
    
    $uq=$db->query("select google_login,CAST(AES_DECRYPT(google_password, 'jakistamhash123') as CHAR)
AS google_password FROM users where id='".$current_user->id."'");
    $rul=$db->fetchByAssoc($uq);
   
    if($rul['google_login']!='' && $rul['google_password']!=''){
         
         
       // require_once ("modules/EcmPaymentStates/createPDF.php");
        require_once ("include/phpmailer/class.phpmailer.php");
        require_once ("include/phpmailer/class.smtp.php");
    
        $mailClassS = new PHPMailer ();
    
        $mailClassS->isSMTP (); // Set mailer to use SMTP
    
        $mailClassS->Host = 'smtp.gmail.com'; // Specify main and backup server
         
        $mailClassS->SMTPAuth = true; // Enable SMTP authentication
        $mailClassS->Username = $rul['google_login']; // SMTP username
        $mailClassS->Password = $rul['google_password']; // SMTP password
        $mailClassS->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
        $mailClassS->Port = 587; // Set the SMTP port number - 587 for
    
        // get email from accounts
        $sea = new SugarEmailAddress;
        // Grab the array of addresses
        $addresses = $sea->getAddressesByGUID($parent_id, 'Accounts');
    
        foreach ( $addresses as $address ) {
            if($address['email_address']!='' && $address['opt_out']==1){
                $mailClassS->addAddress ($address['email_address']); // Add address
            }
        }
        // set sender
        $mailClassS->Sender=$rul['google_login'];
        $mailClassS->From =$rul['google_login'];
        $mailClassS->FromName =$current_user->first_name.' '.$current_user->last_name;
    
        $mailClassS->WordWrap = 50; // Set word wrap to 50 characters
    
        $mailClassS->isHTML ( true ); // Set email format to HTML
    
       $mailClassS->Subject = 'Dokument od E5 Polska sp. z o.o.';
   
    
        $mailClassS->Body = 'Witam,<br><br>Przypominamy o zaległości, w załączniku z znajduje się wezwanie do zapłaty';
        // załącznik
        $path=$m->makeMonit($ids);
       
        if(file_exists('/var/www/html/crm/'.$path)){
            
            $mailClassS->addAttachment($path);
    
        }
        // Read an HTML message body from an external file, convert
        // referenced images to embedded,
        // convert HTML into a basic plain-text alternative body
        // $mailClassS->msgHTML(file_get_contents('contents.html'),
        // dirname(__FILE__));
         
   
        if(count($mailClassS->to)>0){
    
            if (! $mailClassS->send ()) {
                 
                unlink('/var/www/html/crm/'.$path);
                echo '-1';
            } else {
                unlink('/var/www/html/crm/'.$path);
                echo '1';
            }
        } else {
            echo '-1';
             
        }
    } else {
        echo '-1';
    }
}

function getTransaction($id) {
	if (!$id || $id == '') die('-1');
	$db = $GLOBALS['db'];

$res = $db->fetchByAssoc($db->query("
SELECT t.id,t.name, t.value, sum(rel.value) as settled FROM ecmtransactions AS t
INNER JOIN ecmtransactions_rel AS rel
ON (rel.ecmtransaction_a_id=t.id OR rel.ecmtransaction_b_id=t.id)
WHERE t.id='$id'
"));

if (!$res['settled']) $res['settled'] = 0;

echo json_encode($res);
return;
}	

function createRelation($id, $value, $payment) {
	$db = $GLOBALS['db'];
	global $current_user;
	$db->query("
INSERT INTO ecmtransactions_rel VALUES (
'".create_guid()."',
'".date("Y-m-d H:i:s")."',
'".$current_user->id."',
'$id',
'$payment',
'$value'
)			
");

//check is settled
//winien
	$res = $db->fetchByAssoc($db->query("
			SELECT (t.value-sum(rel.value)) as unsettled FROM ecmtransactions AS t
			INNER JOIN ecmtransactions_rel AS rel
			ON (rel.ecmtransaction_a_id=t.id OR rel.ecmtransaction_b_id=t.id)
			WHERE t.id='$id'
			"));	
	echo 'WINIEN '.$row['unsettled'].'...';
	if ($res['unsettled']==0){ 
		$t = new EcmTransaction();
		$t->retrieve($id);
		if($t->record_type=='Documents'){
			$db->query("UPDATE documents SET status='2' WHERE id='$t->record_id'");
		}
		$db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$id'");
	}
//ma 
	$res = $db->fetchByAssoc($db->query("
			SELECT (t.value-sum(rel.value)) as unsettled FROM ecmtransactions AS t
			INNER JOIN ecmtransactions_rel AS rel
			ON (rel.ecmtransaction_a_id=t.id OR rel.ecmtransaction_b_id=t.id)
			WHERE t.id='$payment'
			"));
	echo 'MA '.$row['unsettled'].'...';
	if ($res['unsettled']==0){
		$t = new EcmTransaction();
		$t->retrieve($payment);
		if($t->record_type=='Documents'){
			$db->query("UPDATE documents SET status='2' WHERE id='$t->record_id'");
			$db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$payment'");
		}
	}
	echo '1';
	return; 
}

function getDetails($id) {
	$db = $GLOBALS['db'];
	
	$result = array();
	
	
	
	$res = $db->query("
select t.id, t.name, rel.value from ecmtransactions_rel as rel
inner join ecmtransactions as t
on t.id = rel.ecmtransaction_a_id
where rel.ecmtransaction_b_id='$id' and t.deleted=0");
		
	while ($row = $db->fetchByAssoc($res)) {
		$row['value'] = format_number($row['value']);
		$result[] = $row;
	}
	
	$res = $db->query("
			select t.id, t.name, rel.value from ecmtransactions_rel as rel
			inner join ecmtransactions as t
			on t.id = rel.ecmtransaction_b_id
			where rel.ecmtransaction_a_id='$id'  and t.deleted=0");

	while ($row = $db->fetchByAssoc($res)) {
		$row['value'] = format_number($row['value']);
		$result[] = $row;
	}
	
	$ss = new Sugar_Smarty();
	$ss->assign("ID", $id);
	
	$ss->assign("RES", $result);
	
	echo $ss->display('modules/EcmPaymentStates/tpls/AccountPaymentStatesDetail.tpl');
	return true;
}