
<center><h2><strong>Ubuntu</strong></h2>
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
/**
 *
 * Executé par https://airmob.net/commande_v2/etatcmdv2.cron.php
 * Lien direct https://airmob.net/commande_v2/zoho.actions.php?TEST=ok <= pour le début
 * Lien direct https://airmob.net/commande_v2/zoho.actions.php?SIMU=ok&action=go
 * Fréq : aucune pour le moment execution manuelle
 *
 * http://127.0.0.1/airmob/commande_v2/readme/commandev2.md
 * https://airmob.net/commande_v2/zoho.actions.php
 *
 *
 * CRON : toutes les heures
 * */

    session_start();
    error_reporting(E_ALL);
    ini_set("display_errors", 0);

//  pour API V2
define("APIZOHO", [ "IdOrg"  => "650182655",                                  // Id organization
                    "IdCli"  => "1000.KL48ACSNU2NS34520ESYY3FWZUBS0E",        // Id client
                    "Secret" => "3b4a8173e9dbd396aaeb2603db7560f5ff9a323bb6", // Secret
    ]
);
    /*
    $fileJson = "------.txt";
    $fp = fopen($fileJson, 'a+'); // a+ ajoute / w ecrase
    fwrite($fp,"12");
    fclose($fp);

*/
    include_once ("./lib/gestion.lib.php");
    $ClassCdeV2 = new ClassCdeV2('prod');

    //Tools - Permet de recalculer rapidemnt les delais
/*
    $Datepaiement ="2021-07-08";
    $Semaine3 = strtotime(date("Y-m-d", strtotime($Datepaiement)) . " +3 weeks");
    $Semaine4 = strtotime(date("Y-m-d", strtotime($Datepaiement)) . " +4 weeks");
    echo date("Y-m-d", $Semaine3);
    echo "<br>";
    echo date("Y-m-d", $Semaine4);
    exit;
*/
/*
    $ClassCdeV2->ContenuTable(); //Cree un fichier poru le Suivi/dashbaord
    $ClassCdeV2->Situation(); // Envoi un email avec ce qu il faut faire le jour J
*/
// Le 1er du mois à 9h informe

if( date('h')=="9" && date('d')=="1" ) {
    $Array = [
        'to'      => 'luc@bvcs.fr', //
        'subject' => '[AIRMOB/CDEV2] 1er du mois',
        'body'    => "Lancer les factures périodique ",
    ];
    $Mel   = $ClassCdeV2->MySendMailPHPMailer($Array);
}


// Bloque Tache CRON
    if(!$_REQUEST['action'])   {    die("INTERRUPTION VOLONTAIRE"); }

    $action = "nouvellecmd";

    echo "<h1>=>ATTENTION si le client n existe pas !</h1>Vous devez créer le client sur le CRM<br><a href='https://airmob.net/commande_v2/zoho.crm.php?idu='>Créer le client sur CRM</a><hr>";

// $DEBUG = true; // true = bloque la génération de facture créé le clietn si besoin et affiche les lignes de création de facture


    $MyIP = getenv ("REMOTE_ADDR");
   // echo "<h1>=>TEST</h1>";
    //$_SESSION['AIRCMDV2']['CURL']['STRIPE']['Authorization'] = "c2tfdGVzdF93dE9MWlJKUm1yUm01dmE1Y0RXVUtlTmw6";
    //else
    $_SESSION['AIRCMDV2']['CURL']['STRIPE']['Authorization']  = "c2tfbGl2ZV9qbU1FRXNyQnJydTBxY215U09QaFZpejE6";
    //
    //


// Si [message] => You are not authorized to perform this operation
// unset($_SESSION['CDEV2']['FACTURES']['TOKEN']);    exit;


// Les dates sont calculés à partir e la date de paiement ex 22/04/2021  $Datepaiement


//  API - ZOHOBOOKS
//  -----------------------------
// 1ere connexion, refresh TOKEN
//    if( !$_SESSION['CDEV2']['FACTURES']['TOKEN'] ) {
        $refresh_token = "1000.22c19beee7288032a8fef7398c164f5d.337b11b1cc5478129acacb05623673b9"; // Si l acces token change il faut changer ce code
        $Url           = "https://accounts.zoho.com/oauth/v2/token?refresh_token=$refresh_token&client_id=".APIZOHO['IdCli']."&client_secret=". APIZOHO['Secret']."&grant_type=refresh_token";
        $Param         = ['url' => $Url, 'method' => 'POST'];
        $Result        = $ClassCdeV2->MyCurl_APIZOHO_V2($Param);
        $Result        = json_decode($Result, TRUE);
        $Token         = "Zoho-oauthtoken " . $Result['access_token'];
        $_SESSION['CDEV2']['FACTURES']['TOKEN'] = $Token;
//    } else{
//        $Token = $_SESSION['CDEV2']['FACTURES']['TOKEN'];
//    }



// Controle les traitements à 4 semaines
//$ClassCdeV2->Semaine3(); die("");
//$ClassCdeV2->Semaine4(); die("");
//$ClassCdeV2->Periodique(); die("");

// Extrait les cdes du jours
if($_REQUEST['idu'])   $idu = $_REQUEST['idu']; // TEST :forcer uniquement

  //  $PAYESTRIPE = $ClassCdeV2->Paiement($idu);
   // exit;

    $ListeCmds = $ClassCdeV2->ListeCmds($idu);

    if (count($ListeCmds) > 0 ) {
    // Vérifier pour lidunique l etat de traitement ZOHO
        foreach ($ListeCmds as $key => $Cmd) {

            $idu          = $Cmd['idunique'];
            $Etat         = $ClassCdeV2->ZohoTraitement($idu);

            $MyDate       = strtotime(date("Y-m-d", strtotime($Cmd['paiement'])) . " +2 day");
            $Datepaiement =  date("Y-m-d", $MyDate) ; // J+2

            $Err      = [];
            $JsonFact = [];
            $CmdZOHO  = [];
            $CreeZCRM = false;
            $MemoIdu  = "";
            //  La cmd n existe pas !
            // Ce cas ne doit pas arriver
            //  -------------------------
            /*
            if (!$Etat['id']) {
                echo "<h3>=>Créer la commande $idu</h3>";
                $retour = $ClassCdeV2->InsertCmd($idu,$Cmd);
                if ($retour <> 'OK') echo "<h1>/!\ ERREUR </h1>";
                echo "<pre>";
                print_r($retour);
                echo "</pre>";
            }
            */

            //  Le client n existe pas !
            //  -------------------------

            if (!$Etat['zoho_idclient']) {

                echo "Créer le client sur CRM <a href='https://airmob.net/commande_v2/zoho.crm.php?idu=$idu'>$idu</a>";

                $Json = [];
                // Array
                echo "<pre>";
                print_r($Cmd);
                echo "</pre>";
                echo "Créer le client";



                $contact_name                = $Cmd['nomprenom'];
                $company_name                = strtoupper($Cmd['nomsociete']);

                $contact_persons['email']    = $Cmd['email'];

                $msisdn = $Cmd['telephone'];
                $num    = chunk_split($msisdn, 2, ' ');
                $msisdn = preg_replace("/^0/", "+33 ", $num);
                if(substr($num,0,2)=="06" || substr($num,0,2)=="07")    $contact_persons['mobile']   = $msisdn;
                else                                                                             $contact_persons['phone']   = $msisdn;

                $Country ="France";
                $shipping_address['address'] = $Cmd['nolivraison'] . " " . $Cmd['adrlivraison'];
                $shipping_address['zip']     = $Cmd['cplivraison'];
                $shipping_address['city']    = $Cmd['villelivraison'];
                $shipping_address['country'] = $Country;



                if ($Cmd['nofacturation']) {
                    $billing_address['address'] = $Cmd['nofacturation'] . " " . $Cmd['adrfacturation'];
                    $billing_address['zip']     = $Cmd['cpfacturation'];
                    $billing_address['city']    = $Cmd['villefacturation'];
                    $billing_address['country'] = $Country;
                } else {
                    $billing_address['address'] = $Cmd['nolivraison'] . " " . $Cmd['adrlivraison'];
                    $billing_address['zip']     = $Cmd['cplivraison'];
                    $billing_address['city']    = $Cmd['villelivraison'];
                    $billing_address['country'] = $Country;
                }

                $Json = ['JSONString' => '{
                            "contact_name":"' . $company_name . '",
                            "company_name":"' . $company_name . '",
                            "contact_persons"  :[' . json_encode($contact_persons) . '],
                            "shipping_address" :' . json_encode($shipping_address) . ',
                            "billing_address"  :' . json_encode($billing_address) . '
                            }'];

                $Url     = 'https://books.zoho.com/api/v3/contacts?organization_id=' . APIZOHO['IdOrg'];
                $Param   = ['url' => $Url, 'method' => 'POST', 'header' => ["Authorization: $Token", "contentType: application/x-www-form-urlencoded;charset=UTF-8"], 'body' => $Json];
                $Result  = $ClassCdeV2->MyCurl_APIZOHO_V2($Param);
                $CreaCli = json_decode($Result, TRUE);

                // Création OK
                if ($CreaCli['code'] == "0") {
                    echo "<h3>=>" . $CreaCli['message'] . "</h3>";
                    $Retour_cli = $ClassCdeV2->UpdateCmd("UPDATE zoho_factures SET zoho_idclient='" . $CreaCli['contact']['contact_id'] . "' WHERE idunique='$idu'");

                    $Etat['zoho_idclient'] = $CreaCli['contact']['contact_id'];

                    if ($Retour_cli <> 'OK') {
                        echo "<h1>/!\ ERREUR </h1>";
                    } else {
                        $CreeZCRM = true;
                        $MemoIdu  = $idu;
                    }
                    echo "<pre>";
                    print_r($Retour_cli);
                    echo "</pre>";

                } // Création KO
                else {
                    $Retour_cli = $ClassCdeV2->UpdateCmd("UPDATE zoho_factures SET zoho_idclient='ERR',message='" . $CreaCli['message'] . "' WHERE idunique='$idu'");

                    echo "<pre>";
                    print_r($Json);
                    echo "</pre>";
                    echo "<pre>";
                    print_r($CreaCli);
                    echo "</pre>";

                    $Array = [
                        'to'      => 'luc@bvcs.fr', //
                        'subject' => '[AIRMOB/CDEV2] Erreur Création impossible',
                        'body'    => "Script interrompu car erreur de création client impossible : ".$CreaCli['message']."<br>Vous devez récupérer sur ZOHO BOOKS dans l url l'id du client et le copier dans [zoho_factures] zoho_idclient + nettoyer l erreur et ensuite relancer ",
                    ];
                    $Mel   = $ClassCdeV2->MySendMailPHPMailer($Array);

                    die("Création client impossible.<br>Si le client existe déjà se rendre sur ZBOOK et chercher le nom de Sté, copier l ID de l url dans la talbe zoho_factures champ zoho_idclient  ");
                }
            }

            // Cree les articles
            //  -------------------------
            echo "<pre>"; print_r($Etat); echo "</pre>";

            //  Détails des articles
            $Dtl_Cmd = json_decode($Cmd['detail_cmd'], TRUE);
            echo "<pre>";
            print_r($Dtl_Cmd);
            echo "</pre>";

            //  Extrait les articles Internet, Telephonie, Fibre
            $Type_arr = ['i', 't', 'f'];
            foreach ($Type_arr as $Type) {
                foreach ($Dtl_Cmd['dtl_cmd'][$Type] as $key => $dtl) {
                    $LigneCmd = [];
                    $RefArtZ  = $ClassCdeV2->ZohoReference($dtl['idart']);
                    if($dtl['idart']!="DEJA") {
                // Si ref abs
                    if (!$RefArtZ['ref_zoho']) $Err[] = "Réf. zoho manquante : " . $dtl['idart'];

                // Période
                    $Du = strtotime(date("Y-m-d", strtotime($Datepaiement)));
                    $Au = strtotime(date("Y-m-d", strtotime($Datepaiement)) . " +1 month");
                    if ($dtl['ctg'] == "offre") $description = "Du " . date("d/m/Y", $Du) . " au " . date("d/m/Y", $Au);
                    else                        $description = "";

                        // Ligne Article ZOHO
                        $CmdZOHO[] = ["item_id" => $RefArtZ['ref_zoho'], "quantity" => 1, "purchase_rate" => $dtl['rec'], "rate" => $dtl['rec'], "description" => $description];

                        // Ligne FAS
                        if ($dtl['fas']) {
                            $CmdZOHO[] = ["item_id" => "838708000003772193", "quantity" => 1, "purchase_rate" => $dtl['fas'], "rate" => $dtl['fas'], "description" => $dtl['ctg'] . " " . $dtl['nom']];
                        }
                    } else {
                        echo "Pas besoin d'offre DEJA";
                    }
                }
            }
            // Ligne Articles
            echo "<pre>"; print_r($CmdZOHO);  echo "</pre>";

        //  Si une erreur sur les articles
            if (count($Err)>0) {
                echo "<pre style='background: red'>";                echo "<h1>Erreurs</h1>";                print_r($Err);                echo "</pre>";
            }

        // Si pas deja un n° de facture lance la creation
            if (!$Etat['zoho_nofacture']) {

                // Cree la facture
                //  -------------------------
                if (count($Err) == 0) {

                    echo "<h1>=>Facture</h1>";
                    $notes    = "Paiement par carte bancaire sur site web Airmob.net";
                    $JsonFact = ['JSONString' => '{
                        "customer_id" : "' . $Etat['zoho_idclient'] . '",
                        "reference_number" : "' . $Etat['idunique'] . '",
                        "template_id" : "838708000003769005", 
                        "date":' . date('Y-m-d') . ',
                        "line_items" : ' . json_encode($CmdZOHO) . '
                        }'];

                // echo "<pre>"; print_r($JsonFact); echo "</pre>";

                    $Url     = 'https://books.zoho.com/api/v3/invoices?organization_id=' . APIZOHO['IdOrg'];
                    $ParamF  = ['url' => $Url, 'method' => 'POST', 'header' => ["Authorization: $Token", "contentType: application/x-www-form-urlencoded;charset=UTF-8"], 'body' => $JsonFact];
                    $ResultF = $ClassCdeV2->MyCurl_APIZOHO_V2($ParamF);
                    $Fact    = json_decode($ResultF, TRUE);

                // Array
                //    echo "<pre>"; print_r($Fact); echo "</pre>";
                    echo "<h1>ZBOOKS : ".$Fact['message']." :: ".$Fact['invoice']['invoice_number'] ."</h1>";

                    $Semaine3 = strtotime(date("Y-m-d", strtotime($Datepaiement)) . " +3 weeks");
                    $Semaine4 = strtotime(date("Y-m-d", strtotime($Datepaiement)) . " +4 weeks");

                // Facturation
                    if ($Fact['code'] == '0') {
                        $Retour_fact = $ClassCdeV2->UpdateCmd("UPDATE zoho_factures SET zoho_nofacture='" . $Fact['invoice']['invoice_number'] . "',zoho_datefact='" . date("Y-m-d", $Du) . "',semaine3='" . date("Y-m-d", $Semaine3) . "',semaine4='" . date("Y-m-d", $Semaine4) . "' WHERE idunique='$idu'");
                        if ($Retour_fact <> 'OK') echo "<h1>/!\ ERREUR </h1>";
                        echo "<pre>"; print_r($Retour_fact); echo "</pre>";
                    // Gère le paiement (fonctionne avec les données en dur)
                        //$customer_id = "838708000010515245"; $invoice_id = "838708000010512157"; $Totalttc = '93.6';

                        $Totalttc = $Cmd['montant'];

                        $JsonPaiement = ['JSONString' =>' {
                        "customer_id": "'.$Etat['zoho_idclient'].'",
                        "payment_mode": "creditcard",
                        "amount": '.$Totalttc.',
                        "date": "'.date('Y-m-d').'",
                        "description": "Paiement auto. depuis Commande V2",
                        "invoices": [{ "invoice_id": "'.$Fact['invoice']['invoice_id'].'","amount_applied": '.$Totalttc.'}]
                        }'];


                        $Url            = 'https://books.zoho.com/api/v3/customerpayments?organization_id='.APIZOHO['IdOrg'];
                        $ParamF         = ['url'=>$Url,'method'=>'POST','header'=>["Authorization: $Token","contentType: application/x-www-form-urlencoded;charset=UTF-8"],'body' =>  $JsonPaiement];
                        $ResultF = $ClassCdeV2->MyCurl_APIZOHO_V2($ParamF);
                        $Paid    = json_decode($ResultF, TRUE);

                        //echo "<pre style='border:1px solid #000'>"; print_r($Paid); echo "</pre>";

                        // Fin Gère le paiement

                        echo "<h1>ZBOOKS : ".$Paid['message']."</h1>";


                    } else {
                        $Retour_fact = $ClassCdeV2->UpdateCmd("UPDATE zoho_factures SET zoho_nofacture='ERR',message='" . $Fact['message'] . "' WHERE idunique='$idu'");
                        echo "<pre>";
                        print_r($Fact);
                        echo "</pre>";
                    }

                } else {
                    echo "<h1>=>Erreur : Facture non créé</h1>";

                    $Retour_fact = $ClassCdeV2->UpdateCmd("UPDATE zoho_factures SET zoho_nofacture='ERR',message='" . join('', $Err) . "' WHERE idunique='$idu'");
                    echo "<pre>";
                    print_r($Err);
                    echo "</pre>";
                }
            } else {
                echo "Facture déjà traitée...<br>";
            }

        //  La création du client ZBOOK est OK il faut creer dasn ZCRM
            if($CreeZCRM==true) {
                echo "<h1>Création CRM</h1>";
                $ch = curl_init();
                curl_setopt($ch,CURLOPT_URL,'https://airmob.net/commande_v2/zoho.crm.php?idu=$MemoIdu');
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_exec($ch);
                curl_close($ch);
            }
            echo "TERMINE<hr>";
        }
        die("FIN Nouvelle Commandes");
    } else {
        echo "<h1>Pas de commande à traiter...</h1>";
    }



// Controle les traitements à 3 semaines
echo "<h1>=>Semaine 3 (Emails)</h1>";
$ClassCdeV2->Semaine3();


echo "<h1>=>Semaine 4 </h1>";
$ClassCdeV2->Semaine4();

echo "<h1>=>Semaine PERIODIQUE </h1>";
$ClassCdeV2->Periodique();

echo "<h1>=>Semaine CR </h1>";
// Envoi un email RAPPORT pour le probleme
$ClassCdeV2->CRFactures();







?>