
<center><h2><strong>Ubuntu</strong></h2>
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
    /*
     * Etat des commandes passées
     * 1/ execution toutes les jours à 8h,12h,15h,18h
     * 2/ executé depuis stripe.confirme.php (si paiement confirmé)
     *
     *
     * lien direct possible sans envoi de mail !
     * => etatcmdv2.cron.php?debug=true&visu=true&idu=7b4e3b9eef3e04d97e76d844a3519062
     * https://airmob.net/commande_v2/etatcmdv2.cron.php?debug=true&visu=true&idu=5e7b38ab4e9f2
     *
     * */

    error_reporting(E_ALL);
    ini_set("display_errors", 0);

//  Si lancé depuis stripe.confirme.php
    if(!$idu) {
        include_once("./lib/gestion.lib.php");
    }


//  Si lien direct /etatcmd.cron.php?idu=05102db19bec3170f76bf40c339d41fa
    if($_REQUEST['idu']) $idu = $_REQUEST['idu'];

//
    $MyCde   = new ClassCdeV2();
    $Dern24h = date("Y-m-d H:i:s",mktime(date("H")-24,date("i"),date("s"),date("m"), date("d"),date("Y")));
    $cnx     = $MyCde->CnxDBaseSQL();

    if($_REQUEST['debug']) echo "<h1>Mode visu</h1>Aucun envoi de mail ni d'enreg. dans le xml";

//  Envoi toutes les commandes ou la cde accepté
    if($idu) {
        if( $_REQUEST['debug'] )  $Etats   = ['TERM'=>'x Commande(s) terminée(s)','NONTERM'=>'x Commande(s) NON terminée(s)'];
        else                      $Etats   = ['TERM'=>'Commande acceptée'];
        $subjectCtc = 'Nouvelle commande AIRMOB';
        $Critere = "idunique='".$idu."'";
        $DtlPA   = true;
    } else {
        $Etats   = ['TERM'=>'x Commande(s) terminée(s)','NONTERM'=>'x Commande(s) NON terminée(s)'];
        $subjectCtc = 'Etat des commandes AIRMOB';
    //  $Critere = "1";
    //  $Critere = "creation LIKE '$Hier%'"; // Date de la veille
        $Critere = "creation >= '$Dern24h' && creation<='".date('Y-m-d H:i:s')."'"; // Date de la veille
        $DtlPA   = false;
    }


    /*
    $MyCde->ListeProduits(['data_i', 'opt_i','data_t','opt_t']);
    echo "<pre>"; print_r($_SESSION['AIRCMDV2']['NomProduits']); echo "</pre>";
    */

    /*
     * Stock les commandes
     * */

    $Cdes    = mysqli_query($cnx, "SELECT * FROM commandes_v2 WHERE $Critere ") or die(mysqli_error());
    $CpteCmd =  $Cdes->num_rows;;

    while ($Cde = mysqli_fetch_array($Cdes, MYSQLI_ASSOC)) {
        if(!$Cde['paiement']) $Ope = "NONTERM"; else $Ope = "TERM";

        $CdeEnCours = $Cde;

        $id                              = $Cde['id'];
        $MyArr[$Ope][$id]['creation']    = $Cde['creation'];
        $MyArr[$Ope][$id]['bdc']         = $Cde['nobdc'];
        $MyArr[$Ope][$id]['nomprenom']   = "<b>".$Cde['nomprenom']."</b><br>".$Cde['email']." / ".$Cde['telephone']."<br>Sté : ".$Cde['nomsociete']." (".$Cde['siret'].")";
        $MyArr[$Ope][$id]['telephone']   = $Cde['telephone'];

        $MyArr[$Ope][$id]['facturation'] = $Cde['nofacturation']." ".$Cde['adrfacturation']."<br>".$Cde['cpfacturation']." ".$Cde['villefacturation'];
        $MyArr[$Ope][$id]['livraison']   = $Cde['nolivraison']." ".$Cde['adrlivraison']."<br>".$Cde['cplivraison']." ".$Cde['villelivraison'];

        $MyArr[$Ope][$id]['offre']       = $Cde['idoffre'];
        $MyArr[$Ope][$id]['msg']         = $Cde['msg'];

    // Si paiement
        if($Ope == "TERM") {
            $MyArr[$Ope][$id]['montant']  = $Cde['montant'];
            $MyArr[$Ope][$id]['paiement'] = $Cde['paiement'];
        }

    // Detail de la cde
        $Dtl_arr = json_decode($Cde['detail_cmd'],TRUE);
// Array
    //echo "<pre>"; print_r($Dtl_arr); echo "</pre>";


        foreach($Dtl_arr['dtl_cmd']['t'] as $not=>$dtl) {
        // La porta est pour l instant dasn Telephonie exclusivement
            if($dtl['ctg']=="offre" && $dtl['num']) $Porta = "|Conserver le numero : ".$dtl['num']." / Code RIO : ".$dtl['num'];
            else                                    $Porta = "";
        //  Deja une ligne
            if($dtl['tel'])                         $Deja = "|Déjà numéro : ".$dtl['tel'];
            else                                    $Deja = "";

            $MyArr_Ml['Dtl_Mail'][$not]=  "<li>".ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']."</li>"; // Detail Art pour Mail

            $MyArr[$Ope][$id]['Dtl'][$not]['art'] = ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']." ".$dtl['ope']." ".$Deja." ".$Porta;
            $MyArr[$Ope][$id]['Dtl'][$not]['fas'] = $dtl['fas'];
            $MyArr[$Ope][$id]['Dtl'][$not]['rec'] = $dtl['rec'];
            $MyArr[$Ope][$id]['Dtl'][$not]['qte'] = $dtl['qte'];

        }

        foreach($Dtl_arr['dtl_cmd']['i'] as $noi=>$dtl) {
            //  Deja une ligne
            if($dtl['tel'])                         $Deja = "|Déjà numéro : ".$dtl['tel'];
            else                                    $Deja = "";

            $MyArr_Ml['Dtl_Mail'][$noi]= "<li>".ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']."</li>" ; // Detail Art pour Mail

            $MyArr[$Ope][$id]['Dtl'][$noi]['art'] = ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']." ".$dtl['ope']." ".$Deja;
            $MyArr[$Ope][$id]['Dtl'][$noi]['fas'] = $dtl['fas'];
            $MyArr[$Ope][$id]['Dtl'][$noi]['rec'] = $dtl['rec'];
            $MyArr[$Ope][$id]['Dtl'][$noi]['qte'] = $dtl['qte'];
        }

        foreach($Dtl_arr['dtl_cmd']['f'] as $noi=>$dtl) {

            $MyArr_Ml['Dtl_Mail'][$noi]= "<li>".ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']."</li>" ; // Detail Art pour Mail

            $MyArr[$Ope][$id]['Dtl'][$noi]['art'] = ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']." ".$dtl['ope']." ".$Deja;
            $MyArr[$Ope][$id]['Dtl'][$noi]['fas'] = $dtl['fas'];
            $MyArr[$Ope][$id]['Dtl'][$noi]['rec'] = $dtl['rec'];
            $MyArr[$Ope][$id]['Dtl'][$noi]['qte'] = $dtl['qte'];
            $MyArr[$Ope][$id]['Dtl'][$noi]['abo'] = $dtl['abo'];
        }

    }


    // Array
    //    echo "<pre>"; print_r($MyArr); echo "</pre>";

    /*
     * Format HTML
     * */
    foreach($Etats as $Etat=>$EtatLib) {
        $TABLE  = array();
        $TD1    = array();
        $TR     = array();

    // Commande Entete
        foreach($MyArr[$Etat] as $idCde=>$DtlCmd) {
            $TD1                = [];
            $TD1['creation']    = "<td  valign='top'><b>Création</b><br>".$DtlCmd['creation']."</td>";
            $TD1['nomprenom']   = "<td >".$DtlCmd['nomprenom']."</td>";

            if($Etat=="TERM") {
                $TD1['montant_ttc'] = "<td align='center' valign='top'><h3> ".$DtlCmd['bdc']."<br>" . number_format($DtlCmd['montant'] , 2, ',', ' '). ' € TTC</h3></td>';
                $TD1['msg']         = "<td align='center' valign='top' ><h3>" . $DtlCmd['msg'] . "</h3></td>";
            } else {
                $TD1['montant_ttc'] = "<td >.</td>";
                $TD1['msg']         = "<td >.</td>";
            }


            $TR[]           = "<tr style='background:#f2f2f2'>".join('',$TD1)."</tr>\n";
            if ($DtlPA==true) {
                $TR[] = "<tr style='background:#f2f2f2'><td><b>Facturation</b></td><td>" . $DtlCmd['facturation'] . "</td><td></td><td></td></tr>\n";
                $TR[] = "<tr style='background:#f2f2f2'><td><b>Livraison</b></td><td>" . $DtlCmd['livraison'] . "</td><td></td><td></td></tr>\n";
            }


        // Liste les articles
            $Total_Rec=0;
                $Total_Fas=0;
            $TR[] = '<tr style="font-weight: bold;"><td><b>Détail article(s)</b></td><td  align="center">Abonnement</td><td  align="center">Frais de mise en service</td><td  align="center">Total</td></tr>';
            foreach($DtlCmd['Dtl'] as $Key=>$Dtl) {
                list($Art,$Cfg) = explode ('|',$Dtl['art']);

                if($Dtl['qte']) $qte =$Dtl['qte']; else $qte ="1";

                ($Dtl['abo']) ? $Abo = "(Abo : ".$Dtl['abo']." mois) " : $Abo ="";

                $TR[] = '<tr><td>'.$qte .' x '. $Art.$Cfg . $Abo.'</td>
                        <td align="center">'.number_format($Dtl["rec"], 2, ',', ' ').'</td>
                        <td align="center">'.number_format($Dtl["fas"], 2, ',', ' ').'</td>
                        <td></td></tr>';

                $Total_Rec += $Dtl["rec"];
                $Total_Fas += $Dtl["fas"];
            }
            $HT = ($Total_Rec+$Total_Fas);
            $TVA = (($Total_Rec+$Total_Fas)*20/100);
            $TTC = $HT+$TVA;

        //  Totaux
            $TR[] = '<tr style="background:#f5f5f5; font-weight: bold;"><td>Totaux HT</td>
                     <td align="center">'.number_format($Total_Rec, 2, ',', ' ').'</td>
                     <td align="center">'.number_format($Total_Fas, 2, ',', ' ').'</td>
                     <td align="center">'.number_format($HT, 2, ',', ' ').'</td>
                     </tr>';
            $TR[] = "<tr style=\"background:#f5f5f5; font-weight: bold;\"><td>TVA 20%</td>
                     <td></td>
                     <td></td>
                     <td align=\"center\">".number_format($TVA, 2, ',', ' ')."</td>
                     </tr>";

            $TR[] = "<tr style=\"background:#f5f5f5; font-weight: bold;\"><td>TTC</td>
                     <td></td>
                     <td></td>
                     <td align=\"center\">".number_format($TTC, 2, ',', ' ')."</td>
                     </tr>";
            /*
            if($DtlCmd['Dtl']) {
                foreach($DtlCmd['Dtl'] as $idDtl=>$Dtl) {
                //  echo "<pre>"; print_r($Dtl); echo "</pre>";
                    if($Dtl['Produit']!='pack') { // Exclu le nom du pack déjà présent dans l entete
                    // Affiche les détails pour les articles
                        if ($DtlPA==true) {
                            $DetailArticle = json_decode($Dtl['Detail'], true);
                            $Lignex = [];
                            foreach ($DetailArticle as $KeyNom => $Val) {
                                if(!$Val) $Val= "n.c.";
                                $Lignex[] = "<b>" . $KeyNom . "</b>=" . $Val;
                            }
                            $DtlLigne  = join(', ', $Lignex);
                            $DetailCde = " (".$DtlLigne.")";
                        } else {
                            $DetailCde = "";
                        }

                        $TD2['Offre'] = "<td style='font-style: italic;' colspan='".count($TD1)."'><li>" . $Ref[$Dtl['Produit']][$Dtl['Offre']]['nom'] . $DetailCde."</li></td>";
                        $TR[] = '<tr>' . join('', $TD2) . '</tr>';
                    }
                }
            } else {
                $TR[] = "<tr><td style='font-style: italic;' colspan='".count($TD1)."'><li>Pas de détail</li></td></tr>\n";
            }
            */

            $TR[] = "<tr><td colspan='".count($TD1)."' style='border-top:1px solid #000'>&nbsp;</td></tr>\n";

        }

        $Qte = count($MyArr[$Etat]);


        $TABLE[]= "<TABLE cellpadding='5' cellspacing='0' border='0' width='100%'>\n";
        $TABLE[]=  "<tr style='background:#ccc'><td colspan='".count($TD1)."'><h3>$Qte $EtatLib</h3></td></tr>\n";
        $TABLE[]=  "<tr>".join('',$TR)."</tr>\n";
        $TABLE[]= "</TABLE><br>\n\n";
        $Body .= join ('',$TABLE);

        $XmlQte[] = "<qte_$Etat>".$Qte."</qte_$Etat>";
    }

    $Css     = "<style>body,td { font-family: arial; font-size:10pt;}</style>\n";
    $messageContact = $Css."\n".$Body;

//  Si lien contient (debug=true)
    if( $_REQUEST['debug'] ) {
        echo $messageContact;
    }

    if($_REQUEST['visu']) die('Vous etes en mode visu ! Pas d envoi de mail à contact@');

/*
 * ENVOI d EMAIL
 * */

// @CLIENT si $Msg Valide de STRIPE si appel en direct le mail n est pas envoyé

    if($Msg && $CdeEnCours['email']) {

        $to = $CdeEnCours['email'];

    // Sujet
        $subject = 'Commande AIRMOB';
        $body    = "Bonjour " . $CdeEnCours['nomprenom'] . ", <br>
        <br>
        Nous accusons réception de votre commande et nous remercions de votre confiance.<br>
        <br>
        Voici un récapitulatif de votre commande :<br> 
        <br>
        Prénom Nom : " . $CdeEnCours['nomprenom'] . "<br> 
        Entreprise : " . $CdeEnCours['nomsociete'] . "<br>
        Numéro de téléphone : " . $CdeEnCours['telephone'] . "<br> 
        Mail : " . $CdeEnCours['email'] . "<br>
        N° de commande : " . $CdeEnCours['nobdc'] . "<br>
        Offre souscrite : <br>
        " .join('', $MyArr_Ml['Dtl_Mail']). "<br><br>
        Montant TTC : " . number_format($CdeEnCours['montant'], 2, ',', ' ') . "<br>
        Adresse de facturation : " . $CdeEnCours['nofacturation'] . " " . $CdeEnCours['adrfacturation'] . " " . $CdeEnCours['cpfacturation'] . " " . $CdeEnCours['villefacturation'] . "<br>
        Adresse de livraison : " . $CdeEnCours['nolivraison'] . " " . $CdeEnCours['adrlivraison'] . " " . $CdeEnCours['cplivraison'] . " " . $CdeEnCours['villelivraison'] . "<br>
        <br><br>
        Afin de procéder à l'expédition de votre commande, nous aurions besoin par retour d'e-mail du KBIS de votre société.<br> 
        <br>
        Nous pourrons ainsi vous assurer une livraison à l'adresse indiquée à J+1. *<br>
        <br>
        Vous recevrez ensuite une facture sous 10 jours ouvrés.<br> 
        <br><br>
        Pour toute question complémentaire relative à votre commande, n'hésitez pas à nous contacter au 05 82 99 31 31 ou par e-mail à service-client@airmob.net. 
        <br>
        Très bonne journée,
        ";


        $Mention = "<p style='font-size:0.8em'>*
        Les commandes effectuées du lundi au jeudi avant 12H seront livrées le lendemain avant 13h.<br> 
        Les commandes effectuées le vendredi avant 12H seront livrées le lundi avant 13h. <br>
        Les commandes effectuées le samedi et le dimanche seront livrées mardi avant 13h.</p>";

    // message
        $message = '
         <html>
          <head>
           <title>Titre</title>
          </head>
          <style>
          body {font-family: arial;}
          </style>
          <body data-rsssl=1>
            ' . utf8_decode($body) . '
            <br><br>
            Le service client AIRMOB.<br>
           <img src="https://airmob.net/wp-content/uploads/2019/12/logo-dark.png"><br><br>
           ' . utf8_decode($Mention) . '
          </body>
         </html>
         ';

    // Pour envoyer un mail HTML, l'en-tête Content-type doit être défini
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-type: text/html; charset=iso-8859-1';

    // En-têtes additionnels
        $headers[] = 'To: <'.$CdeEnCours['email'].'>';
        $headers[] = 'From: AIRMOB <contact@airmob.net>';


    // Envoi
        $success = mail($to, $subject, $message, implode("\r\n", $headers));
        //echo "Envoi mail client ".$CdeEnCours['email']." (1 si ok) => " . $success;

        if($success) {
            /*
            $fileTxt = "log/arch.txt";
            $fp = fopen($fileTxt, 'a'); // a+ ajoute / w ecrase
            fwrite($fp, utf8_decode($body)."-----------------------------------------------------------------------------------------\r\n");
            fclose($fp);
            */
        }

    }

// @AIRMOB Contact
    $toCtc      = 'contact@airmob.net';
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
    $headers .= 'From: AIRMOB (Cdes V2) <contact@airmob.net>' . "\r\n";
    $SendMail = 0;

    if($CpteCmd>0) {
    // Commande envoyée
        if (mail($toCtc, $subjectCtc, $messageContact, $headers)) {
            $EtatEnvoi = "ok";
            $DateEnvoi = date('Y-m-d H:i:s');
        }
    //  Erreur d envoi
        else                                            {
            $EtatEnvoi = "erreur";
        }
    } else {
        //  Pas de commande à envoyer
        $EtatEnvoi = "aucun";
    }

//  Fichier dashboard XML
    $XML[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    $XML[] = "<CMD>";
    $XML[] = "<info>";
    $XML[] = join('', $XmlQte);
    $XML[] = "<cron>" . date("Y-m-d H:i:s") . "</cron>";
    $XML[] = "<date_envoi>" . $DateEnvoi . "</date_envoi>";
    $XML[] = "<etat_envoi>" . $EtatEnvoi . "</etat_envoi>";
    $XML[] = "</info>";
    $XML[] = "</CMD>";
    $fpW = fopen("xml/dash.lv.xml", "w");
    fwrite($fpW, join('', $XML));
    fclose($fpW);

?>