<?php
	#################################################################
	##  WHMX Billing system for cPanel / WHM					   ##
	##-------------------------------------------------------------##
	##  Version: 1.00 - ENVATO MARKET                              ##
	##-------------------------------------------------------------##
	##  Author: Gianck Luiz obviosistemas@gmail.com         	   ##
	##-------------------------------------------------------------##
	##  Copyright ©2016 . All rights reserved.	                   ##
	##-------------------------------------------------------------##
	#################################################################
	
    session_start();
    ob_start();
    ini_set("allow_url_fopen", 1);
    date_default_timezone_set("America/Sao_Paulo");
    header("Content-Type: text/html; charset=ISO-8859-1", true);
    require_once("../adm/config/conexao.class.php");
    require_once("../adm/config/crud.class.php");
    
    $con = new conexao(); 
    $con->connect(); 
    
    $dbconfig = mysql_query("SELECT * FROM config WHERE id = '1'");
    $config = mysql_fetch_array($dbconfig);
    
    require_once("../adm/config/mail/class.phpmailer.php");
    require_once("../adm/whm.class.php");

    if(isset($_POST['notificationType']) && $_POST['notificationType'] == 'transaction'){
    //Todo resto do código iremos inserir aqui.
 
    $email = $config['pagseguro'];
    $token = $config['token_pagseguro'];
 
    $url = 'https://ws.pagseguro.uol.com.br/v2/transactions/notifications/' . $_POST['notificationCode'] . '?email=' . $email . '&token=' . $token;
 
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $transaction= curl_exec($curl);
    curl_close($curl);
 
    if($transaction == 'Unauthorized'){
        //Insira seu código avisando que o sistema está com problemas, sugiro enviar um e-mail avisando para alguém fazer a manutenção
    echo "Não Autorizado";
        exit;//Mantenha essa linha
    }
	
    $transaction = simplexml_load_string($transaction);


    $codigo = $transaction->code;
    $status = $transaction->status; 
    $registerID = $transaction->reference; 
    $cliente_nome = $transaction->sender->name;
    $cliente_email = $transaction->sender->email;
    $cliente_endereco = $transaction->shipping->address->street;
    $cliente_numero = $transaction->shipping->address->number;
    $cliente_complemento = $transaction->shipping->address->complement;
    $cliente_bairro = $transaction->shipping->address->district;
    $cliente_cidade = $transaction->shipping->address->city;
    $cliente_estado = $transaction->shipping->address->state;
    $cliente_cep = $transaction->shipping->address->postalcode;
    $valor_frete = $transaction->shipping->cost;
    $tipo_frete = $transaction->shipping->type;
    $valor_pedido = $transaction->grossAmount;
    $tipopagamento = $transaction->paymentmethod->type;

    if($transaction->status == "3"){

    $crud = new crud('invoices'); // Table
		$crud->atualizar("status='confirmed',tp='2'", "invoice='$registerID'");
		
		// UPTADE
		$invoices = mysql_query("SELECT * FROM invoices WHERE invoice = '$registerID'");
		$inv = mysql_fetch_array($invoices);
		$idr = $inv['request'];
		$customer = $inv['customer'];
		
		$crud = new crud('requests'); // Table
		$crud->atualizar("status='S'", "id='$idr'");
		
		$query = mysql_query("SELECT * FROM requests_tbl WHERE request = '$idr'");
 		while($result = mysql_fetch_array($query)){ 
		$idres = $result['id'];
		
		$accts = mysql_query("SELECT * FROM accounts WHERE request = '$idres'");
		$acc = mysql_fetch_array($accts);	
		$accr = mysql_num_rows($accts);	
		if($accr > '0') {
		$crud = new crud('accounts'); // Table
		$crud->atualizar("status='S'", "request='$idres'");
		
		$product = $result['product'];
		$tbprds = mysql_query("SELECT * FROM products WHERE id = '$product'");
	    $tbproduct = mysql_fetch_array($tbprds);
	    $idsrvc = $tbproduct['server'];
		    $dbcs = mysql_query("SELECT * FROM servers WHERE id = '$idsrvc'");
			$srv = mysql_fetch_array($dbcs);
			$whmpwd = $srv['pwd'];
			$whmuser = $srv['user'];
			$whmdomain = $srv['domain'];
			$acctUser = $acc['acctuser'];
			
			$WHM = new WHM( false , $whmdomain, $whmuser, $whmpwd);
			
			$infowhm = $WHM->unsuspend_account($acctUser); 
			if($infowhm) { 
			}
		
	    } else { 
			
		// PRODUCTS
		if($result['product'] > '0') {
		$domain = $result['domain'];
		$tld = $result['tld'];
		$customer = $result['customer'];
			
		$product = $result['product'];
		$tbprds = mysql_query("SELECT * FROM products WHERE id = '$product'");
	    $tbproduct = mysql_fetch_array($tbprds);
			
			if($tbproduct['automation'] == '3') {
			$idsrvc = $tbproduct['server'];
			$dbcs = mysql_query("SELECT * FROM servers WHERE id = '$idsrvc'");
			$srv = mysql_fetch_array($dbcs);
			$whmpwd = $srv['pwd'];
			$whmuser = $srv['user'];
			$whmdomain = $srv['domain'];
	
			$WHM = new WHM( false , $whmdomain, $whmuser, $whmpwd);
			
			$rg = rand(111,999);
			$acctDomain = $domain.''.$tld;
			$acctUser = $domain.''.$rg;
			$acctPass = geraSenha(10, true, true, true);
			$acctPackg = $tbproduct['package'];
			$accDate = date('Y-m-d');
			$acctEmail = '';
			$infowhm = $WHM->create_account($acctDomain,$acctUser,$acctPass,$acctEmail,$acctPackg);	
			if($infowhm) { 
			$crud = new crud('accounts');  // table
			$crud->inserir("request,customer,server,package,domain,acctuser,acctpass,date,status", "'$idres','$customer','$idsrvc','$acctPackg','$acctDomain','$acctUser','$acctPass','$accDate','S'");
		    // EMAIL 
		    $customers = mysql_query("SELECT * FROM customers WHERE id = '$customer'");
		    $customer = mysql_fetch_array($customers);
		    
			$emailcustomer = $customer['email'];
			$namecustomer = $customer['name'];
			$passcustomer = base64_decode($customer['salt']);
			$srvdns1 = $srv['dns1'];
			$srvdns2 = $srv['dns2'];
			$email_template = $tbproduct['email_template'];
			
			$query_tpl = mysql_query("SELECT * FROM email_template WHERE id = '$email_template'");
			$template_mail = mysql_fetch_array($query_tpl);
			
			$mail = new PHPMailer();
			$mail->IsSMTP();		
			$mail->SMTPDebug = 0;		
			$mail->SMTPAuth = true;		
			$mail->IsHTML(true);
			$mail->Host = $config['smtp_host'];	
			$mail->Port = $config['smtp_port'];		
			$mail->Username = $config['smtp_user'];	
			$mail->Password = $config['smtp_pass'];	

			$mail->From = $template_mail['from_mail'];  
			$mail->FromName = $template_mail['name_from']; 

			$mail->AddAddress($emailcustomer);
			$mail->IsHTML(true); 
			$mail->CharSet = 'iso-8859-1'; 
			$mail->Subject  = $template_mail['subject']; 
			
			$corpoDoEmail = $template_mail['msg']; 
			$signature = $config['signature'];
			$logo = $config['logo'];
			$company = $config['company'];
			
			// MAIL Variables
			$corpoDoEmail = str_replace( '%EMAIL%', $emailcustomer, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%NOME%', $namecustomer, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%SENHA%', $passcustomer, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%CP_SENHA%', $acctPass, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%CP_LOGIN%', $acctUser, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%DNS1%', $srvdns1, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%DNS2%', $srvdns2, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%DOMINIO%', $acctDomain, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%SIGNATURE%', $signature, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%LOGO%', $logo, $corpoDoEmail );
			$corpoDoEmail = str_replace( '%COMPANY%', $company, $corpoDoEmail );
			
			
			// END Variables
			$mail->Body = $corpoDoEmail;
			$SendOK = $mail->Send();
			if ($SendOK) {
			}
		    
		    
		    }			
						
			}
			
			
		  } // END account
			
			
		}
		// End 
		

		} // END WHILE
		
		// SEND MAIL 
		$customers = mysql_query("SELECT * FROM customers WHERE id = '$customer'");
		$customer = mysql_fetch_array($customers);
		
		$name = $customer['name'];
		$email = $customer['email'];
		$cpf_cnpj = $customer['cpf_cnpj'];
		$address = $customer['address'];
		$city = $customer['city'];
		$passemail = base64_decode($customer['salt']);
		
		// SEND MAIL 
	
	$query_tpl = mysql_query("SELECT * FROM email_template WHERE id = '12'");
    $template_mail = mysql_fetch_array($query_tpl);
	
	$mail = new PHPMailer();
	$mail->IsSMTP();		
	$mail->SMTPDebug = 0;		
	$mail->SMTPAuth = true;		
	$mail->IsHTML(true);
	$mail->Host = $config['smtp_host'];	
	$mail->Port = $config['smtp_port'];		
	$mail->Username = $config['smtp_user'];	
	$mail->Password = $config['smtp_pass'];	

	$mail->From = $template_mail['from_mail'];  
	$mail->FromName = $template_mail['name_from']; 

	$mail->AddAddress($email);
	$mail->IsHTML(true); 
	$mail->CharSet = 'iso-8859-1'; 
	$mail->Subject  = $template_mail['subject']; 
	
	$corpoDoEmail = $template_mail['msg']; 
	$signature = $config['signature'];
	$logo = $config['logo'];
	$company = $config['company'];
	
	// MAIL Variables
    $corpoDoEmail = str_replace( '%NOME%', $name, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%SENHA%',  $passemail, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%EMPRESA%',  $company, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%CPFCNPJ%',  $cpf_cnpj, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%ENDERECO%',  $address, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%CIDADE%',  $city, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%PEDIDO%',  $registerID, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%EMAIL%',  $email, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%SIGNATURE%',  $signature, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%LOGO%',  $logo, $corpoDoEmail );
    
    // END Variables
	$mail->Body = $corpoDoEmail;
	$SendOK = $mail->Send();
	$mail->ClearAllRecipients();
	$mail->ClearAttachments();
	if ($SendOK) {
	}
		
		
		
}
    

	unset($_SESSION["zim"]);
    

}
