<!DOCTYPE html>
<html>
<?php
    /*
     * Etat des commandes passées
     * 1/ execution toutes les jours à 8 heures => etatcmd.cron.php
     * 2/ executé depuis stripe.confirme.php (si paiement confirmé)
     * liebn direct possible => etatcmd.cron.php?debug=true&idu=7b4e3b9eef3e04d97e76d844a3519062
     *
     * */

    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) {
        $Etats   = ['TERM'=>'Commande acceptée'];
        $subject = '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)'];
        $subject = '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']);
//  DEBUG : affichage
    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";

        $id                              = $Cde['id'];
        $MyArr[$Ope][$id]['creation']    = $Cde['creation'];
        $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
        /*
        $CdesD = mysqli_query($cnx, "SELECT * FROM cde_detail WHERE id_cde='$id' ") or die(mysqli_error());
        while ($CdeD = mysqli_fetch_array($CdesD, MYSQLI_ASSOC)) {
            $idD = $CdeD['id'];
            $MyArr[$Ope][$id]['Dtl'][$idD]['Total']['fas'] += $CdeD['fas'];
            $MyArr[$Ope][$id]['Dtl'][$idD]['Total']['rec'] += $CdeD['rec'];
            $MyArr[$Ope][$id]['Dtl'][$idD]['Produit']       = $CdeD['produit'];
            $MyArr[$Ope][$id]['Dtl'][$idD]['Offre']         = $CdeD['offre'];
            $MyArr[$Ope][$id]['Dtl'][$idD]['Detail']        = $CdeD['detail'];
        }
        */

        $Dtl_arr = json_decode($Cde['detail_cmd'],TRUE);


        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[$Ope][$id]['Dtl'][$not] = ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']." ".$dtl['ope']." ".$Deja." ".$Porta;
        }

        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[$Ope][$id]['Dtl'][$noi] = ucwords($dtl['ctg']) ." ".$dtl['Type']." ".$dtl['nom']." ".$dtl['ope']." ".$Deja;
        }

    }



    /*
     * 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  width='15%' valign='top'>Création<br>".$DtlCmd['creation']."</td>";
            $TD1['nomprenom']   = "<td  width='15%'>".$DtlCmd['nomprenom']."</td>";

            if($Etat=="TERM") {
                $TD1['montant_ttc'] = "<td width='10%' align='center'><b>" . $DtlCmd['montant'] . ' €</b></td>';
                $TD1['msg']         = "<td width='20%' align='center' width='20%'>" . $DtlCmd['msg'] . "</td>";
            } else {
                $TD1['montant_ttc'] = "<td width='10%'></td>";
                $TD1['msg']         = "<td width='20%'></td>";
            }

            $TD1['offre']   = "<td width='10%'>".$DtlCmd['offre']."</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><td></td></tr>\n";
                $TR[] = "<tr style='background:#f2f2f2'><td><b>Livraison</b></td><td>" . $DtlCmd['livraison'] . "</td><td></td><td></td><td></td></tr>\n";
            }


        // Liste les articles
            foreach($DtlCmd['Dtl'] as $Key=>$Dtl) {
                list($Art,$Cfg) = explode ('|',$Dtl);
                $TR[] = '<tr><td>' . $Art . '</td><td>' . $Cfg . '</td><td></td><td></td><td></td></tr>';
            }
            /*
            if($DtlCmd['Dtl']) {
                foreach($DtlCmd['Dtl'] as $idDtl=>$Dtl) {
                //  DEBUG : affichage
                //  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>";
    }
//  DEBUG : affichage
    //echo $Body;
    //exit;

    $Css     = "<style>body,td { font-family: arial; font-size:10pt;}</style>\n";
    $message = $Css."\n".$Body;

    //  DEBUG : affichage
    //echo "<pre>"; print_r($InfoMail); echo "</pre>";

//  Si lien contient (debug=true)
    if( $_REQUEST['debug'] ) {
        echo $message;
    }

//  DEBUG : affichage
//    echo "<pre>"; print_r($MyArr); echo "</pre>";


    if($_REQUEST['visu']) die('Vous etes en mode visu !');

/*
 * Send Email
 * */

    //$to      = 'contact@airmob.net';
    $to      = 'luc@bvcs.fr';

    $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($to, $subject, $message, $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);


?>