<?php

/** 
Copyright La boîte à pain (2018) 

contact@laboiteapain.net

Ce logiciel est un programme informatique servant à aider les producteurs 
à distribuer leur production en circuits courts. 

Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
sur le site "http://www.cecill.info".

En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme,  le
titulaire des droits patrimoniaux et les concédants successifs.

A cet égard  l'attention de l'utilisateur est attirée sur les risques
associés au chargement,  à l'utilisation,  à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant 
donné sa spécificité de logiciel libre, qui peut le rendre complexe à 
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant  des  connaissances  informatiques approfondies.  Les
utilisateurs sont donc invités à charger  et  tester  l'adéquation  du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement, 
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. 

Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/

namespace backend\controllers;

class CommandeController extends BackendController {

    var $enableCsrfValidation = false;

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['report-cron'],
                        'allow' => true,
                        'roles' => ['?']
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return Yii::$app->user->identity->status == USER::STATUS_ADMIN || Yii::$app->user->identity->status == USER::STATUS_BOULANGER;
                        }
                    ]
                ],
            ],
        ];
    }

    public function actionReportCron($date = '', $save = false, $id_etablissement = 0, $key = '') {
        if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
            $this->actionReport($date, $save, $id_etablissement);
        }
    }

    public function actionReport($date = '', $save = false, $id_etablissement = 0) {

        if (!Yii::$app->user->isGuest)
            $id_etablissement = Yii::$app->user->identity->id_etablissement;

        $commandes = Commande::findBy([
            'date' => $date,
            'date_delete' => 'NULL',
            'id_etablissement' => $id_etablissement,
            'orderby' => 'commentaire_point_vente ASC, user.nom ASC'
        ]);

        foreach ($commandes as $c)
            $c->init();

        $production = Production::find()
                ->where('date LIKE \'' . $date . '\'')
                ->andWhere(['id_etablissement' => $id_etablissement])
                ->one();
        if ($production) {
            $produits_selec = ProductionProduit::findProduits($production->id);
            $points_vente = PointVente::find()
                    ->where(['id_etablissement' => $id_etablissement])
                    ->all();
            foreach ($points_vente as $pv)
                $pv->initCommandes($commandes);

            // produits
            $produits = Produit::find()
                    ->where(['id_etablissement' => $id_etablissement])
                    ->orderBy('order ASC')
                    ->all();

            // get your HTML raw content without any layouts or scripts
            $content = $this->renderPartial('report', [
                'production' => $production,
                'produits_selec' => $produits_selec,
                'points_vente' => $points_vente,
                'date' => $date,
                'produits' => $produits,
                'commandes' => $commandes
            ]);

            $date_str = date('d/m/Y', strtotime($date));

            if ($save) {
                $destination = Pdf::DEST_FILE;
            } else {
                $destination = Pdf::DEST_BROWSER;
            }

            $pdf = new Pdf([
                // set to use core fonts only
                'mode' => Pdf::MODE_UTF8,
                // A4 paper format
                'format' => Pdf::FORMAT_A4,
                // portrait orientation
                'orientation' => Pdf::ORIENT_PORTRAIT,
                // stream to browser inline
                'destination' => $destination,
                'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $id_etablissement . '.pdf'),
                // your html content input
                'content' => $content,
                // format content from your own css file if needed or use the
                // enhanced bootstrap css built by Krajee for mPDF formatting 
                //'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
                // any css to be embedded if required
                //'cssInline' => '.kv-heading-1{font-size:18px}', 
                // set mPDF properties on the fly
                //'options' => ['title' => 'Krajee Report Title'],
                // call mPDF methods on the fly
                'methods' => [
                    'SetHeader' => ['Commandes du ' . $date_str],
                    'SetFooter' => ['{PAGENO}'],
                ]
            ]);

            // return the pdf output as per the destination setting
            return $pdf->render();
        }
    }

    public function actionDeleteCommande($date, $id_commande) {

        $commande = Commande::find()
                ->with(['production', 'commandeProduits'])
                ->where(['id' => $id_commande])
                ->one();

        if ($commande) {
            $commande->init();

            // remboursement de la commande
            if ($commande->id_user && $commande->getMontantPaye() && Etablissement::getConfig('credit_pain')) {
                $commande->creditHistorique(
                    CreditHistorique::TYPE_REMBOURSEMENT, 
                    $commande->getMontantPaye(), 
                    $commande->production->id_etablissement, 
                    $commande->id_user,
                    Yii::$app->user->identity->id
                );
            }

            $commande->delete();
            CommandeProduit::deleteAll(['id_commande' => $id_commande]);
        }

        $this->redirect(['index', 'date' => $date]);
    }

    public function gestionFormCommandes($production, $date, $points_vente, $produits, $users) {

        if ($date != '') {
            // commandes
            $commandes = Commande::find()
                    ->with('commandeProduits', 'user')
                    ->joinWith('production')
                    ->where(['production.date' => $date])
                    ->andWhere(['production.id_etablissement' => Yii::$app->user->identity->id_etablissement])
                    ->all();

            foreach ($commandes as $c)
                $c->init();

            foreach ($points_vente as $pv) {
                $pv->initCommandes($commandes);

                if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {

                    // modifs 
                    foreach ($pv->commandes as $c) {

                        // suppression des commande_produit
                        $commande_produits = CommandeProduit::find()->where(['id_commande' => $c->id])->all();

                        foreach ($commande_produits as $cp)
                            $cp->delete();

                        // création des commande_produit modifiés
                        foreach ($produits as $p) {
                            $quantite = Yii::$app->getRequest()->post('produit_' . $c->id . '_' . $p->id, 0);
                            if ($quantite) {
                                $commande_produit = new CommandeProduit;
                                $commande_produit->id_commande = $c->id;
                                $commande_produit->id_produit = $p->id;
                                $commande_produit->quantite = $quantite;
                                $commande_produit->prix = $p->prix;
                                $commande_produit->save();
                            }
                        }
                    }

                    // ajout
                    //$id_client = Yii::$app->getRequest()->post('user_pv_'.$pv->id, 0) ;

                    $username = Yii::$app->getRequest()->post('username_pv_' . $pv->id, 0);
                    $date = Yii::$app->getRequest()->post('date_commande_pv_' . $pv->id, 0);
                    $one_product = false;
                    foreach ($produits as $p) {
                        $quantite = Yii::$app->getRequest()->post('produit_pv_' . $pv->id . '_' . $p->id, 0);
                        if ($quantite) {
                            $one_product = true;
                        }
                    }

                    if (strlen($username) && $date && $one_product) {
                        $commande = new Commande;
                        $commande->id_point_vente = $pv->id;
                        $commande->id_production = $production->id;
                        $commande->id_user = 0;
                        $commande->username = $username;
                        $tab_date = explode('/', $date);
                        $commande->date = $tab_date[2] . '-' . $tab_date[1] . '-' . $tab_date[0] . ' 00:00:00';
                        $commande->save();

                        foreach ($produits as $p) {
                            $quantite = Yii::$app->getRequest()->post('produit_pv_' . $pv->id . '_' . $p->id, 0);
                            if ($quantite) {
                                $commande_produit = new CommandeProduit;
                                $commande_produit->id_commande = $commande->id;
                                $commande_produit->id_produit = $p->id;
                                $commande_produit->quantite = $quantite;
                                $commande_produit->prix = $p->prix;
                                $commande_produit->save();
                            }
                        }
                    }
                }
            }
        }
    }

    public function actionIndex($date = '', $return_data = false) {

        if (!Produit::count() && !PointVente::count()) {
            $this->redirect(['site/index', 'erreur_produits_points_vente' => 1]);
        }

        $commandes = [];

        // users
        $arr_users = [0 => '--'];
        $users = User::find()->orderBy('prenom, nom ASC')->all();
        foreach ($users as $u) {
            $arr_users[$u->id] = $u->prenom . ' ' . $u->nom;
        }

        // création du jour de production
        $production = Production::initProduction($date) ;

        // points de vente
        if ($production) {
            $points_vente = PointVente::find()
                    ->joinWith(['productionPointVente' => function($q) use ($production) {
                            $q->where(['id_production' => $production->id]);
                        }])
                            ->where([
                                'id_etablissement' => Yii::$app->user->identity->id_etablissement,
                            ])
                            ->all();
        } else {
            $points_vente = PointVente::find()
                    ->where(['id_etablissement' => Yii::$app->user->identity->id_etablissement,])
                    ->all();
        }

        // produits
        $produits = Produit::getAll();

        // gestion des commandes
        $this->gestionFormCommandes($production, $date, $points_vente, $produits, $users);

        // commandes
        $commandes = Commande::findBy([
            'date' => $date,
            'date_delete' => 'NULL'
        ]);

        $recettes = 0;
        $recettes_pain = 0;
        $recettes_vrac = 0;
        $recettes_pain_livre = 0;
        $poids_pain = 0;
        $poids_vrac = 0;

        foreach ($commandes as $c) {
            $c->init();
            
            if(is_null($c->date_delete)) {
                $recettes += $c->montant;
                $recettes_pain += $c->montant_pain;
                $recettes_vrac += $c->montant_vrac;
                if ($c->id_point_vente != 1)
                    $recettes_pain_livre += $c->montant_pain;

                $poids_pain += $c->poids_pain;
                $poids_vrac += $c->poids_vrac;
            }
        }
        $recettes = number_format($recettes, 2);
        $recettes_pain = number_format($recettes_pain, 2);
        $recettes_vrac = number_format($recettes_vrac, 2);

        // init commandes point de vente
        foreach ($points_vente as $pv) {
            $pv->initCommandes($commandes);

            $data_select_commandes = [];
            $data_options_commandes = [];
            foreach ($pv->commandes as $c) {
                if ($c->user) {
                    $data_select_commandes[$c->id] = $c->user->nom . ' ' . $c->user->prenom;
                } else {
                    $data_select_commandes[$c->id] = $c->username;
                }

                $data_options_commandes[$c->id] = [];
                $array_options = [];
                $array_options[$c->id]['montant'] = $c->montant;
                $array_options[$c->id]['str_montant'] = number_format($c->montant, 2, ',', '') . ' €';
                $array_options[$c->id]['montant_paye'] = $c->montant_paye;
                $array_options[$c->id]['produits'] = [];
                $array_options[$c->id]['commentaire'] = Html::encode($c->commentaire);
                foreach ($c->commandeProduits as $cp) {
                    $array_options[$c->id]['produits'][$cp->id_produit] = $cp->quantite;
                }

                $data_options_commandes[$c->id]['data-commande'] = json_encode($array_options[$c->id]);
                $data_options_commandes[$c->id]['value'] = $c->id;
            }
            $pv->data_select_commandes = $data_select_commandes;
            $pv->data_options_commandes = $data_options_commandes;
        }

        // gestion produits selec
        if (isset($_POST['valider_produit_selec'])) {

            if (isset($_POST['Produit'])) {

                foreach ($produits as $p) {
                    $produit_production = ProductionProduit::find()->where(['id_production' => $production->id, 'id_produit' => $p->id])->one();

                    if (!$produit_production) {
                        $produit_production = new ProductionProduit();
                        $produit_production->id_production = $production->id;
                        $produit_production->id_produit = $p->id;
                        $produit_production->actif = 0;

                        if (isset($p->quantite_max))
                            $produit_production->quantite_max = $p->quantite_max;
                        else
                            $produit_production->quantite_max = null;

                        $produit_production->save();
                    }

                    if (isset($_POST['Produit'][$p->id]['actif'])) {
                        $produit_production->actif = 1;
                    } else {
                        $produit_production->actif = 0;
                    }

                    if ((isset($_POST['Produit'][$p->id]['quantite_max']) && $_POST['Produit'][$p->id]['quantite_max'] != '')) {
                        $produit_production->quantite_max = (int) $_POST['Produit'][$p->id]['quantite_max'];
                    } else {
                        $produit_production->quantite_max = null;
                    }

                    $produit_production->save();
                }
            }
        }

        // init produits sélectionnés pour cette production
        $produits_selec = [];
        if ($production) {
            $day_production = date('N', strtotime($production->date));
            $produits_production = ProductionProduit::find()->where(['id_production' => $production->id])->all();

            if (!count($produits_production)) {
                foreach ($produits as $p) {
                    $pp = new ProductionProduit();
                    $pp->id_production = $production->id;
                    $pp->id_produit = $p->id;

                    $pp->actif = 0;
                    if ($p->actif && $day_production == 1 && $p->lundi)
                        $pp->actif = 1;
                    if ($p->actif && $day_production == 2 && $p->mardi)
                        $pp->actif = 1;
                    if ($p->actif && $day_production == 3 && $p->mercredi)
                        $pp->actif = 1;
                    if ($p->actif && $day_production == 4 && $p->jeudi)
                        $pp->actif = 1;
                    if ($p->actif && $day_production == 5 && $p->vendredi)
                        $pp->actif = 1;
                    if ($p->actif && $day_production == 6 && $p->samedi)
                        $pp->actif = 1;
                    if ($p->actif && $day_production == 7 && $p->dimanche)
                        $pp->actif = 1;

                    $pp->quantite_max = $p->quantite_max;

                    $pp->save();
                }
            }

            // produits selec pour production
            $produits_selec = ProductionProduit::findProduits($production->id);
        }

        // produit en vrac forcément activé
        if ($date != '') {
            foreach ($produits as $p) {
                $produit_production = ProductionProduit::find()->where(['id_production' => $production->id, 'id_produit' => $p->id])->one();
                if ($p->vrac) {
                    if (!$produit_production) {
                        $produit_production = new ProductionProduit();
                        $produit_production->id_production = $production->id;
                        $produit_production->id_produit = $p->id;
                        $produit_production->quantite_max = 0;
                        $produit_production->actif = 1;
                        $produit_production->save();
                    } else {
                        $produit_production->actif = 1;
                        $produit_production->save();
                    }
                }
            }
        }

        // produits
        if ($production)
            $produits = Produit::getByProduction($production->id);

        // poids total de la production et CA potentiel
        $ca_potentiel = 0;
        $poids_total = 0;
        foreach ($produits_selec as $id_produit_selec => $produit_selec) {
            if ($produit_selec['actif']) {
                foreach ($produits as $produit) {
                    if ($produit->id == $id_produit_selec) {
                        //echo $produit->nom.' : '.$produit_selec['quantite_max'].'<br />' ;
                        $ca_potentiel += $produit_selec['quantite_max'] * $produit->prix;
                        $poids_total += $produit_selec['quantite_max'] * $produit->poids / 1000;
                    }
                }
            }
        }

        // jours de production
        $jours_production = Production::find()
                ->where([
                    'actif' => 1,
                    'id_etablissement' => Yii::$app->user->identity->id_etablissement
                ])
                ->all();

        // commandes auto
        $model_commande_auto = new CommandeAutoForm;

        // productions point vente
        $production_point_vente = new ProductionPointVente;

        $productions_point_vente = [];
        if ($production) {
            $productions_point_vente = ProductionPointVente::find()
                    ->with('pointVente')
                    ->where(['id_production' => $production->id])
                    ->all();
        }

        $arr_productions_point_vente = [];
        
        foreach ($productions_point_vente as $ppv) {
            $key = $ppv->id_production . '-' . $ppv->id_point_vente;
            if ($ppv->livraison == 1)
                $production_point_vente->productions_point_vente[] = $key;
            if(isset($ppv->pointVente) && strlen($ppv->pointVente->nom)) {
                $arr_productions_point_vente[$key] = Html::encode($ppv->pointVente->nom);
            }
        }
        
        // une production de la semaine activée ou non
        $production_semaine_active = false ;
	$week = sprintf('%02d',date('W',strtotime($date)));
	$start = strtotime(date('Y',strtotime($date)).'W'.$week);
        $date_lundi = date('Y-m-d',strtotime('Monday',$start)) ;
        $date_mardi = date('Y-m-d',strtotime('Tuesday',$start)) ;
        $date_mercredi = date('Y-m-d',strtotime('Wednesday',$start)) ;
        $date_jeudi = date('Y-m-d',strtotime('Thursday',$start)) ;
        $date_vendredi = date('Y-m-d',strtotime('Friday',$start)) ;
        $date_samedi = date('Y-m-d',strtotime('Saturday',$start)) ;
        $date_dimanche = date('Y-m-d',strtotime('Sunday',$start)) ;
        
        $production_semaine = Production::find()
                ->andWhere([
                    'id_etablissement' => Yii::$app->user->identity->id_etablissement,
                    'actif' => 1,
                ])
                ->andWhere(['or',
                    ['date' => $date_lundi], 
                    ['date' => $date_mardi],
                    ['date' => $date_mercredi],
                    ['date' => $date_jeudi],
                    ['date' => $date_vendredi],
                    ['date' => $date_samedi],
                    ['date' => $date_dimanche],
                ])
                ->one();
        if($production_semaine) {
            $production_semaine_active = true ;
        }
	
        
        $datas = [
            'produits' => $produits,
            'points_vente' => $points_vente,
            'commandes' => $commandes,
            'date' => $date,
            'production' => $production,
            'jours_production' => $jours_production,
            'produits_selec' => $produits_selec,
            'users' => $arr_users,
            'recettes' => $recettes,
            'recettes_pain' => $recettes_pain,
            'recettes_vrac' => $recettes_vrac,
            'recettes_pain_livre' => $recettes_pain_livre,
            'poids_pain' => $poids_pain,
            'poids_vrac' => $poids_vrac,
            'ca_potentiel' => $ca_potentiel,
            'poids_total' => $poids_total,
            'model_commande_auto' => $model_commande_auto,
            'production_point_vente' => $production_point_vente,
            'productions_point_vente' => $productions_point_vente,
            'arr_productions_point_vente' => $arr_productions_point_vente,
            'production_semaine_active' =>$production_semaine_active
        ];

        if ($return_data) {
            return $datas;
        } else {
            return $this->render('index', $datas);
        }
    }

    public function actionDownload($date = '', $id_point_vente = 0, $global = 0) {

        // commandes
        $commandes = Commande::find()
                ->with('commandeProduits', 'user')
                ->joinWith('production')
                ->where(['production.date' => $date])
                ->orderBy('date ASC')
                ->all();

        foreach ($commandes as $c)
            $c->init();

        // points de vente
        $points_vente = PointVente::find()->all();
        foreach ($points_vente as $pv)
            $pv->initCommandes($commandes);

        // produits
        $produits = Produit::find()->orderBy('order ASC')->all();

        $production = Production::find()->where('date LIKE \'' . $date . '\'')->one();
        $produits_selec = ProductionProduit::findProduits($production->id);

        /*
         * export global
         */
        if ($global) {

            $data = [];
            $filename = 'export_' . $date . '_global';

            $num_jour_semaine = date('w', strtotime($date));
            $arr_jour_semaine = [0 => 'dimanche', 1 => 'lundi', 2 => 'mardi', 3 => 'mercredi', 4 => 'jeudi', 5 => 'vendredi', 6 => 'samedi'];
            $champs_horaires_point_vente = 'horaires_' . $arr_jour_semaine[$num_jour_semaine];

            // par point de vente
            foreach ($points_vente as $pv) {
                if (count($pv->commandes) && strlen($pv->$champs_horaires_point_vente)) {

                    $line = [$pv->nom, 'Produits', 'Montant', 'Commentaire'];

                    $data[] = $line;

                    $res = $this->contentPointVenteCSV($date, $produits, $points_vente, $pv->id);
                    foreach ($res['data'] as $line) {
                        $data[] = $line;
                    }
                }

                if (count($pv->commandes) && strlen($pv->$champs_horaires_point_vente)) {

                    $line = ['Total pain'];
                    $str_produits = '';
                    foreach ($produits as $p) {
                        if (!$p->vrac && isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                            $quantite = Commande::getQuantiteProduit($p->id, $pv->commandes);
                            $str_quantite = '';
                            if ($quantite) {
                                $str_quantite = $quantite;
                                $str_produits .= $str_quantite . $p->diminutif . ', ';
                            }
                        }
                    }
                    $line[] = substr($str_produits, 0, strlen($str_produits) - 2);
                    $line[] = number_format($pv->recettes_pain, 2) . ' €';
                    $data[] = $line;

                    $line = ['Total vrac'];
                    $str_produits = '';
                    foreach ($produits as $p) {
                        if ($p->vrac && isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                            $quantite = Commande::getQuantiteProduit($p->id, $pv->commandes);
                            $str_quantite = '';
                            if ($quantite) {
                                $str_quantite = $quantite;
                                $str_produits .= $str_quantite . $p->diminutif . ', ';
                            }
                        }
                    }
                    $line[] = substr($str_produits, 0, strlen($str_produits) - 2);
                    $line[] = number_format($pv->recettes_vrac, 2) . ' €';
                    $data[] = $line;

                    $data[] = [];
                }
            }

            // récap
            //$line = ['Totaux'] ;
            // pain
            $line = ['Total pain'];
            $str_produits = '';
            foreach ($produits as $p) {
                if (!$p->vrac && isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                    $quantite = Commande::getQuantiteProduit($p->id, $commandes);
                    $str_quantite = '';
                    if ($quantite) {
                        $str_quantite = $quantite;
                        $str_produits .= $str_quantite . '' . $p->diminutif . ', ';
                    }
                }
            }
            $line[] = substr($str_produits, 0, strlen($str_produits) - 2);

            $data[] = $line;

            // vrac
            $line = ['Total vrac'];
            $str_produits = '';
            foreach ($produits as $p) {
                if ($p->vrac && isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                    $quantite = Commande::getQuantiteProduit($p->id, $commandes);
                    $str_quantite = '';
                    if ($quantite) {
                        $str_quantite = $quantite;
                        $str_produits .= $str_quantite . '' . $p->diminutif . ', ';
                    }
                }
            }
            $line[] = substr($str_produits, 0, strlen($str_produits) - 2);

            $data[] = $line;


            $infos = $this->actionIndex($date, true);

            CSV::downloadSendHeaders($filename . '.csv');
            echo CSV::array2csv($data);
            die();
        }
        /*
         * export individuel
         */ else {
            if ($commandes && count($commandes)) {

                $data = [];

                // par point de vente
                if ($id_point_vente) {
                    $res = $this->contentPointVenteCSV($date, $produits, $points_vente, $id_point_vente);
                    $data = $res['data'];
                    $filename = $res['filename'];
                }
                // récapitulatif
                else {
                    $res = $this->contentRecapCSV($date, $produits, $points_vente, $commandes);
                    $filename = 'recapitulatif_' . $date;
                    $data = $res['data'];
                }

                CSV::downloadSendHeaders($filename . '.csv');
                echo CSV::array2csv($data);
                die();
            }
        }
    }

    public function contentRecapCSV($date, $produits, $points_vente, $commandes) {

        $data = [];
        $filename = 'recapitulatif_' . $date;

        $production = Production::find()->where('date LIKE \'' . $date . '\'')->one();
        $produits_selec = ProductionProduit::findProduits($production->id);

        // head
        $data[0] = ['Lieu'];
        foreach ($produits as $p) {
            if (isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                $data[0][] = $p->description;
            }
        }

        $num_jour_semaine = date('w', strtotime($date));
        $arr_jour_semaine = [0 => 'dimanche', 1 => 'lundi', 2 => 'mardi', 3 => 'mercredi', 4 => 'jeudi', 5 => 'vendredi', 6 => 'samedi'];
        $champs_horaires_point_vente = 'horaires_' . $arr_jour_semaine[$num_jour_semaine];


        // datas
        foreach ($points_vente as $pv) {
            if (count($pv->commandes) && strlen($pv->$champs_horaires_point_vente)) {
                $data_add = [$pv->nom];
                foreach ($produits as $p) {
                    if (isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                        $data_add[] = Commande::getQuantiteProduit($p->id, $pv->commandes);
                    }
                }
                $data[] = $data_add;
            }
        }

        $data_add = ['Total'];
        foreach ($produits as $p) {
            if (isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                $data_add[] = Commande::getQuantiteProduit($p->id, $commandes);
            }
        }
        $data[] = $data_add;

        return [
            'data' => $data,
            'filename' => $filename
        ];
    }

    public function contentPointVenteCSV($date, $produits, $points_vente, $id_point_vente) {

        $data = [];

        $production = Production::find()->where('date LIKE \'' . $date . '\'')->one();
        $produits_selec = ProductionProduit::findProduits($production->id);

        // head
        /* $data[0] = ['Client', 'Date commande'] ;
          foreach($produits as $p) {
          if(isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
          $data[0][] = $p->description ;
          }
          } */

        // datas
        foreach ($points_vente as $pv) {
            if ($pv->id == $id_point_vente) {

                $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pv->nom));

                foreach ($pv->commandes as $c) {

                    $str_user = '';

                    // username
                    if ($c->user) {
                        $str_user = $c->user->prenom . " " . $c->user->nom; //.' - '.date('d/m', strtotime($c->date)) ;
                    } else {
                        $str_user = $c->username; //.' - '.date('d/m', strtotime($c->date)) ;
                    }

                    // téléphone
                    if (isset($c->user) && strlen($c->user->telephone)) {
                        $str_user .= ' (' . $c->user->telephone . ')';
                    }

                    $data_add = [$str_user];

                    // produits
                    $str_produits = '';
                    foreach ($produits as $p) {
                        if (isset($produits_selec[$p->id]['actif']) && $produits_selec[$p->id]['actif']) {
                            $add = false;
                            foreach ($c->commandeProduits as $cp) {
                                if ($p->id == $cp->id_produit) {
                                    $str_produits .= $cp->quantite . '' . $p->diminutif . ', ';
                                    $add = true;
                                }
                            }
                        }
                    }

                    $data_add[] = substr($str_produits, 0, strlen($str_produits) - 2);

                    $data_add[] = number_format($c->montant, 2) . ' €';

                    $data_add[] = $c->commentaire;

                    $data[] = $data_add;
                }
            }
        }

        return [
            'data' => $data,
            'filename' => $filename
        ];
    }
    
    public function actionAddCommandesAuto($date) {
        CommandeAuto::addAll($date, true);
        $this->redirect(['index', 'date' => $date]);
    }

    public function actionChangeState($date, $actif, $redirect = true) {
        
        // changement état
        $production = Production::initProduction($date) ;
        $production->actif = $actif;
        $production->save();

        if ($actif) {
            // add commandes automatiques
            CommandeAuto::addAll($date);
        }

        if($redirect)
            $this->redirect(['index', 'date' => $date]);
    }
    
    public function actionChangeStateSemaine($date, $actif) {
        
        $week = sprintf('%02d',date('W',strtotime($date)));
	$start = strtotime(date('Y',strtotime($date)).'W'.$week);
        $date_lundi = date('Y-m-d',strtotime('Monday',$start)) ;
        $date_mardi = date('Y-m-d',strtotime('Tuesday',$start)) ;
        $date_mercredi = date('Y-m-d',strtotime('Wednesday',$start)) ;
        $date_jeudi = date('Y-m-d',strtotime('Thursday',$start)) ;
        $date_vendredi = date('Y-m-d',strtotime('Friday',$start)) ;
        $date_samedi = date('Y-m-d',strtotime('Saturday',$start)) ;
        $date_dimanche = date('Y-m-d',strtotime('Sunday',$start)) ;
                
        $points_vente = PointVente::find()
            ->where(['id_etablissement' => Yii::$app->user->identity->id_etablissement,])
            ->all();
        
        $lundi_active = false ;
        $mardi_active = false ;        
        $mercredi_active = false ;
        $jeudi_active = false ;
        $vendredi_active = false ;
        $samedi_active = false ;
        $dimanche_active = false ;
        
        foreach($points_vente as $pv) {
            if($pv->livraison_lundi) $lundi_active = true ;
            if($pv->livraison_mardi) $mardi_active = true ;
            if($pv->livraison_mercredi) $mercredi_active = true ;
            if($pv->livraison_jeudi) $jeudi_active = true ;
            if($pv->livraison_vendredi) $vendredi_active = true ;
            if($pv->livraison_samedi) $samedi_active = true ;
            if($pv->livraison_dimanche) $dimanche_active = true ;
        }
        
        if($lundi_active || !$actif) $this->actionChangeState($date_lundi, $actif, false) ;
        if($mardi_active || !$actif) $this->actionChangeState($date_mardi, $actif, false) ;
        if($mercredi_active || !$actif) $this->actionChangeState($date_mercredi, $actif, false) ;
        if($jeudi_active || !$actif) $this->actionChangeState($date_jeudi, $actif, false) ;
        if($vendredi_active || !$actif) $this->actionChangeState($date_vendredi, $actif, false) ;
        if($samedi_active || !$actif) $this->actionChangeState($date_samedi, $actif, false) ;
        if($dimanche_active || !$actif) $this->actionChangeState($date_dimanche, $actif, false) ;

        $this->redirect(['index', 'date' => $date]);
    }

    public function actionChangeLivraison($date, $livraison) {
        $production = Production::find()->where(['date' => $date])->one();
        $production->livraison = $livraison;
        $production->save();
        $this->redirect(['index', 'date' => $date]);
    }

    public function actionAjaxUpdate($id_commande, $produits, $date, $commentaire) {
        $commande = Commande::find()->with('production', 'creditHistorique', 'user')->where(['id' => $id_commande])->one();

        if ($commande &&
                $commande->production->id_etablissement == Yii::$app->user->identity->id_etablissement) {
            $commande->init();
            $produits = json_decode($produits);
            foreach ($produits as $key => $quantite) {
                $commande_produit = CommandeProduit::findOne([
                            'id_commande' => $id_commande,
                            'id_produit' => $key
                        ]);

                if ($quantite) {
                    if ($commande_produit) {

                        $commande_produit->quantite = $quantite;
                    } else {

                        $produit = Produit::findOne($key);

                        if ($produit) {
                            $commande_produit = new CommandeProduit;
                            $commande_produit->id_commande = $id_commande;
                            $commande_produit->id_produit = $key;
                            $commande_produit->quantite = $quantite;
                            $commande_produit->prix = $produit->prix;
                        }
                    }

                    $commande_produit->save();
                } else {
                    if ($commande_produit)
                        $commande_produit->delete();
                }
            }

            $commande->date_update = date('Y-m-d H:i:s');
            $commande->commentaire = $commentaire;
            $commande->save();

            // data commande
            $json_commande = $commande->getDataJson();

            // total point de vente
            $point_vente = PointVente::findOne($commande->id_point_vente);
            $commandes = Commande::find()
                    ->with('commandeProduits', 'user')
                    ->joinWith('production')
                    ->where(['production.date' => $date])
                    ->andWhere(['production.id_etablissement' => Yii::$app->user->identity->id_etablissement])
                    ->orderBy('date ASC')
                    ->all();
            foreach ($commandes as $c)
                $c->init();
            $point_vente->initCommandes($commandes);

            echo json_encode([
                'total_pv' => number_format($point_vente->recettes, 2) . ' €',
                'json_commande' => $json_commande
            ]);

            die();
        }
    }

    public function actionAjaxDelete($date, $id_commande) {
        $commande = Commande::find()
                ->with(['production', 'commandeProduits'])
                ->where(['id' => $id_commande])
                ->one();
        $commande->init() ;

        // delete
        if ($commande) {
            // remboursement si l'utilisateur a payé pour cette commande
            $montant_paye = $commande->getMontantPaye();
            if ($montant_paye > 0.01) {
                $commande->creditHistorique(
                    CreditHistorique::TYPE_REMBOURSEMENT, 
                    $montant_paye, 
                    Yii::$app->user->identity->id_etablissement, 
                    $commande->id_user,
                    Yii::$app->user->identity->id
                );
            }

            $commande->delete();
            CommandeProduit::deleteAll(['id_commande' => $id_commande]);
        }

        // total point de vente
        $point_vente = PointVente::findOne($commande->id_point_vente);
        $commandes = Commande::find()
                ->with('commandeProduits', 'user')
                ->joinWith('production')
                ->where(['production.date' => $date])
                ->andWhere(['production.id_etablissement' => Yii::$app->user->identity->id_etablissement])
                ->orderBy('date ASC')
                ->all();
        foreach ($commandes as $c)
            $c->init();
        $point_vente->initCommandes($commandes);

        echo json_encode([
            'total_pv' => number_format($point_vente->recettes, 2) . ' €',
        ]);

        die();
    }

    public function actionAjaxCreate($date, $id_pv, $id_user, $username, $produits, $commentaire) {
        $produits = json_decode($produits);
        $point_vente = PointVente::findOne($id_pv);
        $production = Production::findOne([
                    'date' => $date,
                    'id_etablissement' => Yii::$app->user->identity->id_etablissement
                ]);

        if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date) &&
                ($id_user || strlen($username)) &&
                $point_vente &&
                count($produits) &&
                $production) {
            $commande = new Commande;
            $commande->date = date('Y-m-d H:i:s', strtotime($date . ' ' . date('H:i:s')));
            $commande->id_point_vente = $id_pv;
            $commande->id_production = $production->id;
            $commande->type = Commande::TYPE_ADMIN;
            $commande->commentaire = $commentaire;

            if ($id_user) {
                $commande->id_user = $id_user;

                // commentaire du point de vente
                $point_vente_user = PointVenteUser::find()
                        ->where(['id_point_vente' => $id_pv, 'id_user' => $id_user])
                        ->one();

                if ($point_vente_user && strlen($point_vente_user->commentaire)) {
                    $commande->commentaire_point_vente = $point_vente_user->commentaire;
                }
            } else {
                $commande->username = $username;
                $commande->id_user = 0;
            }

            $commande->save();

            foreach ($produits as $key => $quantite) {
                $produit = Produit::findOne($key);
                if ($produit) {
                    $commande_produit = new CommandeProduit;
                    $commande_produit->id_commande = $commande->id;
                    $commande_produit->id_produit = $key;
                    $commande_produit->quantite = $quantite;
                    $commande_produit->prix = $produit->prix;
                    $commande_produit->save();
                }
            }

            // total point de vente
            $point_vente = PointVente::findOne($commande->id_point_vente);
            $commandes = Commande::find()
                    ->with('commandeProduits', 'user')
                    ->joinWith('production')
                    ->where(['production.date' => $date])
                    ->andWhere(['production.id_etablissement' => Yii::$app->user->identity->id_etablissement])
                    ->orderBy('date ASC')
                    ->all();
            foreach ($commandes as $c)
                $c->init();
            $point_vente->initCommandes($commandes);

            // json commande
            $commande = Commande::find()
                    ->with('commandeProduits', 'user')
                    ->where(['commande.id' => $commande->id])
                    ->one();
            $commande->init();

            $produits = [];
            foreach ($commande->commandeProduits as $cp) {
                $produits[$cp->id_produit] = $cp->quantite;
            }

            $json_commande = json_encode(['montant' => number_format($commande->montant, 2), 'produits' => $produits]);
            $json_commande = $commande->getDataJson();

            $str_user = '';
            if ($commande->user)
                $str_user = $commande->user->nom . ' ' . $commande->user->prenom;
            else
                $str_user = $commande->username;

            $str_commentaire = '';
            if (strlen($commande->commentaire)) {
                $str_commentaire = ' <span class="glyphicon glyphicon-comment"></span>';
            }

            $str_label_type_commande = '';
            if ($commande->type) {
                $str_label_type_commande = ' <span class="label label-warning">vous</span>';
            }

            echo json_encode([
                'id_commande' => $commande->id,
                'total_pv' => number_format($point_vente->recettes, 2) . ' €',
                'commande' => '<li>'
                . '<a class="btn btn-default" href="javascript:void(0);" '
                . 'data-pv-id="' . $id_pv . '" '
                . 'data-id-commande="' . $commande->id . '" '
                . 'data-commande=\'' . $json_commande . '\' '
                . 'data-date="' . date('d/m H:i', strtotime($commande->date)) . '">'
                . '<span class="montant">' . number_format($commande->montant, 2) . ' €</span>'
                . '<span class="user">' . $str_label_type_commande . ' ' . $str_user . '</span>'
                . $str_commentaire
                . '</a></li>',
            ]);
            die();
        }
    }

    public function actionAjaxTotalCommandes($date) {

        $production = Production::find()
                ->where(['date' => $date])
                ->andWhere(['id_etablissement' => Yii::$app->user->identity->id_etablissement])
                ->one();


        if ($production) {
            // produits
            $produits = Produit::find()
                    ->where(['id_etablissement' => Yii::$app->user->identity->id_etablissement])
                    ->orderBy('order ASC')
                    ->all();



            // commandes
            $commandes = Commande::find()
                    ->with('commandeProduits','commandeProduits.produit', 'user')
                    ->joinWith('production')
                    ->where(['production.date' => $date])
                    ->andWhere(['production.id_etablissement' => Yii::$app->user->identity->id_etablissement])
                    ->orderBy('date ASC')
                    ->all();

            $recettes = 0;
            $poids_pain = 0;
            foreach ($commandes as $c) {
                $c->init();
                
                if(is_null($c->date_delete)) {
                    $recettes += $c->montant;
                    $poids_pain += $c->poids_pain;
                }
            }

            // produits selec pour production
            $produits_selec = ProductionProduit::findProduits($production->id);


            $ca_potentiel = 0;
            $poids_total = 0;
            foreach ($produits_selec as $id_produit_selec => $produit_selec) {
                if ($produit_selec['actif']) {
                    foreach ($produits as $produit) {
                        if ($produit->id == $id_produit_selec) {
                            $ca_potentiel += $produit_selec['quantite_max'] * $produit->prix;
                            $poids_total += $produit_selec['quantite_max'] * $produit->poids / 1000;
                        }
                    }
                }
            }

            $html_totaux = $this->renderPartial('_total_commandes.php', [
                'produits' => $produits,
                'commandes' => $commandes,
                'produits_selec' => $produits_selec,
                'recettes_pain' => $recettes,
                'poids_total' => $poids_total,
                'ca_potentiel' => $ca_potentiel,
                'poids_pain' => $poids_pain,
            ]);


            echo json_encode([
                'html_totaux' => $html_totaux,
            ]);
        }

        die();
    }

    public function actionAjaxPointVenteLivraison($id_production, $id_point_vente, $bool_livraison) {

        $production_point_vente = ProductionPointVente::find()
                ->where([
                    'id_production' => $id_production,
                    'id_point_vente' => $id_point_vente,
                ])
                ->one();

        if ($production_point_vente) {
            $production_point_vente->livraison = $bool_livraison;
            $production_point_vente->save();
        }

        die();
    }

    public function actionStatutPaiement($id_commande) {
        $commande = Commande::find()
                ->with('commandeProduits', 'production')
                ->where(['id' => $id_commande])
                ->one();

        if ($commande) {
            $commande->init();
            $html = '';

            if ($commande->id_user) {
                $user_etablissement = UserEtablissement::find()
                        ->where([
                            'id_user' => $commande->id_user,
                            'id_etablissement' => $commande->production->id_etablissement
                        ])
                        ->one();

                $montant_paye = $commande->getMontantPaye();
                //$html .= $commande->montant.' | '.$montant_paye ;

                if (abs($commande->montant - $montant_paye) < 0.0001) {
                    $html .= '<span class="label label-success">Payé</span>';
                    $buttons_credit = Html::a('Rembourser ' . $commande->getMontantFormat(), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $commande->montant, 'data-type' => 'remboursement']);
                } elseif ($commande->montant > $montant_paye) {
                    $montant_payer = $commande->montant - $montant_paye;
                    $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($montant_payer, 2) . ' €</strong> à payer';
                    $buttons_credit = Html::a('Payer ' . number_format($montant_payer, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $montant_payer, 'data-type' => 'paiement']);
                } elseif ($commande->montant < $montant_paye) {
                    $montant_rembourser = $montant_paye - $commande->montant;
                    $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($montant_rembourser, 2) . ' €</strong> à rembourser';
                    $buttons_credit = Html::a('Rembourser ' . number_format($montant_rembourser, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $montant_rembourser, 'data-type' => 'remboursement']);
                }

                $html .= '<span class="buttons-credit">'
                        . 'Crédit pain : <strong>' . number_format($user_etablissement->credit, 2) . '  €</strong><br />'
                        . $buttons_credit
                        . '</span>';

                // historique
                $historique = CreditHistorique::find()
                        ->with('userAction')
                        ->where(['id_commande' => $id_commande])
                        ->all();

                $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
                        . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
                        . '<tbody>';

                if ($historique && is_array($historique) && count($historique)) {
                    foreach ($historique as $h) {
                        $html .= '<tr>'
                                . '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
                                . '<td>' . Html::encode($h->strUserAction()) . '</td>'
                                . '<td>' . $h->getStrLibelle() . '</td>'
                                . '<td>' . ($h->isTypeDebit() ? '- '.$h->getMontant(true) : '') . '</td>'
                                . '<td>' . ($h->isTypeCredit() ? '+ '.$h->getMontant(true) : '') . '</td>'
                                . '</tr>';
                    }
                } else {
                    $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
                }

                $html .= '</tbody></table>';
            } else {
                $html .= '<div class="alert alert-warning">Pas de gestion de crédit pain pour cette commande car elle n\'est pas liée à un compte utilisateur.</div>';
            }

            echo json_encode([
                'html_statut_paiement' => $html,
                'json_commande' => $commande->getDataJson()
            ]);
        }

        die();
    }

    public function actionPaiement($id_commande, $type, $montant) {
        $commande = Commande::find()
                ->with('commandeProduits', 'production')
                ->where(['id' => $id_commande])
                ->one();
        
        $commande->init() ;
        
        if ($commande) {
            $commande->creditHistorique(
                $type, 
                $montant, 
                Yii::$app->user->identity->id_etablissement, 
                $commande->id_user,
                Yii::$app->user->identity->id
            );
        }

        return $this->actionStatutPaiement($id_commande);
    }

}