<?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 'createRelationM': createRelationM($_POST['id'], $_POST['value'], $_POST['payment']); break;
	case 'createRelationMany': createRelationMany($_POST['id'], $_POST['value'], $_POST['payment']); break;
	case 'getDetails': getDetails($_POST['id']); break;
	case 'createMonit': createMonit($_POST['ids'],$_POST['parent_id'],$_POST['email'],$_POST['text']); break;
	case 'sendNote': sendNote($_POST['ids'],$_POST['parent_id']); break;
	case 'sendSMS': sendSMS($_POST['number'],$_POST['content']); break;
	case 'createCsvFile': createCsvFile($_POST['ids'],$_POST['bank']); break;
}

function sendSMS($number,$content){
	$db=$GLOBALS['db'];
	$EcmSysInfo = new EcmSysInfo();

	if($EcmSysInfo->getDatabaseName() == 'saassystem'){

		static $content2;
		$params = array(
				'username' => 'admin',
				'api_key' => 'rudemodz',
				'message' => $content,
				'number' => $number
		);
		$params['message']=urldecode($content);
		
		$params['to']=$number;
		
	
			$url = 'http://damznac.pl/api/sendSms';
		
	
		$c = curl_init();
		curl_setopt( $c, CURLOPT_URL, $url );
		curl_setopt( $c, CURLOPT_POST, true );
		curl_setopt( $c, CURLOPT_POSTFIELDS, $params );
		curl_setopt( $c, CURLOPT_RETURNTRANSFER, true );
		
		$content2 = curl_exec( $c );
		$http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
		
		if($http_status != 200){
			
			echo $content2;
		} else {
			echo 'OK';
			return;
		}
		
		curl_close( $c );
	} else {
		$query="select * from operating_values where value0='smsApi'";
		$res=$db->query($query);
		$dane= $db->fetchByAssoc($res);
		
		static $content2;
		$params = array(
				'username' => $dane['value1'],
				'password' => md5($dane['value2']),
				'to' => '',
				'from' => 'SMSAPI',
				'eco' => 0,
				'message' => "",
		);
		$params['message']=urldecode($content);
		
		$params['to']=$number;
		
		if($backup == true){
			$url = 'https://api2.smsapi.pl/sms.do';
		}else{
			$url = 'https://api.smsapi.pl/sms.do';
		}
		
		$c = curl_init();
		curl_setopt( $c, CURLOPT_URL, $url );
		curl_setopt( $c, CURLOPT_POST, true );
		curl_setopt( $c, CURLOPT_POSTFIELDS, $params );
		curl_setopt( $c, CURLOPT_RETURNTRANSFER, true );
		
		$content2 = curl_exec( $c );
		$http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
		
		if($http_status != 200 && $backup == false){
			$backup = true;
			sms_send($params, $backup);
		}
		
		curl_close( $c );
	}
	
return 'ok';
}

function createCsvFile($ids,$bank){

    $przelewy=array();
    foreach ($ids as $id){

        $t = new EcmTransaction();
        $t->retrieve($id);

        $a = new Account();
        $a->retrieve($t->parent_id);
    

        if($a->getFirstBankAccount()!=''){
        $przelewy[$t->parent_id]['value']+=$t->value;
        $przelewy[$t->parent_id]['index']=str_replace("'","",htmlspecialchars_decode($a->index_dbf));
        $przelewy[$t->parent_id]['parent_name']=str_replace("'","",htmlspecialchars_decode($t->parent_name));
        $przelewy[$t->parent_id]['parent_name']=str_replace('"',"",$przelewy[$t->parent_id]['parent_name']);
        $przelewy[$t->parent_id]['account']=$a->getFirstBankAccount();
        $przelewy[$t->parent_id]['desc'].=$t->name.', ';
        }
    }

    getBankFormat($bank,$przelewy);
}

function removeBadChars($name){
	$chars=array('/','?','-',"'",'(',')','+',',','.','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','ź','Ą','Ć','Ę','Ł','Ń','Ó','Ś','Ż','Ź'
		,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','ą','ć','ę','ł','ń','ó','ś','ż','|',' '	
	);
	$new=array();

	for($i=0;$i<strlen($name);$i++){
	
		foreach ($chars as $char){
			if($char==$name[$i]){
		
				$new[]=$name[$i];
			}
		}
	}
	return implode('',$new);
}



function createLineBGZ($line){
	$name=removeBadChars($line['parent_name']);
	$title=removeBadChars($line['desc']);
	
	$title=substr($title,0,140);

	if(strlen($name)>35){
		$name=substr($name,0,35);
		$line=';'.str_replace(' ','',$line['account']).';'.$name.';;;;'.$title.';'.str_replace('.',',',$line['value']).PHP_EOL;
	} else {
		$line=';'.str_replace(' ','',$line['account']).';'.$name.';;;;'.$title.';'.str_replace('.',',',$line['value']).PHP_EOL;
	}
	return $line;
}
  
function getBankFormat($id,$data){ 
	global $current_user; 
	$fp=fopen('import_'.$current_user->id.'.csv','w');
	if($id==1){
		foreach ($data as $key=>$val){
			if($val['value']!=''){
				$line=createLineBGZ($val);
				fwrite($fp,$line);
			}
		}
	}
	fclose($fp);
	echo json_encode('import_'.$current_user->id.'.csv');
	return;
	return '';
}

function createRelationMany($id){
    global $current_user;
    $db=$GLOBALS['db'];
    $ids=explode(',',$id);
    $prawa=0;
    $lewa_id=array();
    $prawa_id=array();
    $lewa=0;
    foreach ($ids as $i){
        $t = new EcmTransaction();
        $t->retrieve($i);
        if($t->value>0){
            $lewa+=$t->value;
            $tmp=array();
            $tmp['id']=$t->id;
            $tmp['value']=$t->value;
            $tmp['left']=$t->getRelations();
            $tmp['used']=0;
            $lewa_id[]=$tmp;
        } else {
            $prawa+=$t->value;
            $tmp=array();
            $tmp['id']=$t->id;
            $tmp['value']=$t->value;
            $tmp['left']=$t->getRelations();
            $tmp['used']=0;
            $prawa_id[]=$tmp;
        }
    }
 
        foreach ($prawa_id as $p=>$v){
            foreach ($lewa_id as $l=>$v2){
                if($prawa_id[$p]['used']==0 && $lewa_id[$l]['used']==0){
                    if($prawa_id[$p]['left']+$lewa_id[$l]['left']<=0){
                        echo $prawa_id[$p]['left']." ".$lewa_id[$l]['left']."\n";
                        if(round($prawa_id[$p]['left']+$lewa_id[$l]['left'],2)==0.00){
                            $prawa_id[$p]['used']=1;
                               $db->query("update ecmtransactions set settled=1 where id='".$prawa_id[$p]['id']."'");
                            echo "update ecmtransactions set settled=1 where id='".$prawa_id[$p]['id']."'\n";
                        }
                        $prawa_id[$p]['left']+=$lewa_id[$l]['left'];
                        $lewa_id[$l]['used']=1;
                        echo "Po operacji ".$prawa_id[$p]['left']."\n";
                            $db->query("update ecmtransactions set settled=1 where id='".$lewa_id[$l]['id']."'");
                        echo "update ecmtransactions set settled=1 where id='".$lewa_id[$l]['id']."'\n";
                         echo "
INSERT INTO ecmtransactions_rel VALUES (
'".create_guid()."',
'".date("Y-m-d H:i:s")."',
'".$current_user->id."',
'".$prawa_id[$p]['id']."',


'".$lewa_id[$l]['id']."',
        '".abs($lewa_id[$l]['left'])."'
)
";
                       $db->query("
INSERT INTO ecmtransactions_rel VALUES (
'".create_guid()."',
'".date("Y-m-d H:i:s")."',
'".$current_user->id."',
'".$prawa_id[$p]['id']."',


'".$lewa_id[$l]['id']."',
        '".abs($lewa_id[$l]['left'])."'
)
");

                    } else {
                        $lewa_id[$l]['left']+=$prawa_id[$p]['left'];
                        $prawa_id[$p]['left']+=abs($prawa_id[$p]['left']);
                        echo "po : ".$prawa_id[$p]['left']." ".$lewa_id[$l]['left']."\n";
                        $prawa_id[$p]['used']=1;
                         $db->query("update ecmtransactions set settled=1 where id='".$prawa_id[$p]['id']."'");
                        echo "update ecmtransactions set settled=1 where id='".$prawa_id[$p]['id']."'";
                        echo "
INSERT INTO ecmtransactions_rel VALUES (
'".create_guid()."',
'".date("Y-m-d H:i:s")."',
'".$current_user->id."',
'".$prawa_id[$p]['id']."',


'".$lewa_id[$l]['id']."',
        '".abs($prawa_id[$p]['value'])."'
)";
                     $db->query("
INSERT INTO ecmtransactions_rel VALUES (
'".create_guid()."',
'".date("Y-m-d H:i:s")."',
'".$current_user->id."',
'".$prawa_id[$p]['id']."',


'".$lewa_id[$l]['id']."',
        '".abs($prawa_id[$p]['value'])."'
)");  
                        continue;
                    }
                }
            }
        }
  
}

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 Saas SystemS 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,$email_us,$text){
   //ini_set('display_errors',1);
   
	
	    include 'modules/EcmPaymentStates/interestModel.php';
    $m= new interestModel(); 

    
    global $current_user;
    
    $db=$GLOBALS['db'];
    

         
         
       // 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
    
    
        require_once('modules/EcmSysInfos/EcmSysInfo.php');
        
        $EcmSysInfo = new EcmSysInfo();
        $email=$EcmSysInfo->getEmailSettings();
        $cc=explode(':',$email['value1']);
        if($email['value1']!='' && $email['value2']!='' && $email['value3']!=''){
            global $sugar_config,$current_user;
            $mailClassS->isSMTP (); // Set mailer to use SMTP
            $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
            $mailClassS->Port = $cc[1]; // Set the SMTP port number - 587 for
            if($email['value4']!=''){
                $mailClassS->Sender=$email['value4'];
                 $mailClassS->From =$email['value4'];
                if(!empty($email['value6'])){
                	 $mailClassS->AddReplyTo($email['value6'],$EcmSysInfo->getName());
                }
            } else {
                $mailClassS->Sender=$email['value2'];
                 $mailClassS->From =$email['value2'];
                if(!empty($email['value6'])){
                	 $mailClassS->AddReplyTo($email['value6'], $EcmSysInfo->getName());
                }
            }
            $mailClassS->FromName =$EcmSysInfo->getName();
            $mailClassS->WordWrap = 50; // Set word wrap to 50 characters  
        } else {
            global $sugar_config,$current_user;
            $mailClassS->isSMTP (); // Set mailer to use SMTP
            $mailClassS->Host = $sugar_config['sendMail_host']; // Specify main and backup server
            $mailClassS->SMTPAuth = true; // Enable SMTP authentication
            $mailClassS->Username = $sugar_config['sendMail_username'];
            $mailClassS->Password = $sugar_config['sendMail_password'];
            $mailClassS->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
            $mailClassS->Port = 587; // Set the SMTP port number - 587 for
            $mailClassS->Sender=$sugar_config['sendMail_from'];
            $mailClassS->From =$sugar_config['sendMail_from'];
            $mailClassS->FromName =$EcmSysInfo->getName();
            $mailClassS->WordWrap = 50; // Set word wrap to 50 characters
        }
        //$mailClassS->SMTPDebug=2;

        // get email from accounts
        $sea = new SugarEmailAddress;
        // Grab the array of addresses
        
        
        $addresses = $sea->getAddressesByGUID($parent_id, 'Accounts');
        $found=0;
		foreach( $addresses as $key=>$value){
			if($value['email_address']==$email_us){
				$found=1;
			}
		}
		$email_num=count($addresses)+1;
		$n='email'.$email_num;
		if($found==0){
			$acc= new Account ();
			$acc->retrieve($parent_id);
			$acc->$n=$email_us;
			$acc->save();
			
		}
        	
       // $mailClassS->addAddress ($addresses[0]['email_address']);
      
        $mailClassS->addAddress ($email_us);
        
        // set sender

    
       // $mailClassS->WordWrap = 50; // Set word wrap to 50 characters
    
        $mailClassS->isHTML ( true ); // Set email format to HTML
    
        $mailClassS->Subject = 'Dokument od '.$EcmSysInfo->getName();
   
    
        $mailClassS->Body = $text;
        // załącznik
        $path=$m->makeMonit($ids);
       
        if(file_exists('/var/www/html/system/'.$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/system/'.$path);
                echo '-1';
            } else {
                unlink('/var/www/html/system/'.$path);
                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(abs(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) 
		$db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$id'");
//ma 
	$res = $db->fetchByAssoc($db->query("
			SELECT (t.value-sum(abs(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)
		$db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$payment'");
	echo '1';
	return; 
}

function createRelationM($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
    if($value>0){
    $res = $db->fetchByAssoc($db->query("
    SELECT (abs(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'
    "));
	if ($res['unsettled']==0)
	        $db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$id'");
	        //ma
	        $res = $db->fetchByAssoc($db->query("
	        SELECT (abs(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)
		$db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$payment'");
		
    } else {
        $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'
                "));
        if ($res['unsettled']==0)
            $db->query("UPDATE ecmtransactions SET settled='1' WHERE id='$id'");
            //ma
            $res = $db->fetchByAssoc($db->query("
            SELECT (abs(t.value)-sum(abs(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)
                $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'");
		
	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'");

	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;
}