<?php
/**
 * @file
 *   Module file for testing moneybird module - basic testing only
 *   Written by Kevin and Cedric (E-nova)
 */

class MoneybirdFunctionalTest extends UbercartTestHelper {

  var $moneybird_emailaddress =  'kevin.muller@enova-tech.net';
  var $moneybird_password =  'knowledge';
  var $moneybird_client = 'drupal';
  
  public static function getInfo() {
    return array(
        'name' => 'Moneybird Tests',
        'description' => 'Unit Tests for moneybird',
        'group' => 'Moneybird',
    );
  }

  function setUp() {
    parent::setUp(array('moneybird'));

    variable_set('moneybird_emailaddress', $this->moneybird_emailaddress);
    variable_set('moneybird_password', $this->moneybird_password);
    variable_set('moneybird_client', $this->moneybird_client);
    
    module_load_include('php', 'moneybird', 'moneybird_php_api/ApiConnector');
    spl_autoload_register('Moneybird\ApiConnector::autoload');
    $transport = new Moneybird\HttpClient();
    $transport->setAuth(
      variable_get('moneybird_emailaddress', ''), // put your username here
      variable_get('moneybird_password', '')  // put your password here
    );
    $connector = new Moneybird\ApiConnector(
      variable_get('moneybird_client', ''), // put your client name here (<...>.moneybird.nl)
      $transport,
      new Moneybird\XmlMapper() // create a mapper
    );
    $this->connector = $connector;
  }

  function testHookUcOrder() {
    // Test 1 : purchase a product as an anonymous user
    // Test 2 : purchase a product as an authenticated user
    $product = $this->createProduct();

    for ($i = 1; $i <= 2; $i++) {
      if ($i == 1) {
        $this->drupalLogout();
      }
      elseif ($i == 2) {
        $this->drupalLogin($this->adminUser); // Test number 2 : log on as admin
      }

      //$this->assertTrue(true, print_r($product, true));
      $this->drupalPost("node/1", array(), 'Add to cart');
      $this->drupalPost('cart', array(), 'Checkout');

      $edit = array();
      $edit = $this->populateCheckoutForm($edit);

      // Submit the checkout page.
      $this->drupalGet('cart/checkout');
      $this->assertText('Continue with checkout to complete payment.'); // Check that moneybird payment method is visible in the page

      $this->drupalPost('cart/checkout', $edit, t('Review order'));
      // Complete the review page.
      $this->drupalPost(NULL, array(), t('Submit order'));
      $order_id = db_query("SELECT order_id FROM {uc_orders} WHERE delivery_first_name = :name", array(':name' => $edit['panes[delivery][delivery_first_name]']))->fetchField();

      $mid = db_query("SELECT mid FROM {moneybird_orders} WHERE id = :order_id", array(':order_id' => $order_id))->fetchField();
      $this->assertTrue($mid != null, "mid should have a value stored in {moneybird_orders}. value is $mid");

      // Check that the contact exists and  is inserted in moneybird
      // 1) Get the contact muid from db
      $muid = db_query("SELECT MAX(mid) as mid FROM {moneybird_users}")->fetchField();
      $this->assertTrue($muid != null, "muid should have a value stored in {moneybird_users}. muid value is $muid");
      // 2) Get the contact bean from moneybird
      $contactService = $this->connector->getService('Contact');
      $contact = $contactService->getById($muid);
      $this->assertTrue($contact != null, 'contact retrieved from moneybird. content is ' . print_r($contact, true));
    }
  }

  function testSyncMoneybirdToDrupal() {
    // Test 1 : change of status

    // 1) we create a fake order
    $product = $this->createProduct();
    $this->drupalPost("node/1", array(), 'Add to cart');
    $this->drupalPost('cart', array(), 'Checkout');
    $edit = array();
    $edit = $this->populateCheckoutForm($edit);
    $this->drupalPost('cart/checkout', $edit, t('Review order'));
    $this->drupalPost(NULL, array(), t('Submit order'));
    $order_id = db_query("SELECT MAX(order_id) as order_id FROM {uc_orders}")->fetchField();
    $old_status = db_query("SELECT order_status FROM {uc_orders} WHERE order_id = :order_id", array(':order_id' => $order_id))->fetchField();
    $mid = db_query("SELECT mid FROM {moneybird_orders} WHERE id = :order_id", array(':order_id' => $order_id))->fetchField();
    // 2) we modify the invoice status
    $invoiceService = $this->connector->getService('Invoice');
    $invoice = $invoiceService->getById($mid);
    $invoice->setData(array('state' => 'paid'));
    $invoice->save($invoiceService);
    //sync_moneybird_to_drupal(); // This line currently generates bugs due to the payment method bug in the api
    $new_status = db_query("SELECT order_status FROM {uc_orders} WHERE order_id = :order_id", array(':order_id' => $order_id))->fetchField();
    $this->assertFalse($old_status == $new_status, "the hook should have updated the order status in db. old status = $old_status ; new status = $new_status");
  }

  function testPush() {

  }

  // Override populateCheckoutForm with our data, for custom tests
  /*function populateCheckoutForm($edit = array()) {
    foreach (array('billing', 'delivery') as $pane) {
      $prefix = 'panes[' . $pane . '][' . $pane;
      $key =  $prefix . '_country]';
      $country = empty($edit[$key]) ? variable_get('uc_store_country', 840) : $edit[$key];
      $zone_id = db_query_range('SELECT zone_id FROM {uc_zones} WHERE zone_country_id = :country ORDER BY rand()', 0, 1, array('country' => $country))->fetchField();
      $edit += array(
        $prefix . '_first_name]' => "d7test",
        $prefix . '_last_name]' => "d7test",
        $prefix . '_street1]' => $this->randomName(10),
        $prefix . '_city]' => $this->randomName(10),
        $prefix . '_zone]' => $zone_id,
        $prefix . '_postal_code]' => mt_rand(10000, 99999),
        //'panes[payment][payment_method' => 'moneybird', // Added moneybirs selection
      );
    }

    // If the email address has not been set, and the user has not logged in,
    // add a primary email address.
    if (!isset($edit['panes[customer][primary_email]']) && !$this->loggedInUser) {
      $edit['panes[customer][primary_email]'] = $this->randomName(8) . '@example.com';
    }

    return $edit;
  }*/
}