#!/usr/bin/php -q
<?php
$version = '0.3';
$argc = $_SERVER['argc'];
$argv = $_SERVER['argv'];

if ($argc > 1) {
    foreach ($argv as $value) {
        switch ($value) {
        case 'availability':     $availability     = true; break;
        case 'matchidentifiers': $matchidentifiers = true; break;
        case 'matchmethods':     $matchmethods     = true; break;
        case 'commandes':        $checkCommandes   = true; break;
        case 'all':
            $checkCommandes   = true;
            $matchidentifiers = true;
            $matchmethods     = true;
            $checkCommandes   = true;
            break;
        default:
            break;
        }
    }
} else {
    print $argv[0]." version : ".$version."\n\n";
    print "Lancer le script ".$argv[0].
        " sans paramètres permet de charger toutes les méthodes graydon".
        " et vérifier les commandes\n\n";
    print "Les services disponibles sont :\n";
    print "\t- Disponibilité des pays graydon (availability).\n";
    print "\t- Types d'identifiant disponible par pays (matchidentifiers).\n";
    print "\t- Méthodes de recherche (matchmethods).\n";
    print "\t- Vérification des commandes (commandes).\n";
    exit;
}

require_once '../config/prepend.php';
// Inclure la base de données
require_once 'dbbootstrap.php';
// Inclure la config graydon
require_once 'graydon/graydon.php';

setDbConn('graydon');

if (isset($availability) == true && $availability === true) {
    // Country Availability
    $request = new StdClass();
    $request->Authentication_Parameters = $authentication;
    try	{
        $result = $graydon->getCountryAvailability($request);
        // Enregistrement de l'action dans les logs
        $transactionIdentifier = $result->Service_Log->TransactionIdentifier;
        $sessionID = $result->Service_Log->SessionID;
        foreach ($result->CountryAvailablity->CountryAndProduct as $item) {
            $availability = array();
            $availability = $item->Products->Product;
            // Enregistrement pour chaque pays de la disponibilité des services
            $countryavailability = new Countryavailability();
            $countryavailability->country = $item->Country;
            $countryavailability->availability = serialize($availability);
            $countryavailability->replace();
        }
    }
    catch (SoapFault $fault) {
    }
}

if (isset($matchidentifiers) == true && $matchidentifiers === true) {
    // matchidentifiers
    $request = new StdClass();
    $request->Authentication_Parameters = $authentication;
    try	{
        $result = $graydon->getCompanyMatchIdentifiers($request);
        // Enregistrement de l'action dans les logs
        $transactionIdentifier = $result->Service_Log->TransactionIdentifier;
        $sessionID = $result->Service_Log->SessionID;

        foreach ($result->CompanyMatchIdentifiers->CompanyMatchIdentifier as
                 $item) {
            $tabIdentifiers = array();
            $tabIdentifiers = $item->CompanyIdentifier;
            // Stockage du résultat de la méthode en caches
            $matchidentifiers = new Matchidentifiers();
            $matchidentifiers->country = $item->Country;
            $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();
            }
        } else {
            graydon_processSoapFault($graydon,$fault,$tabInfo);
        }
    }
}

if (isset($matchmethods) == true && $matchmethods === true) {
    // matchmethods
    $request = new StdClass();
    $request->Authentication_Parameters = $authentication;
    try	{
        $result = $graydon->getCompanyMatchMethods($request);
        $transactionIdentifier = $result->Service_Log->TransactionIdentifier;
        $sessionID = $result->Service_Log->SessionID;

        foreach ($result->CompanyMatchMethods->CompanyMatchMethod as $item) {
            $methods = array();
            $methods = $item->MatchMethods->MatchMethod;
            // Stockage du résultat de la méthode en cache
            $matchmethods = new Matchmethods();
            $matchmethods->country = $item->Country;
            $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/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();
            }
        } else {
            graydon_processSoapFault($graydon,$fault,'');
        }
    }
}

// --------------------------------------------------------------------------- //
// Commandes
// --------------------------------------------------------------------------- //
if (isset($checkCommandes) == true && $checkCommandes === true) {
    $tabCommandes = Doctrine_Query::create()
        ->select('*')
        ->from('Commandes')
        ->execute();
    foreach ($tabCommandes as $commande) {
        if ($commande->servicespeed == 'Immediate' ||
            $commande->reference == '') {
            continue;
        }
        print 'Commande:'.
            ' servicespeed='.$commande->servicespeed.
            ' orderstate='  .$commande->orderstate.
            ' reference='   .$commande->reference.
            "\n";
        switch ($commande->orderstate) {
        case 'InError':
            break;
        // Mise à jour pour 'Notified', 'Initialised', 'Assigned', et ''
        case 'Notified':
        case 'Initialised':
        case 'Assigned':
        case '':
            $requete = new StdClass();
            $requete->Authentication_Parameters = $authentication;
            $requete->OrderReference = $commande->reference;
            try {
                $checkOrderResult = $graydon->checkOrders($requete);
            } catch (SoapFault $e) {
                print "erreur soap\n";
                break;
            }
            $orderstate =
                $checkOrderResult->CheckOrders->OrderStatus[0]->OrderState;
            print 'orderstate ==> '.$orderstate."\n";
            if ($orderstate != $commande->orderstate) {
                Doctrine_Query::create()
                    ->update('Commandes')
                    ->set('orderstate', '?', $orderstate)
                    ->where('id = ?', $commande->id)
                    ->execute();
            }
            if (isset($checkOrderResult->CheckOrders->OrderStatus[0]->DateDue)) {
                $datedue =
                    $checkOrderResult->CheckOrders->OrderStatus[0]->DateDue;
                if ($datedue != $commande->datedue) {
                    Doctrine_Query::create()
                        ->update('Commandes')
                        ->set('datedue', '?', $datedue)
                        ->where('id = ?', $commande->id)
                        ->execute();
                }
            }
            if ($orderstate != 'Completed' &&
                $orderstate != 'CompletedwithUpdate' &&
                $orderstate != 'ReCompleted' &&
                $orderstate != 'Delivered') {
                break;
            }
        // Récupération pour 'Completed', 'CompletedwithUpdate',
        // 'Delivered', et 'ReCompleted'
        case 'Completed':
        case 'CompletedwithUpdate':
        case 'ReCompleted':
        case 'Delivered':
            // On verifie qu'on ne l'a pas deja
            $q = Doctrine_Query::create()
                ->from('Report')
                ->where('order_id = ?', $commande->id)
                ->fetchOne();
            if ($q != false) {
                print "rapport déjà enregistré\n";
                continue;
            }
            $requete = new StdClass();
            $requete->Authentication_Parameters = $authentication;
            $requete->LanguageCode = 'F';
            $requete->OrderReference = $commande->reference;
            // Récupération des MimeTypes
            $pays = Doctrine_Query::create()
                ->from('Country')
                ->where('id = ?', $commande->country_id)
                ->fetchOne();
            $pays = $pays->graydon_country;
            $availability = getCountryAvailability($pays);
            foreach($availability as $a) {
                if ($a->ServiceSpeed == $commande->servicespeed) {
                    $mime_types = $a->MimeTypes->MimeType;
                    break;
                }
            }
            // Récupération des documents
            if (is_array($mime_types) == false) {
                $mime_types = array($mime_types);
            }
            foreach ($mime_types as $mime_type) {
                $requete->MimeType = $mime_type;  // 'html', 'xml', 'pdf', 'doc'
                try {
                    $checkOrderResult = $graydon->getCompanyReport($requete);
                } catch (SoapFault $e) {
                    print "erreur soap\n";
                    print_r($e);
                    continue;
                }
                $report = new Report();
                $detail = Doctrine_Query::create()
                    ->from('CommandesDetail')
                    ->where('commandes_id = ?', $commande->id)
                    ->fetchOne();
                $report->name       = $detail->eName;
                $report->identifier = $detail->eIdentifiers;
                switch($mime_type) {
                case 'html':
                    $report->content = $checkOrderResult->ReportText;
                    break;
                case 'xml':
                    $report->content = $checkOrderResult->ReportXML->any;
                    break;
                case 'pdf':
                case 'doc':
                    $report->content = $checkOrderResult->ReportBinary;
                    break;
                default:
                    print 'type de document inconnu: '.
                        $checkOrderResult->ReportMimeType."\n";
                    continue;
                }
                $report->format = $checkOrderResult->ReportMimeType;
                $report->order_id = $commande->id;
                $report->save();
                Doctrine_Query::create()
                    ->update('Commandes')
                    ->set('datecompleted', '?',
                          $checkOrderResult->Service_Log
                          ->ResponseTimestamp->Date)
                    ->set('orderstate', '?', 'Delivered')
                    ->where('id = ?', $commande->id)
                    ->execute();
                print $mime_type." enregistré\n";
          }
            break;
        default:
            print 'état inconnu\n';
        }
    }
}
?>