<?php
include "ip.php";
require_once('../../db.php');
//Config Data
require_once('../config.php');
$site_url       = mysqli_escape_string($conn, SITE."reservation.php");

require 'phpmail/class.phpmailer.php';
include('class/encryptor.php');
function createSalt()
{
    $string = md5(uniqid(rand(), true));
    return substr($string, 0, 8);
}
function puntos($ips)
{
    list($a, $b, $c, $d) = explode(".", $ips);
    return $a . $b . $c . $d;
}
function newdate($date)
{
    list($d, $m, $a) = explode("/", $date);
    return $a . "-" . $d . "-" . $m;
}
function daysDifference($endDate, $beginDate)
{
    $date_parts1 = explode("/", $beginDate);
    $date_parts2 = explode("/", $endDate);
    $start_date  = gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
    $end_date    = gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
    return $end_date - $start_date;
}
$ip             = GetUserIp();
$sesionip       = puntos($ip);
$salt           = createSalt();
$tiempo         = time();
$randomtransact = $sesionip . $tiempo . $salt;
$keyaccess      = createSalt();

$otacode   = mysqli_escape_string($conn, $_POST['otacode']);
$hotelid   = mysqli_escape_string($conn, $_POST['hotelid']);
$checkin   = mysqli_escape_string($conn, $_POST['checkin']);
$checkout  = mysqli_escape_string($conn, $_POST['checkout']);
$rooms     = mysqli_escape_string($conn, $_POST['rooms']);
$email     = mysqli_escape_string($conn, $_POST['email']);
$phone     = mysqli_escape_string($conn, $_POST['phone']);
$workphone = mysqli_escape_string($conn, $_POST['workphone']);

$roomcode       = mysqli_escape_string($conn, $_POST['roomcode']);
$ratekey        = mysqli_escape_string($conn, $_POST['ratekey']);
$ratecode       = mysqli_escape_string($conn, $_POST['ratecode']);
$room_name      = mysqli_escape_string($conn, $_POST['room_name']);
$hotelname      = mysqli_escape_string($conn, $_POST['hotel_name']);
$taxfee         = mysqli_escape_string($conn, $_POST['taxfee']);
$roompricetotal = mysqli_escape_string($conn, $_POST['roompricetotal']);

//room1
$adults0       = mysqli_escape_string($conn, $_POST['adults1']);
$children0     = mysqli_escape_string($conn, $_POST['children1']);
$children0age0 = mysqli_escape_string($conn, $_POST['children1age1']);
$children0age1 = mysqli_escape_string($conn, $_POST['children1age2']);
$children0age2 = mysqli_escape_string($conn, $_POST['children1age3']);
$firstname0    = mysqli_escape_string($conn, $_POST['firstname0']);
$lastname0     = mysqli_escape_string($conn, $_POST['lastname0']);
$smokingpref0  = mysqli_escape_string($conn, $_POST['smokingpref0']);

//room2
$adults1       = mysqli_escape_string($conn, $_POST['adults2']);
$children1     = mysqli_escape_string($conn, $_POST['children2']);
$children1age0 = mysqli_escape_string($conn, $_POST['children2age1']);
$children1age1 = mysqli_escape_string($conn, $_POST['children2age2']);
$children1age2 = mysqli_escape_string($conn, $_POST['children2age3']);
$firstname1    = mysqli_escape_string($conn, $_POST['firstname1']);
$lastname1     = mysqli_escape_string($conn, $_POST['lastname1']);
$smokingpref1  = mysqli_escape_string($conn, $_POST['smokingpref1']);

//room3
$adults2       = mysqli_escape_string($conn, $_POST['adults3']);
$children2     = mysqli_escape_string($conn, $_POST['children3']);
$children2age0 = mysqli_escape_string($conn, $_POST['children3age1']);
$children2age1 = mysqli_escape_string($conn, $_POST['children3age2']);
$children2age2 = mysqli_escape_string($conn, $_POST['children3age3']);
$firstname2    = mysqli_escape_string($conn, $_POST['firstname2']);
$lastname2     = mysqli_escape_string($conn, $_POST['lastname2']);
$smokingpref2  = mysqli_escape_string($conn, $_POST['smokingpref2']);

//room4
$adults3       = mysqli_escape_string($conn, $_POST['adults4']);
$children3     = mysqli_escape_string($conn, $_POST['children4']);
$children3age0 = mysqli_escape_string($conn, $_POST['children4age1']);
$children3age1 = mysqli_escape_string($conn, $_POST['children4age2']);
$children3age2 = mysqli_escape_string($conn, $_POST['children4age3']);
$firstname3    = mysqli_escape_string($conn, $_POST['firstname3']);
$lastname3     = mysqli_escape_string($conn, $_POST['lastname3']);
$smokingpref3  = mysqli_escape_string($conn, $_POST['smokingpref3']);

//sum guest
$totalAdults   = $adults0 + $adults1 + $adults2 + $adults3;
$totalChildren = $children0 + $children1 + $children2 + $children3;


$special_requests = mysqli_escape_string($conn, $_POST['special-requests-1']);
$country          = mysqli_escape_string($conn, $_POST['country']);
$state            = mysqli_escape_string($conn, $_POST['state']);
$billaddress      = mysqli_escape_string($conn, $_POST['billaddress']);
$zip              = mysqli_escape_string($conn, $_POST['zip']);
$payment          = mysqli_escape_string($conn, $_POST['payment']);
$city             = mysqli_escape_string($conn, $_POST['city']);
$cardfirstname    = mysqli_escape_string($conn, $_POST['cardfirstname']);
$cardlastname     = mysqli_escape_string($conn, $_POST['cardlastname']);
$cardtype         = mysqli_escape_string($conn, $_POST['cardtype']);
$cardnumber       = mysqli_escape_string($conn, $_POST['cardnumber']);
$card_exp_month   = mysqli_escape_string($conn, $_POST['credit-card-exp-month']);
$card_exp_year    = mysqli_escape_string($conn, $_POST['credit-card-exp-year']);
$securitycode     = mysqli_escape_string($conn, $_POST['securitycode']);

//Encrypt the Data
$nocard = $encryptor->Encrypt($cardnumber);
$codeno = $encryptor->Encrypt($securitycode);

//Card Name Display
if ($cardtype == 'AX') {
    $cardname = 'American Express';
} elseif ($cardtype == 'CA') {
    $cardname = 'Master Card';
} elseif ($cardtype == 'CU') {
    $cardname = 'China UnionPay';
} elseif ($cardtype == 'DC') {
    $cardname = 'DINERS CLUB';
} elseif ($cardtype == 'DS') {
    $cardname = 'Discover';
} elseif ($cardtype == 'DS') {
    $cardname = 'JCB';
} elseif ($cardtype == 'VI') {
    $cardname = 'Visa';
}
//Saving data before the transaction
$fcid = newdate($checkin);
$fcod = newdate($checkout);

//Preparing data to register in bookingo
$infoArray['hotel_id']                 = $hotelid;
$infoArray['checkIn']                  = $checkin;
$infoArray['checkOut']                 = $checkout;
$infoArray['rateKey']                  = $ratekey;
$infoArray['roomTypeCode']             = $roomcode;
$infoArray['rateCode']                 = $ratecode;
$infoArray['chargeableRate']           = $roompricetotal;
$infoArray['numberOfRooms']            = $rooms;
//ROOM 0;
$infoArray['room-0-adult-total']       = $adults0;
$infoArray['room-0-child-total']       = $children0;
$infoArray['room-0-child-0-age']       = $children0age0;
$infoArray['room-0-child-1-age']       = $children0age1;
$infoArray['room-0-child-2-age']       = $children0age2;
$infoArray['room-0-firstName']         = $firstname0;
$infoArray['room-0-lastName']          = $lastname0;
$infoArray['room-0-smokingPreference'] = $smokingpref0;
//ROOM 1;
$infoArray['room-1-adult-total']       = $adults1;
$infoArray['room-1-child-total']       = $children1;
$infoArray['room-1-child-0-age']       = $children1age0;
$infoArray['room-1-child-1-age']       = $children1age1;
$infoArray['room-1-child-2-age']       = $children1age2;
$infoArray['room-1-firstName']         = $firstname1;
$infoArray['room-1-lastName']          = $lastname1;
$infoArray['room-1-smokingPreference'] = $smokingpref1;
//ROOM 2;
$infoArray['room-2-adult-total']       = $adults2;
$infoArray['room-2-child-total']       = $children2;
$infoArray['room-2-child-0-age']       = $children2age0;
$infoArray['room-2-child-1-age']       = $children2age1;
$infoArray['room-2-child-2-age']       = $children2age2;
$infoArray['room-2-firstName']         = $firstname2;
$infoArray['room-2-lastName']          = $lastname2;
$infoArray['room-2-smokingPreference'] = $smokingpref2;
//ROOM 3;
$infoArray['room-3-adult-total']       = $adults3;
$infoArray['room-3-child-total']       = $children3;
$infoArray['room-3-child-0-age']       = $children3age0;
$infoArray['room-3-child-1-age']       = $children3age1;
$infoArray['room-3-child-2-age']       = $children3age2;
$infoArray['room-3-firstName']         = $firstname3;
$infoArray['room-3-lastName']          = $lastname3;
$infoArray['room-3-smokingPreference'] = $smokingpref3;

$infoArray['contact_email']      = $email;
$infoArray['cardFirstName']      = $cardfirstname;
$infoArray['cardLastName']       = $cardlastname;
$infoArray['contact_phone']      = $phone;
$infoArray['contact_workPhone']  = $phone;
$infoArray['cardType']           = $cardtype;
$infoArray['cardNumber']         = $cardnumber;
$infoArray['cardSecurity']       = $securitycode;
$infoArray['cardExpMonth']       = $card_exp_month;
$infoArray['cardExpYear']        = $card_exp_year;
$infoArray['billing_address']    = $billaddress;
$infoArray['billing_city']       = $city;
$infoArray['billing_state']      = $state;
$infoArray['billing_country']    = $country;
$infoArray['billing_postalCode'] = $zip;

//Creating the inventory
mysqli_query($conn, "INSERT INTO itineraries (check_in_date,check_out_date,ota_code,hotel_id,room_type_id,rooms_number,total_adults,total_children,total_amount,first_name_owner,last_name_owner,phone_owner,email_owner,key_time,key_access,itinerary_date) VALUES('$fcid', '$fcod', '$otacode', '$hotelid', '$roomcode', '$rooms', '$totalAdults', '$totalChildren', '$roompricetotal', '$firstname0', '$lastname0', '$phone', '$email', '$randomtransact', '$keyaccess', now() )");
$itinerario_id = mysqli_insert_id($conn);

//Creating the transaction
mysqli_query($conn, "INSERT INTO transactions (itinerario_id, hotel_id, cardholder_first_name, cardholder_last_name, country, state, city, address, zipcode, phone, email, ip, random_transaction, cantidad, precio_total, type_transaction, transaction_process, created, void, message) VALUES('$itinerario_id', '$hotelid', '$cardfirstname', '$cardlastname', '$country ', '$state', '$city', '$billaddress', '$zip', '$phone', '$email', '$ip', '$randomtransact', '$rooms', '$roompricetotal', 'sale', '2', now(), 'NO', 'Transaction Started')");
$transaction_last_id = mysqli_insert_id($conn);
$transaction_id      = $transaction_last_id;

//Updating the availability of each room
$fiava = strtotime($fcid);
$diava = date('d', $fiava);
$miava = date('m', $fiava);
$yiava = date('Y', $fiava);
$foava = strtotime($fcod);
$doava = date('d', $foava);
$moava = date('m', $foava);
$yoava = date('Y', $foava);
$intday_ava = daysDifference($checkout, $checkin);
$fechaavainicial = newdate($checkin);
//obteniendo el inventario actual
$roominventory = mysqli_query($conn, "SELECT room_type_inventory FROM hotel_room_type WHERE room_type_id = '$roomcode'");
$roominventoryData = mysqli_fetch_array($roominventory);
$inventariodefault = $roominventoryData['room_type_inventory'];

for ( $interva = 1 ; $interva <= $intday_ava ; $interva ++)      
    {
     $undia = $interva;
     $fechaavasiguiente = mktime(0,0,0, $miava,$diava,$yiava) + $undia * 24 * 60 * 60;
     $fechaavasalida=date("Y-m-d",$fechaavasiguiente);
	 //verificacion diaria
	 $veriday = mysqli_query($conn, "SELECT * FROM booking_check_avilability WHERE check_in_date = '$fechaavainicial' AND check_out_date = '$fechaavasalida' AND room_type_id = '$roomcode'");
     $totalveriday= mysqli_num_rows($veriday);
	 $veridayData = mysqli_fetch_array($veriday);
	 $total_booked = $veridayData['total_room'] + $rooms;	
	 //echo '<br>';
	 $availability_id  = $veridayData['check_availability_id'];
	 //echo '<br>';
	 if ($totalveriday > 0){
        mysqli_query($conn, "UPDATE booking_check_avilability SET total_room = '$total_booked' WHERE check_availability_id = '$availability_id' ");
     }else {
	    mysqli_query($conn, "INSERT INTO booking_check_avilability (check_in_date,check_out_date,room_type_id,total_room) VALUES('$fechaavainicial','$fechaavasalida','$roomcode','$rooms')");	 
	 }
	 $fechaavainicial = $fechaavasalida;
  }


//Creatingn the temporal booking
for ($jj = 1; $jj <= $rooms; $jj++) {
    $estadoroom    = $jj - 1;
    $adultosroom   = $infoArray['room-' . $estadoroom . '-adult-total'];
    $kidsroom      = $infoArray['room-' . $estadoroom . '-child-total'];
    $guestsroom    = $adultosroom + $kidsroom;
    $firstnameroom = $infoArray['room-' . $estadoroom . '-firstName'];
    $lastnameroom  = $infoArray['room-' . $estadoroom . '-lastName'];
    mysqli_query($conn, "INSERT INTO booking_master (ota_priority, hotel_id, check_in_date, check_out_date, booking_date, room_type_id, total_guest, adults, kids, total_price, first_name_owner, last_name_owner, preferences_owner, email_owner, phone_owner, transaction_id, itinerary_id, booking_status, ip_address) VALUES('$otacode', '$hotelid', '$fcid', '$fcod', now(), '$roomcode', '$guestsroom', '$adultosroom', '$kidsroom', '$roompricetotal', '$firstnameroom', '$lastnameroom', '', '$email', '$phone', '$transaction_id', '$itinerario_id', '2', '$ip')");
}
$booking_id       = mysqli_insert_id($conn);
$numeroitinerario = $itinerario_id;
//Updating itinerary	
$checknumeric     = is_numeric($numeroitinerario);
if ($numeroitinerario > 0) {
    mysqli_query($conn, "UPDATE booking_master SET itinerary_approved = '$numeroitinerario', booking_status = '1' WHERE booking_id = '$booking_id' ");
    mysqli_query($conn, "UPDATE transactions SET completed = '1', success = '1' WHERE transaction_id = '$transaction_id' ");
    mysqli_query($conn, "UPDATE itineraries SET itinerary_status = '1' WHERE itinerary_id = '$itinerario_id' ");
    

if(isset($_POST['baseC'])) {
	$newcurrency =  mysqli_escape_string($conn, $_POST['baseC']);
	
/* READ VALUES AND MAKE CALCULATIONS */
@$base    = 'USD';
@$foreign = $newcurrency;
@$amount  = '1';

/* require class and create function */
require ('../querys/class.php');
function format($amount) { return round($amount); }

/* create object */
$fx = new exchange($base, $foreign);

/* echo the value */
$finaltotal = $fx->toForeign($amount);
	
} else {
	$newcurrency = 'USD';
	$finaltotal = '1';
}

if($newcurrency == 'USD') {
		$currencysymbol = '$';	
	} else {
		$currencysymbol = $newcurrency;
	}


    
    //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');
    
    if ($payment == 'hotel') {
        //Admin Email DATA
        $admin_mail     = mysqli_query($conn, "SELECT * FROM email_template WHERE email_type = 'booking_request_notification' ");
        $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 = 'new_booking_confirmed' ");
        $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();
        }
        header("Location: ../../confirmation.php?itinerary_id=$numeroitinerario&email_client=$email&rooms=$rooms&totaladults=$totalAdults&totalchildren=$totalChildren&gateway=In Hotel&baseC=$newcurrency");
    } else {
        header("Location: ../../paypal.php?itinerary_id=" . $numeroitinerario . "&hotel_name=" . $hotelname . "&email_client=" . $email . "&rooms=" . $rooms . "&totaladults=" . $totalAdults . "&totalchildren=" . $totalChildren);
    }
       
} else {
    header("Location: ../../checkout.php?hotel_id=$hotelid&hotel_name=$hotelname&room_code=$roomcode&room_name=$room_name&room_price=$roompriceuni&room_price_total=$roompriceuni&taxfee=$taxfee&ratekey=$ratekey&ratecode=$ratecode&ota_priority=EX&allroomsprice=$roompricetotal&cancelpolicy=$cancelpolicy&$datosbusqueda&baseC=$newcurrency");
}
?>