<?php

/*
Suggests matches between domains and accounts
TODO: fix f.eks. co.uk domæner. Vi antager at alt efter sidste . er tld. 
*/
$config = (require 'config.php');
require 'includes/redbean/rb.php';
$dsn = 'mysql:host=' . $config->dbHost . ';dbname=' . $config->dbName;
R::setup($dsn, $config->dbUsername, $config->dbPassword);
$domains = R::getCol('select name from domain');
require 'includes/classes/class.sugarCrmConnector.php';
try {
    $sugar = sugarCrmConnector::getInstance();
    $sugar->connect($config->sugarLogin, $config->sugarPassword);
    $accounts = array();
    $results = $sugar->getEntryList('Accounts', "accounts.account_type = 'Customer'", 'name', 0, array('name'));
    foreach ($results->entry_list as $result) {
        #$accounts[] = (object) array( 'id' => $result->id, 'label' => $result->name_value_list[0]->value, 'value' => $result->name_value_list[0]->value );
        $accounts[] = array('id' => $result->id, 'value' => $result->name_value_list[0]->value);
    }
} catch (Exception $e) {
    print_r($e);
}
find_suggestions($domains, $accounts);
function domainToAccount($domainname, $account, $account_id)
{
    $owner = R::findOne('owner', 'account_id=?', array($account_id));
    if ($owner === false) {
        $owner = R::dispense("owner");
        $owner->name = $account;
 /**
  * Searches for accounts
  *
  * @return array
  * @author Henrik Farre <*****@*****.**>
  **/
 private function accountSearch($str)
 {
     $finalResults = array();
     require 'class.sugarCrmConnector.php';
     try {
         $sugar = sugarCrmConnector::getInstance();
         $sugar->connect(mvc\retrieve('config')->sugarLogin, mvc\retrieve('config')->sugarPassword);
         $results = $sugar->getEntryList('Accounts', "accounts.account_type = 'Customer' AND accounts.name LIKE '{$str}'", 'name', 0, array('name'));
         foreach ($results->entry_list as $result) {
             $formattedResult = array('id' => $result->id, 'label' => $result->name_value_list[0]->value, 'type' => $this->type, 'value' => $result->name_value_list[0]->value);
             $finalResults[] = $formattedResult;
         }
     } catch (Exception $e) {
         // TODO: return error msg
         error_log(__LINE__ . ':' . __FILE__ . ' ' . $e->getMessage());
         // hf@bellcom.dk debugging
     }
     return $finalResults;
 }