<?php

require_once "config.php";
require_once "libs/functions.php";

require_once "libs/Http.class.php";
require_once "libs/Record.class.php";
require_once "libs/Order.class.php";
require_once "libs/Smarty.class.php";
require_once "libs/IValidator.class.php";

$smarty = new Smarty;

$smarty->template_dir = "template";

$user = DB_USER;
$pass = DB_PASS;
$db =   DB_DATABASE;
$host = DB_HOST;
  
$conn = mysql_connect($host, $user, $pass);
if(!$conn); // error message
  mysql_select_db($db, $conn);

// global smarty assigns
$result = mysql_query("SELECT CountryId, Name FROM Countries ORDER BY Name", $conn);
while($res = mysql_fetch_array($result))
{
  $c = null;
  $c->id = $res["CountryId"];
  $c->name = $res["Name"];
  $cList[] = $c;
}

$cfg = GetTemplateVars();
$smarty->assign("countries", $cList);
$smarty->assign("prices", GetPrices());
$smarty->assign("config", $cfg);

$num = array();
for($i = 0; $i < 10; $i++)
  $num[] = $i;
$smarty->assign("numbers", $num);
//

$minHotel = strtotime(MINIMUM_LODGING_DAY);
$maxHotel = strtotime(MAXIMUM_LODGING_DAY);
$curHotel = $minHotel;
while($curHotel <= $maxHotel)
{
  $day = null;
  $day->time = $curHotel;
  $day->shortFormat = date("F jS", $curHotel);
  $day->longFormat = date("l, F jS, Y", $curHotel);
  $hotelDays[] = $day;  
  $curHotel = strtotime("+1 day", $curHotel);
}

$smarty->assign("firstHotelDay", 0);
$smarty->assign("lastHotelDay", sizeof($hotelDays) - 1);
$smarty->assign("hotelDays", $hotelDays);

$minPark = strtotime(MINIMUM_PARKING_DAY);
$maxPark = strtotime(MAXIMUM_PARKING_DAY);
$curPark = $minPark;
while($curPark <= $maxPark)
{
  $day = null;
  $day->time = $curPark;
  $day->shortFormat = date("F jS", $curPark);
  $day->longFormat = date("l, F jS, Y", $curPark);
  $parkDays[] = $day;  
  $curPark = strtotime("+1 day", $curPark);
}

$smarty->assign("firstParkingDay", 0);
$smarty->assign("lastParkingDay", sizeof($parkDays) - 1);
$smarty->assign("parkingDays", $parkDays);

if(isset($_POST["submit"]))
{
  // Step 2.
  $record = Record::Create($_POST);
  
  $validators = array( 
	new NameValidator,
	new GenderValidator,
    new PhoneValidator,
    new FaxValidator,
	new OrganizationValidator,
    new AddressValidator,
    new CountryValidator,
    new CityValidator,
	new LocationValidator,
	new DinnerValidator,
	new EmailValidator,
	new ParkingValidator,
	new PhoneValidator,
	new RoomValidator,
	new ZipValidator
  );
  
  foreach($validators as $validator)
  {
    $r = $validator->Validate($record);
    if($r->IsError)
    {
      $error = $r->Message;
      break;
    }
    elseif($r->IsWarning)
      $warnings[] = $r->Message;
  }
  
  $price = Calculate($record);
  $smarty->assign("order", $price);
  
  $smarty->assign("recordStateName", GetStateName($record->State, $conn));
  $smarty->assign("recordCountryName", GetCountryName($record->Country, $conn));
  
  $smarty->assign("record", $record);
  if(!isset($error))
    $smarty->display("confirmation.tpl");
  else 
  {
    $smarty->assign("errorMessage", $error);
	
    $provinces = GetProvinces($record->Country, $conn);
    $smarty->assign("provinces", $provinces);
	
    $smarty->display("information.tpl");
  }
}
else if(isset($_POST["confirm"]))
{
  // Step 3.
  $record = Record::Create($_POST);
  
  $result = $record->Save($conn);
  if($result === true)
  {
	$order = Order::Create($record);

    // Now prepare payment link for AIS.  Request a GUID from AIS:
    $http_client = new Http;
    $http_client->timeout = 0;
    $http_client->data_timeout = 0;
    $http_client->debug = false;
    $http_client->html_debug = true;

    $url = PAYMENT_GUID_REQUEST_URL;

    $error = $http_client->GetRequestArguments($url, $form);
    $form["RequestMethod"] = "POST";

	  $form["PostValues"] = array(
	    "MerchantID"      => MERCHANT_ID,
	    "OrderID"         => $order->Id,
	    "MaxAmount"       => 0, // not sure if this is required.
	    "FixedAmount"     => $order->AmountOwed,
	    "Description"     => FS_DESC,
	    "NCRCode"         => NCR_CODE,
	    "ReturnURL"       => "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/transResult.php",
	    "CancelURL"       => "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/transResult.php",
	    "POSTURL"         => "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/post.php",
	    "UserField1"      => $order->RandomKey,
	    "BackGroundColor" => "#FFFFFF"
	  );

	  $error = $http_client->Open($form);

	  if(empty($error))
	  {
	    $error = $http_client->SendRequest($form);
	    if(empty($error))
	    {
	      $error = $http_client->ReadReplyHeaders($headers);
	      if(empty($error))
	      {
	        $error = $http_client->ReadReplyBody($body, 1000);
	        $guid = explode("\r\n", $body);
	        if($guid[0] == "GOOD") 
	          $payUrl = PAYMENT_GATEWAY_URL . $guid[1];
	        else 
	          $error = "Payment Server is Out of Service.  Response:" . $body;
			// Everything's OK, put order into the database.
			if(empty($error))
  			{
	          $save = $order->Save($conn);
			  if($save !== true)
			    $error = $save;
            }  
	      }
	    }
	    $http_client->Close();
	  }
  }
  else
  {
    $error = "MySQL Error: " . $result;
  }
  
  $smarty->assign("record", $record);
  if(strlen($error) > 0)
  {
    // error message
    $smarty->assign("errorMessage", $error);
    $smarty->display("confirmation.tpl");
  }
  else
  {
    $smarty->assign("PaymentUrl", $payUrl);
    $smarty->display("payment.tpl");
  }
  // end
}
elseif(isset($_POST["retry"]))
{
  $order = Order::Load($_POST["RetryOrder"], $conn);
  $record = Record::Load($order->RecordId, $conn);
  $smarty->assign("record", $record);

  // create a new order.
  $newOrder = Order::Create($record);
  
  // get a new GUID from payment
  $guid = GetGUID(PAYMENT_GUID_REQUEST_URL, $newOrder);
  if($guid->result)
  { 
    // create the Payment URL
    $smarty->assign("PaymentUrl", PAYMENT_GATEWAY_URL . $guid->return);
    $r = $newOrder->Save($conn);
  }
  $smarty->display("payment.tpl");
}
elseif(isset($_POST["back"]))
{
  $record = Record::Create($_POST);

  $provinces = GetProvinces($record->Country, $conn);
  $smarty->assign("provinces", $provinces);

  $smarty->assign("record", $record);
  $smarty->display("information.tpl");
}
else
{
  // Step 1.
  $smarty->display("information.tpl");
}

mysql_close($conn);

?>
