<?php
require_once 'graydon/graydon.php';
require_once 'dbbootstrap.php';

/**
 * Retourne les identifiants disponible.
 * @param string $pays
 *		Le pays Graydon
 * @return string
 * 		.
 */
function getCompanyMatchIdentifiers($pays)
{
	global $page, $mode, $firephp, $graydon, $authentication;

	$firephp->info('Méthode getCompanyMatchIdentifiers');

	setDbConn('graydon');
	$q = Doctrine_Query::create()
	    ->from('Matchidentifiers')
	    ->where('country = ?', $pays);

	$matchidentifiers = new Matchidentifiers();
	$matchidentifiers = $q->fetchOne();

	/** Recup des types d'identifiants pour le pays **/
	if($matchidentifiers == false)
	{
		//Récupération des intitulés identifiant
		$request = new StdClass();
		$request->Authentication_Parameters = $authentication;
		$request->Country = $pays;
		$firephp->log($request,'REQUETE CompanyMatchIdentifier');
		try
		{
			$result = $graydon->getCompanyMatchIdentifiers($request);
			$firephp->log($result,'CompanyMatchIdentifiers');
			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog($_SESSION['tabInfo']['login'], $page, 'getCompanyMatchIdentifiers', $transactionIdentifier, $sessionID);
			//Log de la requete dans la bdd
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCompanyMatchIdentifiers';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = $mode;
			$log->save();

			$tabIdentifiers = $result->CompanyMatchIdentifiers->CompanyMatchIdentifier[0]->CompanyIdentifier;

			//Stockage du résultat de la méthode en cache
			$matchidentifiers = new Matchidentifiers();
			$matchidentifiers->country = $pays;
			$matchidentifiers->identifiers = serialize($tabIdentifiers);
			$matchidentifiers->replace();

		}catch( SoapFault $fault ){
			$code = $fault->detail->GraydonCompanyData_Fault->FaultReturnCode;
			$text = $fault->detail->GraydonCompanyData_Fault->FaultMessage;
			$firephp->log($text,'texterror');
			require_once 'graydon/graydon_error.php';
			if(graydon_error($code, $text)!=false){
					if($code=='CWS0112'){
						//Stockage du résultat de la méthode en cache
						$matchidentifiers = new Matchidentifiers();
						$matchidentifiers->country = $pays;
						$matchidentifiers->identifiers = serialize('noidentifiers');
						$matchidentifiers->replace();
						$tabIdentifiers = 'noidentifiers';
					}
			}else{
				$tabIdentifiers = graydon_processSoapFault($graydon,$fault,$_SESSION['tabInfo']);
			}
		}
	}else{
		$firephp->info('tabIdentifiers pris dans la bdd');
		$tabIdentifiers = unserialize($matchidentifiers->identifiers);
	}
	return $tabIdentifiers;
}

function getCompanyProducts($identifier)
{
    global $page, $mode, $firephp, $graydon, $authentication;

    setDbConn('graydon');
    $q = Doctrine_Query::create()
        ->from('Companyproducts')
        ->where('identifiers = ?', $identifier);

    $companyproducts = new Companyproducts();
    $companyproducts = $q->fetchOne();
    $now = mktime(date('G'), date('i'), date('s'),
                  date("m"), date("d"), date("Y"));
    if ($companyproducts == false) {
        $request = new StdClass();
        $request->Authentication_Parameters = $authentication;
        $request->CompanyMatchIdentifier    = $identifier;
        try {
            // Make a request on the web service
            $result = $graydon->getCompanyProducts($request);

            // Enregistrement de l'action dans les logs
            $transactionIdentifier = $result->Service_Log->TransactionIdentifier;
            $sessionID = $result->Service_Log->SessionID;
            graydonRequeteLog($_SESSION['tabInfo']['login'], $page,
                              'getCompanyProducts', $transactionIdentifier,
                              $sessionID);

            // Log de la requete dans la bdd
            $log = new Requetelog();
            $log->login = $_SESSION['tabInfo']['login'];
            $log->action = 'getCompanyProducts';
            $log->request = serialize($request);
            $log->transactionIdentifier = $transactionIdentifier;
            $log->sessionID = $sessionID;
            $log->mode = $mode;
            $log->save();

            // Sauvegarde dans la bdd
            $companyproducts = new Companyproducts();
            $companyproducts->identifiers = $identifier;
            $companyproducts->company  = serialize($result->Company);
            $companyproducts->products = serialize($result->Products);
            $companyproducts->save();

            // Extraction
            $company  = $result->Company;
            $products = $result->Products->Product;

        } catch(SoapFault $fault){
            $code = $fault->detail->GraydonCompanyData_Fault->FaultReturnCode;
            $text = $fault->detail->GraydonCompanyData_Fault->FaultMessage;
            $firephp->log($text,'texterror');
            require_once 'graydon/graydon_error.php';
            if (graydon_error($code, $text) == false) {
                graydon_processSoapFault($graydon, $fault, $_SESSION['tabInfo']);
            }
        }
    } else {
        $company  = unserialize($companyproducts->company);
        $products = unserialize($companyproducts->products);
        $products = $products->Product;
    }

    return array('Company' => $company, 'Products' => $products);
}


function getCompanyMatches($pays)
{
	global $page, $mode, $firephp, $graydon, $authentication;

	// Create the request parameters
	$request = new StdClass();
	// Initialise the request object
	$request->Authentication_Parameters = $authentication;

	// Create a new country parameters object
	$company = new StdClass();
	// Initialise the country object
	$company->Country = $pays;
	$company->ClientReference = '';

	$request->CompanyMatches_Parameters = $company;

	if($_REQUEST['method'] == 'keyword'){
		$request->Keyword = $_REQUEST['frmRecherche']['Keywords'];
		$request->City = isset($_REQUEST['frmRecherche']['City']) ? $_REQUEST['frmRecherche']['City'] : '' ;
		$request->PostCode = isset($_REQUEST['frmRecherche']['PostCode']) ? $_REQUEST['frmRecherche']['PostCode'] : '' ;
	}elseif($_REQUEST['method'] == 'identifier'){
		$request->Identifier = $_REQUEST['frmRecherche']['Identifier'];
	}elseif($_REQUEST['method'] == 'name'){
		$request->Name = $_REQUEST['frmRecherche']['Name'];
		$request->City = isset($_REQUEST['frmRecherche']['City']) ? $_REQUEST['frmRecherche']['City'] : '' ;
		$request->PostCode = isset($_REQUEST['frmRecherche']['PostCode']) ? $_REQUEST['frmRecherche']['PostCode'] : '' ;
	}elseif($_REQUEST['method'] == 'postcode'){
		$request->PostCode = isset($_REQUEST['frmRecherche']['PostCode']) ? $_REQUEST['frmRecherche']['PostCode'] : '' ;
	}

	try
	{
		// Make a request on the webservice
		if($_REQUEST['method'] == 'keyword'){
			$result = $graydon->getCompanyMatchesByKeyword($request);

			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog($_SESSION['tabInfo']['login'], $page, 'getCompanyMatchesByKeyword', $transactionIdentifier, $sessionID);

			//Log de la requete dans la bdd
			setDbConn('graydon');
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCompanyMatchesByKeyword';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = 'normal';
			$log->save();

		}elseif($_REQUEST['method'] == 'identifier'){
			$result = $graydon->getCompanyMatchesByIdentifier($request);

			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog($_SESSION['tabInfo']['login'], $page, 'getCompanyMatchesByIdentifier', $transactionIdentifier, $sessionID);

			//Log de la requete dans la bdd
			setDbConn('graydon');
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCompanyMatchByIdentifier';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = 'normal';
			$log->save();

		}elseif($_REQUEST['method'] == 'name'){
			$result = $graydon->getCompanyMatchesByName($request);

			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog($_SESSION['tabInfo']['login'], $page, 'getCompanyMatchesByName', $transactionIdentifier, $sessionID);

			//Log de la requete dans la bdd
			setDbConn('graydon');
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCompanyMatchesByName';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = 'normal';
			$log->save();

		}elseif($_REQUEST['method'] == 'postcode'){
			$result = $graydon->getCompanyMatchesByPostCode($request);

			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog($_SESSION['tabInfo']['login'], $page, 'getCompanyMatchesByPostCode', $transactionIdentifier, $sessionID);

			//Log de la requete dans la bdd
			setDbConn('graydon');
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCompanyMatchesByPostCode';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = 'normal';
			$log->save();

		}

		$_SESSION['graydon']['SessionID'] = $result->Service_Log->SessionID;
		$_SESSION['graydon']['TransactionIdentifier'] = $result->Service_Log->TransactionIdentifier;

		return $result;

	}catch( SoapFault $fault ){
		if(isset($fault->faultstring) && $fault->faultcode = 'HTTP'){
			print '<br/>Le service partenaire n\'est pas disponible.';
		}else{
			$code = $fault->detail->GraydonCompanyData_Fault->FaultReturnCode;
			$text = $fault->detail->GraydonCompanyData_Fault->FaultMessage;
			$firephp->log($text,'texterror');
			require_once 'graydon/graydon_error.php';
			$error = graydon_error($code, $text);
			if($error==false){
				return graydon_processSoapFault($graydon,$fault,$_SESSION['tabInfo']);
			}elseif($error['Code'] == 'CWS5000'){
				return array();
			}
		}
	}
}


function getCountryAvailability($pays)
{
	global $page, $mode, $firephp, $graydon, $authentication;

	setDbConn('graydon');
	$q = Doctrine_Query::create()
	    ->from('Countryavailability')
	    ->where('country = ?', $pays);

	$countryavailability = new Countryavailability();
	$countryavailability = $q->fetchOne();
	if($countryavailability == false)
	{
		// Create the request parameters
		$request = new StdClass();
		// Initialise the request object
		$request->Authentication_Parameters = $authentication;
		$request->Country = $pays;
		$firephp->log($request, 'request');
		try
		{
			$result = $graydon->getCountryAvailability($request);
			$firephp->log($result,'CountryAvailability');
			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog( $_SESSION['tabInfo']['login'], $page, 'getCountryAvailability', $transactionIdentifier, $sessionID);
			//Log de la requete dans la bdd
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCountryAvailability';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = $mode;
			$log->save();

			$availability = $result->CountryAvailablity->CountryAndProduct[0]->Products->Product;

			//Stockage du résultat de la méthode en cache
			$countryavailability = new Countryavailability();
			$countryavailability->country = $pays;
			$countryavailability->availability = serialize($availability);
			$countryavailability->replace();

		}catch(SoapFault $fault){
			$code = $fault->detail->GraydonCompanyData_Fault->FaultReturnCode;
			$text = $fault->detail->GraydonCompanyData_Fault->FaultMessage;
			$firephp->log($text,'texterror');
			require_once 'graydon/graydon_error.php';
			if(graydon_error($code, $text)==false){
				$availability = graydon_processSoapFault($graydon,$fault,$_SESSION['tabInfo']);
			}else{
				$availability = false;
			}
		}
	}else{
		$availability = unserialize($countryavailability->availability);
	}
	return $availability;
}


function getCompanyMatchMethods($pays)
{
	global $page, $mode, $firephp, $graydon, $authentication;

	setDbConn('graydon');
	$q = Doctrine_Query::create()
	    ->from('Matchmethods')
	    ->where('country = ?', $pays);

	$matchmethods = new Matchmethods();
	$matchmethods = $q->fetchOne();

	if($matchmethods == false)
	{
		// Create the request parameters
		$request = new StdClass();
		// Initialise the request object
		$request->Authentication_Parameters = $authentication;
		$request->Country = $pays;
		try
		{
			$result = $graydon->getCompanyMatchMethods($request);
			//Enregistrement de l'action dans les logs
			$transactionIdentifier = $result->Service_Log->TransactionIdentifier;
			$sessionID = $result->Service_Log->SessionID;
			graydonRequeteLog( $_SESSION['tabInfo']['login'], $page, 'getCompanyMatchMethods', $transactionIdentifier, $sessionID);
			//Log de la requete dans la bdd
			$log = new Requetelog();
			$log->login = $_SESSION['tabInfo']['login'];
			$log->action = 'getCompanyMatchMethods';
			$log->request = serialize($request);
			$log->transactionIdentifier = $transactionIdentifier;
			$log->sessionID = $sessionID;
			$log->mode = $mode;
			$log->save();

			$methods = $result->CompanyMatchMethods->CompanyMatchMethod[0]->MatchMethods->MatchMethod;

			//Stockage du résultat de la méthode en cache
			$matchmethods = new Matchmethods();
			$matchmethods->country = $pays;
			$matchmethods->methods = serialize($methods);
			$matchmethods->replace();

		}catch( SoapFault $fault ){
			$code = $fault->detail->GraydonCompanyData_Fault->FaultReturnCode;
			$text = $fault->detail->GraydonCompanyData_Fault->FaultMessage;
			$firephp->log($text,'texterror');
			require_once 'graydon/graydon_error.php';
			if(graydon_error($code, $text)!=false){
				if($code=='CWS0112'){
					//Stockage du résultat de la méthode en cache
					$matchmethods = new Matchmethods();
					$matchmethods->country = $pays;
					$matchmethods->methods = serialize('nomethods');
					$matchmethods->replace();
					$methods = 'nomethods';
				}
			}else{
				$methods = graydon_processSoapFault($graydon,$fault,$_SESSION['tabInfo']);
			}
		}
	}else{
		$methods = unserialize($matchmethods->methods);
	}
	return $methods;
}

// --------------------------------------------------------------------------- //
// getIdentite
// --------------------------------------------------------------------------- //
function getIdentite($identifier, $CompanyProductIdentifier)
{
    global $page, $graydon, $authentication;

    $pays  = $_SESSION['graydon']['pays'];
    $login = $_SESSION['tabInfo']['login'];
    $mode  = $_SESSION['graydon']['mode'];
    $name  = $_SESSION['graydon']['name'];

    setDbConn('graydon');

    // Requete
    $request = new StdClass();
    $request->Authentication_Parameters = $authentication;
    $request->OrderCreatorEmail = 'mricois@scores-decisions.com';
    $request->CompanyProductIdentifier = $CompanyProductIdentifier;
    $request->PartnerData = '';

    try	{
        $placeOrderResult = $graydon->placeOrder($request);
    } catch (SoapFault $e) {
        $code = $e->detail->GraydonCompanyData_Fault->FaultReturnCode;
        $text = $e->detail->GraydonCompanyData_Fault->FaultMessage;
        require_once 'graydon/graydon_error.php';
        $error = graydon_error($code, $text);
        if ($error == false) {
            print graydon_processSoapFault($graydon, $e, $_SESSION['tabInfo']);
        } else {
            print graydon_messageSoapFault();
            //envoieCourriel("SoapFault, identifiant : ".
            //               $CompanyProductIdentifier);
        }
        return 0;
    }

    // Prix
    $prix = Doctrine_Query::create()
        ->from('Price p')
        ->leftJoin('p.Country c')
        ->where('c.graydon_country = ?', $pays)
        ->fetchOne()->immediate;

    // Enregistrement des commandes dans la bdd
    $commande = new Commandes();
    $commande->reference = $placeOrderResult->OrderStatus->OrderReference;
    $commande->servicespeed =
        $placeOrderResult->OrderStatus->Order->ServiceSpeed;
    $commande->prix = $prix;
    $commande->orderstate  = $placeOrderResult->OrderStatus->OrderState;
    $commande->dateordered = $placeOrderResult->OrderStatus->DateOrdered;
    $commande->datecompleted =
        $placeOrderResult->OrderStatus->DateCompleted;
    $commande->datedue = $placeOrderResult->OrderStatus->DateDue;
    $commande->companyproductidentifier = $CompanyProductIdentifier;
    $commande->sessionid = $placeOrderResult->Service_Log->SessionID;
    $commande->transactionidentifier =
        $placeOrderResult->Service_Log->TransactionIdentifier;
    $commande->user = $login;
    $commande->mode = $mode;
    $commande->Country = Doctrine_Query::create()
        ->from('Country')
        ->where('graydon_country = ?', $pays)
        ->fetchOne();
    $commande->save();

    $mailcommande = $commande->toString();
    $commande_id = $commande->id;

    // Detail
    $commandeDetail = new CommandesDetail();
    $commandeDetail->eName         = $name;
    $commandeDetail->eIdentifiers  = $identifier;
    $commandeDetail->ePays         = $pays;
    $commandeDetail->commandes_id  = $commande->id;
    $commandeDetail->eLanguageCode = 'F';
    $commandeDetail->eCreditOpinionCurrency = 'EUR';
    $commandeDetail->save();

    // setLog
    $client = new SoapClient(null, array(
        'trace'        => 1,
        'soap_version' => SOAP_1_1,
        'location'     => WEBSERVICE_URL,
        'uri'          => WEBSERVICE_URI,
        'login'        => $login,
        'password'     => $_SESSION['tabInfo']['password']));
    $client->setLog('international_identite', $commande_id, 0, $prix);

    // Enregistrement de l'action dans les logs
    $transactionIdentifier =
        $placeOrderResult->Service_Log->TransactionIdentifier;
    $sessionID = $placeOrderResult->Service_Log->SessionID;
    graydonRequeteLog($login, $page, 'placeOrder',
                      $transactionIdentifier, $sessionID);

    // Log de la requete dans la bdd
    $log = new Requetelog();
    $log->login = $_SESSION['tabInfo']['login'];
    $log->action = 'placeOrder';
    $log->request = serialize($request);
    $log->transactionIdentifier = $transactionIdentifier;
    $log->sessionID = $sessionID;
    $log->mode = $mode;
    $log->save();

    // Envoi d'un mail pour le passage de la commande
    envoieCourriel($mailcommande);

    // On verifie l'etat de la demande
    if (isset($placeOrderResult) == true &&
        $placeOrderResult->OrderStatus->OrderState == 'Completed') {
        $requete = new StdClass();
        $requete->Authentication_Parameters = $authentication;
        $requete->LanguageCode = 'F';
        $requete->OrderReference =
            $placeOrderResult->OrderStatus->OrderReference;

        $availability = getCountryAvailability($pays);
        foreach($availability as $a) {
            if ($a->ServiceSpeed == $commande->servicespeed) {
                $mime_types = $a->MimeTypes->MimeType;
                break;
            }
        }
        if (empty($mime_types) == true) {
            return 0;
        }
        // Récupération des documents
        foreach ($mime_types as $mime_type) {
            if (empty($mime_type) == true) {
                continue;
            }
            print "mime_type='$mime_type'<br/>";
            $requete->MimeType = $mime_type;  // 'html', 'xml', 'pdf', 'doc'
            try {
                $reportResult = $graydon->getCompanyReport($requete);
            } catch (SoapFault $e) {
                $code = $e->detail->GraydonCompanyData_Fault->FaultReturnCode;
                $text = $e->detail->GraydonCompanyData_Fault->FaultMessage;
                require_once 'graydon/graydon_error.php';
                $error = graydon_error($code, $text);
                if ($error == false) {
                    print graydon_processSoapFault($graydon, $e,
                                                   $_SESSION['tabInfo']);
                } else {
                    print graydon_messageSoapFault();
                    //envoieCourriel("SoapFault, identifiant : ".$commande_id);
                }
                return 0;
            }
            // Enregistrement de l'action dans les logs
            $transactionIdentifier =
                $reportResult->Service_Log->TransactionIdentifier;
            $sessionID = $reportResult->Service_Log->SessionID;
            graydonRequeteLog($login, $page,
                              'getCompanyReport', $transactionIdentifier,
                              $sessionID);
            // Log dans la bdd
            $log = new Requetelog();
            $log->login = $login;
            $log->action = 'getCompanyReport';
            $log->request = serialize($requete);
            $log->transactionIdentifier = $transactionIdentifier;
            $log->sessionID = $sessionID;
            $log->mode = $mode;
            $log->save();

            // Rapport dans la bdd
            $rapport = new Report();
            $rapport->identifier = $identifier;
            $rapport->name = $name;
            $rapport->format = $mime_type;
            switch($mime_type) {
            case 'html':
                $rapport->content = $reportResult->ReportText;
                break;
            case 'xml':
                $rapport->content = $reportResult->ReportXML->any;
                break;
            case 'pdf':
            case 'doc':
                $rapport->content = $reportResult->ReportBinary;
            break;
            default:
                print 'type de document inconnu: '.
                    $reportResult->ReportMimeType."\n";
                continue;
            }
            $rapport->order_id = $commande_id;
            $rapport->save();
        }
        $commande->orderstate = 'Delivered';
        $commande->save();
    }
    return $commande_id;
}

// --------------------------------------------------------------------------- //
// envoieCourriel
// --------------------------------------------------------------------------- //
function envoieCourriel($ref)
{
    require_once 'mail/mail.php';
    sendMail("[International] - (Date :".
             date("d")."/".date("m")."/".date("Y").") - Commande",
             "Commande effectuée par ".$_SESSION['tabInfo']['login']."\n".
             $ref,
             // From
             array('email' => 'contact@scores-decisions.com',
                   'name'  => 'Commandes International'),
             // To
             array(0 => array('email' => EMAIL_SUPPORTDEV,
                              'name'  => 'Support')));
}

// --------------------------------------------------------------------------- //
// copieDesRapports
// --------------------------------------------------------------------------- //
function copieDesRapports($commande_a_copier,
                          $identifier,
                          $pidentifier)
{
    $pays  = $_SESSION['graydon']['pays'];
    $login = $_SESSION['tabInfo']['login'];
    $mode  = $_SESSION['graydon']['mode'];
    $name  = $_SESSION['graydon']['name'];

    // Nouvelle commande
    $commande = new Commandes();
    $commande->prix = Doctrine_Query::create()
        ->from('Price p')
        ->leftJoin('p.Country c')
        ->where('c.graydon_country = ?', $pays)
        ->fetchOne()->immediate;
    $commande->servicespeed  = 'Immediate';
    $commande->orderstate    = 'Delivered';
    $commande->dateordered   = date('Y-m-d');
    $commande->datedue       = $commande->dateordered;
    $commande->datecompleted = Doctrine_Query::create()
        ->from('Commandes')
        ->where('id = ?', $commande_a_copier)
        ->fetchOne()->datecompleted;
    $commande->companyproductidentifier = $pidentifier;
    list($dummy, $session_id, $transaction_identifier) =
        explode(':', $commande->companyproductidentifier);
    $commande->sessionid = $session_id;
    $commande->transactionidentifier = $transaction_identifier;
    $commande->user = $login;
    $commande->mode = $mode;
    $commande->Country = Doctrine_Query::create()
        ->from('Country')
        ->where('graydon_country = ?', $pays)
        ->fetchOne();
    $commande->save();

    // Detail de la commande
    $commandeDetail = new CommandesDetail();
    $commandeDetail->eName         = $name;
    $commandeDetail->eIdentifiers  = $identifier;
    $commandeDetail->ePays         = $pays;
    $commandeDetail->commandes_id  = $commande->id;
    $commandeDetail->eLanguageCode = 'F';
    $commandeDetail->eCreditOpinionCurrency = 'EUR';
    $commandeDetail->save();

    // Copie des rapports
    $rapports = Doctrine_Query::create()
        ->from('Report')
        ->where('order_id = ?', $commande_a_copier)
        ->orderby('id')
        ->execute();
    foreach ($rapports as $r) {
        $rapport = new Report();
        $rapport->identifier = $r->identifier;
        $rapport->name       = $r->name;
        $rapport->content    = $r->content;
        $rapport->format     = $r->format;
        $rapport->order_id   = $commande->id;
        $rapport->save();
    }

    return $commande->id;
}

// --------------------------------------------------------------------------- //
// setEnquete
// --------------------------------------------------------------------------- //
function setEnquete($pays)
{
    global $page, $mode, $graydon, $authentication;

    setDbConn('graydon');

    // Si la commande existe pour cet utilisateur
    $c = Doctrine_Query::create()
        ->from('Commandes')
        ->where('companyproductidentifier = ?', $_POST['pidentifier'])
        ->andWhere('user = ?', $_SESSION['tabInfo']['login'])
        ->andWhere('not servicespeed = ?', 'Immediate')
        ->fetchOne();
    if ($c != false) {
        if ($c->orderstate == 'Delivered') {
            header('Location: ?page=international_commandes&id='.$c->id);
            print '<a href="?page=international_commandes&id='.$c->id.
                '">Veuillez suivre ce lien</a>';
            return $c->id;
        } else {
            print 'Cette commande est en cours<br/>';
            return 0;
        }
    }

    // Si on a un rapport pas trop vieux
    $rapports = Doctrine_Query::create()
        ->from('Report')
        ->where('identifier = ?', $_POST['identifier'])
        ->orderby('id desc')
        ->execute();
    if ($rapports != false && count($rapports) > 0) {
        foreach ($rapports as $rapport) {
            $c = Doctrine_Query::create()
                ->from('Commandes')
                ->where('id = ?', $rapport->order_id)
                ->orderby('id desc')
                ->fetchOne();
            if ($c == false || $c->servicespeed == 'Immediate') {
                continue;
            }
            if (strtotime("-2 week") <=
                strtotime($c->datecompleted)) {
                $commande_id =  copieDesRapports($rapport->order_id,
                                                 $_POST['identifier'],
                                                 $_POST['pidentifier']);
                if ($commande_id > 0) {
                    header('Location: ?page=international_commandes&id='.
                           $commande_id);
                    print '<a href="?page=international_commandes&id='.
                        $commande_id.
                        '">Veuillez suivre ce lien</a>';
                    return $commande_id;
                }
            }
        }
    }

    $serviceSpeed = strtolower($_POST['InfoEnq']['Servicespeed']);

    // Prix
    $prix = Doctrine_Query::create()
        ->select('p.'.$serviceSpeed)
        ->from('Price p')
        ->leftJoin('p.Country c')
        ->where('c.graydon_country = ?', $pays)
        ->fetchOne();

    // Sauvegarde des infos dans la base avant le passage de la commande
    $commande = new Commandes();
    $commande->servicespeed = $serviceSpeed;
    $commande->prix = $prix->$serviceSpeed;
    $commande->orderstate = '';
    $commande->companyproductidentifier = $_POST['pidentifier'];
    $commande->user = $_SESSION['tabInfo']['login'];
    $commande->mode = $_SESSION['graydon']['mode'];

    $country_id = Doctrine_Query::create()
        ->from('Country')
        ->where('graydon_country = ?', $pays)
        ->fetchOne()->id;
    $commande->country_id = $country_id;

    $commande->save();
    $commande_id = $commande->id;

    // Enregistrement des détails de la commande
    $commandeDetail = new CommandesDetail();
    $commandeDetail->dIdentite       = $_POST['InfoUser']['Identite'];
    $commandeDetail->dTelephone      = $_POST['InfoUser']['Tel'];
    $commandeDetail->dEmail          = $_POST['InfoUser']['Email'];
    $commandeDetail->dFax            = $_POST['InfoUser']['Fax'];
    $commandeDetail->eName           = $_POST['InfoEnq']['Name'];
    $commandeDetail->eIdentifiers    = $_POST['identifier'];
    $commandeDetail->eAdresse        = $_POST['InfoEnq']['Adresse'];
    $commandeDetail->eTelephone      = $_POST['InfoEnq']['Telephone'];
    $commandeDetail->ePays           = $_POST['InfoEnq']['Pays'];
    $commandeDetail->eAttentionOf    = $_POST['InfoEnq']['AttentionOf'];
    $commandeDetail->eSpecialRemarks = $_POST['InfoEnq']['SpecialRemarks'];
    $commandeDetail->commandes_id    = $commande_id;
    $commandeDetail->eLanguageCode   = 'F';
    $commandeDetail->eCreditOpinionCurrency = 'EUR';
    if (isset($_POST['InfoEnq']['Bankers']) == true) {
        $commandeDetail->eBankers = $_POST['InfoEnq']['Bankers'];
    }
    $commandeDetail->save();

    // Passage de la commande chez graydon
    $request = new StdClass();
    $request->Authentication_Parameters = $authentication;
    if (!isset($_POST['pidentifier'])) {
        $request->OrderCreatorEmail = EMAIL_SUPPORTDEV;
        $request->Order->LanguageCode = 'F';
        $request->Order->Name = $_POST['InfoEnq']['Name'];
        $request->Order->ServiceSpeed = $_POST['InfoEnq']['Servicespeed'];
        $request->Order->Country = $_POST['InfoEnq']['Pays'];
        $request->Order->Address->EntireAddress =
            $_POST['InfoEnq']['Adresse'];

        if (count($_POST['InfoEnq']['Identifiers']) > 1) {
            $count = 0;
            foreach ($_POST['InfoEnq']['Identifiers'] as $key => $value) {
                $request->Order->CompanyIdentifier[$count]->Identifier = $value;
                $request->Order->CompanyIdentifier[$count]->Type = $key;
                $count++;
            }
        } else {
            foreach ($_POST['InfoEnq']['Identifiers'] as $key => $value){
                $request->Order->CompanyIdentifier->Identifier = $value;
                $request->Order->CompanyIdentifier->Type = $key;
            }
        }

        $request->Order->AttentionOf    = $_POST['InfoEnq']['AttentionOf'];
        $request->Order->Bankers        = $_POST['InfoEnq']['Bankers'];
        $request->Order->SpecialRemarks = $_POST['InfoEnq']['SpecialRemarks'];
        $request->Order->Telephone      = $_POST['InfoEnq']['Telephone'];
    } else {
        $request->OrderCreatorEmail = 'mricois@scores-decisions.com';
        $request->CompanyProductIdentifier = $_POST['pidentifier'];
        $request->PartnerData = '';
    }
    $request->PartnerData = '';

    try {
        $placeOrderResult = $graydon->placeOrder($request);
    } catch (SoapFault $e) {
        $code = $e->detail->GraydonCompanyData_Fault->FaultReturnCode;
        $text = $e->detail->GraydonCompanyData_Fault->FaultMessage;
        require_once 'graydon/graydon_error.php';
        $error = graydon_error($code, $text);
        if ($error == false) {
            print graydon_processSoapFault($graydon, $e, $_SESSION['tabInfo']);
        } else {
            print graydon_messageSoapFault();
            //envoieCourriel("SoapFault, identifiant : ".$commande_id);
        }
        return 0;
    }

    // setLog
    $client = new SoapClient(null, array(
        'trace'        => 1,
        'soap_version' => SOAP_1_1,
        'location'     => WEBSERVICE_URL,
        'uri'          => WEBSERVICE_URI,
        'login'        => $_SESSION['tabInfo']['login'],
        'password'     => $_SESSION['tabInfo']['password']));
    $client->setLog('international_enquete', $commande_id, 0, $prix);

    // Enregistrement de l'action dans les logs
    $transactionIdentifier =
        $placeOrderResult->Service_Log->TransactionIdentifier;
    $sessionID = $placeOrderResult->Service_Log->SessionID;
    graydonRequeteLog($_SESSION['tabInfo']['login'], $page, 'placeOrder',
                      $transactionIdentifier, $sessionID);

    // Log de la requete dans la bdd
    $log = new Requetelog();
    $log->login = $_SESSION['tabInfo']['login'];
    $log->action = 'placeOrder';
    $log->request = serialize($request);
    $log->transactionIdentifier = $transactionIdentifier;
    $log->sessionID = $sessionID;
    $log->mode = $mode;
    $log->save();

    // Enregistrement de la commande dans la bdd
    $commande = new Commandes();
    $commande->assignIdentifier($commande_id);
    $commande->reference = $placeOrderResult->OrderStatus->OrderReference;
    $commande->servicespeed =
        $placeOrderResult->OrderStatus->Order->ServiceSpeed;
    $commande->prix = $prix->$serviceSpeed;
    $commande->orderstate = $placeOrderResult->OrderStatus->OrderState;
    $commande->dateordered = $placeOrderResult->OrderStatus->DateOrdered;
    if (isset($placeOrderResult->OrderStatus->DateCompleted) == true) {
        $commande->datecompleted =
            $placeOrderResult->OrderStatus->DateCompleted;
    }
    if (isset($placeOrderResult->OrderStatus->DateDue) == true) {
        $commande->datedue = $placeOrderResult->OrderStatus->DateDue;
    }
    $commande->sessionid = $sessionID;
    $commande->transactionidentifier = $transactionIdentifier;
    $commande->user = $_SESSION['tabInfo']['login'];
    $commande->mode = $_SESSION['graydon']['mode'];
    $commande->country_id = $country_id;
    $commande->save();
    $commande_id = $commande->id;

    // Enregistrement des détails de la commande
    // Déjà fait avant le passage de la commande chez graydon

    // Envoi d'un mail pour le passage de la commande
    envoieCourriel("Reference commande : ".$commande->reference);

    return $commande_id;
}
?>