<?php
ini_set('log_errors', true);
ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log');

include('ipnlistener.php');

//Mail
require_once('../config.php');
require_once('../../db.php');
require '../libraries-bgo/phpmail/class.phpmailer.php';
$site_url = SITE;

$listener = new IpnListener();

/*
To post using the fsockopen() function rather than cURL, use:
*/

$listener->use_curl = false;


try {
    $listener->requirePostMethod();
    $verified = $listener->processIpn();
}
catch (Exception $e) {
    error_log($e->getMessage());
    exit(0);
}

// assign posted variables to local variables
$item_name        = mysqli_escape_string($conn, $_POST['item_name']);
$item_number      = mysqli_escape_string($conn, $_POST['item_number']);
$payment_status   = mysqli_escape_string($conn, $_POST['payment_status']);
$pageurl 		  = mysqli_escape_string($conn, $_POST['custom']);
$roompricetotal   = mysqli_escape_string($conn, $_POST['mc_gross']);
$payment_currency = mysqli_escape_string($conn, $_POST['mc_currency']);
$txn_id           = mysqli_escape_string($conn, $_POST['txn_id']);
$receiver_email   = mysqli_escape_string($conn, $_POST['receiver_email']);
$payer_email      = mysqli_escape_string($conn, $_POST['payer_email']);

// other variables
$message = mysqli_escape_string($conn, $_POST['custom']);
$name    = mysqli_escape_string($conn, $_POST['first_name']);
$surname = mysqli_escape_string($conn, $_POST['last_name']);
$city    = mysqli_escape_string($conn, $_POST['address_city']);
$country = mysqli_escape_string($conn, $_POST['address_country']);
$address = mysqli_escape_string($conn, $_POST['address_street']);
$city    = mysqli_escape_string($conn, $_POST['address_city']);
$date    = date('d-m-Y');

$posted_data = print_r($_POST,true);
file_put_contents('IPN_data.txt',$posted_data);

if ($verified) {
    
    //mail('your@email.com', 'Verified', $listener->getTextReport());
    
    $check_transaction_id = mysqli_query($conn, "SELECT * FROM itineraries WHERE itinerary_id = '$item_number' ");
    $tot_transaction_id   = mysqli_num_rows($check_transaction_id);
    $reservationData      = mysqli_fetch_array($check_transaction_id);
    
    //Variables
    $itinerario_id   = $reservationData['itinerario_id'];
    $checkin         = $reservationData['check_in_date'];
    $checkout        = $reservationData['check_out_date'];
    $room_type_id    = $reservationData['room_type_id'];
    $total_adults    = $reservationData['total_adults'];
    $total_children  = $reservationData['total_children'];
    $firstname0      = $reservationData['first_name_owner'];
    $lastname0       = $reservationData['last_name_owner'];
    $phone           = $reservationData['phone_owner'];
    $email           = $reservationData['email_owner'];
    $guestsroom      = $total_adults + $total_children;
    //Room Type Name
    $hotel_rooms     = mysqli_query($conn, "SELECT * FROM hotel_room_type WHERE room_type_id = '$room_type_id' ");
    $hotel_roomsData = mysqli_fetch_array($hotel_rooms);
    //Variables
    $room_name       = $hotel_roomsData['room_type_name'];
    
    if ($tot_transaction_id > 0) {
        
        
        mysqli_query($conn, "UPDATE transactions SET operator_transaction_id = '$txn_id', pp_payment = 'YES', cardholder_first_name = '$name', cardholder_last_name = '$surname', country = '$country', city = '$city', address = '$address', precio_total = '$roompricetotal', auth_code = '1', message = 'Completed', pp_email = '$payer_email' WHERE itinerario_id = '$item_number'");
        
        //Email Reservation Aditional Admin Emails Loop
		$email_notifications = mysqli_query($conn, "SELECT * FROM email_recipients");
		
		//Email Reservation
		$email_recipients = mysqli_query($conn, "SELECT * FROM email_recipients WHERE id = 1");
		$email_Data       = mysqli_fetch_array($email_recipients);
		
		//Variables
		$recipient_email = $email_Data['email_address'];
		$site_name       = $email_Data['site_name'];
		$reply_email     = $email_Data['reply_email'];
		$from_email      = $email_Data['from_email'];
		
		//sumbission data
		$ipaddress = $_SERVER['REMOTE_ADDR'];
		$date      = date('d/m/Y');
		$time      = date('H:i:s');
        
        
        //Admin Email DATA
        $admin_mail     = mysqli_query($conn, "SELECT * FROM email_template WHERE email_type = 'new_booking_paypal' ");
        $admin_mailData = mysqli_fetch_array($admin_mail);
        //Variables
        $string         = $admin_mailData['email_message'];
        $subjectmail    = $admin_mailData['email_subject'];
        $pattern        = '/{(\w+)}/i';
        $replacement    = "$$1";
        $msnAdminbody   = preg_replace($pattern, $replacement, $string);
        eval("\$msnAdminbody = \"<html><body> " . $msnAdminbody . " </body></html>\";");
        
        //Client Email DATA
        $client_mail       = mysqli_query($conn, "SELECT * FROM email_template WHERE email_type = 'booking_request_payment' ");
        $client_mailData   = mysqli_fetch_array($client_mail);
        //Variables
        $clientemsn        = $client_mailData['email_message'];
        $subjectmailclient = $client_mailData['email_subject'];
        $pattern2          = '/{(\w+)}/i';
        $replacement2      = "$$1";
        $msnClientbody     = preg_replace($pattern2, $replacement2, $clientemsn);
        eval("\$msnClientbody = \"<html><body> " . $msnClientbody . " </body></html>\";");
        
        try {
            $mail = new PHPMailer(true); // New instance, with exceptions enabled
            $mail->IsSMTP(); // tell the class to use SMTP
            $mail->SMTPAuth   = true; // enable SMTP authentication
            $mail->SMTPSecure = 'ssl'; // need SSL or TLS
            $mail->Port       = 465; // set the SMTP server port
            $mail->Host       = 'smtp.gmail.com'; // SMTP server
            $mail->Username   = "hoteles@bookingo.net"; // SMTP server username
            $mail->Password   = "PASSWORD"; // SMTP server password
            $mail->IsSendmail(); // tell the class to use Sendmail
            //Send, Reply Email Adress
            $mail->AddReplyTo($reply_email, $site_name);
            $mail->From     = $from_email;
            $mail->FromName = $site_name;
            
            
            //Admin Mail
            while ($email_notifications_Data = mysqli_fetch_array($email_notifications)) {
                $to = $email_notifications_Data['email_address'];
                $mail->AddAddress($email_notifications_Data['email_address']);
            }
			
            $mail->Subject  = $subjectmail;
            $mail->AltBody  = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
            $mail->WordWrap = 80; // set word wrap
            $mail->MsgHTML($msnAdminbody);
            $mail->IsHTML(true); // send as HTML
            $mail->Send();
            $mail->ClearAddresses();
            
            
            //Client Mail
            $toClient = $email;
            
            $mail->AddAddress($toClient);
            $mail->Subject  = $subjectmailclient;
            $mail->AltBody  = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
            $mail->WordWrap = 80; // set word wrap
            $mail->MsgHTML($msnClientbody);
            $mail->IsHTML(true); // send as HTML
            $mail->Send();
            
        }
        catch (phpmailerException $e) {
            echo $e->errorMessage();
        }
        
    }
    
    
} else {
    
    /*
    INVALID IPN
    */
    mail('webmaster@travelmarketing.com.gt', 'Invalid IPN', $listener->getTextReport());
}

?>