<?php

namespace common\models;

use Yii;
use common\helpers\Departements ;
use yii\helpers\Html ;

/**
 * This is the model class for table "etablissement".
 *
 * @property integer $id
 * @property string $nom
 * @property string $siret
 * @property string $logo
 * @property string $photo
 * @property string $description
 * @property string $code_postal
 * @property string $ville
 */
class Etablissement extends \yii\db\ActiveRecord
{
    const PAIEMENT_OK = 'ok' ;
    const PAIEMENT_ESSAI = 'essai' ;
    const PAIEMENT_ESSAI_TERMINE = 'essai-terminee' ;
    const PAIEMENT_RETARD = 'retard-paiement' ;
    
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'etablissement';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nom', 'siret', 'heure_limite_commande','delai_commande'], 'required'],
            [['heure_limite_commande','delai_commande'],'integer'],
            ['heure_limite_commande','in', 'range' => [18, 19, 20, 21, 22, 23, 24]],
            ['delai_commande','in', 'range' => [1,2,3,4,5,6,7]],
            ['code', function($attribute, $params) 
            {
                $code = $this->$attribute ;
                
                $etablissement = Etablissement::findOne(['code' => $code]) ;
                
                if($etablissement && $etablissement->id != $this->id)
                {
                    $this->addError($attribute, 'Ce code est déjà utilisé par une autre boulangerie.');
                }
            }],
            [['description'], 'string'],
            [['solde_negatif', 'credit_pain','actif'], 'boolean'],
            [['nom', 'siret', 'logo', 'photo', 'code_postal', 'ville','code'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'nom' => 'Nom',
            'siret' => 'Siret',
            'logo' => 'Logo',
            'photo' => 'Photo',
            'description' => 'Description',
            'code_postal' => 'Code postal',
            'ville' => 'Ville',
            'code' => 'Code',
            'heure_limite_commande' => 'Heure limite de commande',
            'delai_commande' => 'Délai de commande',
            'solde_negatif' => 'Solde négatif',
            'credit_pain' => 'Crédit pain',
            'actif' => 'Actif',
            'date_creation' => 'Date de création'
        ];
    }
    
    public function getUserEtablissement()
    {
        return $this->hasMany(UserEtablissement::className(), ['id_etablissement' => 'id']) ;
    }
    
    public function getUser()
    {
        return $this->hasMany(User::className(), ['id_etablissement' => 'id']) ;
    }
    
    public static function getEtablissementsPopulateDropdown() 
    {
        
        $etablissements_dispos = Etablissement::find()
                ->where(['actif' => 1])
                ->orderby('code_postal, ville ASC')
                ->all() ;
        
        $departements = Departements::get() ;
        $data_etablissements_dispos = [] ;
        $options_etablissements_dispos = [] ;
        foreach($etablissements_dispos as $e) 
        {
            if($e->etatPaiement() == self::PAIEMENT_OK || $e->etatPaiement() == self::PAIEMENT_ESSAI) 
            {
                if(!key_exists('d'.  substr($e->code_postal, 0, 2), $data_etablissements_dispos)) 
                {
                    $data_etablissements_dispos['d'.  substr($e->code_postal, 0, 2)] = '<strong>'.$departements[substr($e->code_postal, 0, 2)].'</strong>' ;
                    $options_etablissements_dispos['d'.  substr($e->code_postal, 0, 2)] = ['disabled' => true] ;
                }

                $data_etablissements_dispos[$e->id] = '<span class="glyphicon glyphicon-lock"></span> '.Html::encode($e->nom).' - '.Html::encode($e->code_postal).' '.Html::encode($e->ville).' <span class="glyphicon glyphicon-lock"></span>' ;
                
                if(strlen($e->code))
                    $options_etablissements_dispos[$e->id] = ['class' => 'lock'] ;
            }
        }
        
        return ['data' => $data_etablissements_dispos, 'options' => $options_etablissements_dispos] ;
    }
    
    public function etatPaiement() 
    {
        $date_limite = strtotime($this->date_creation) + 30*24*60*60 ;
        $date = time() ;
        $date_paiement = strtotime($this->date_paiement) ;

        if($date < $date_paiement + 30*24*60*60 || $this->gratuit)
        {
            return 'ok' ;
        }
        else {
            if($date < $date_limite) 
            {
                return 'essai' ;
            }
            else {
                if(!$this->date_paiement)
                    return 'essai-terminee' ;
                else
                    return 'retard-paiement' ;
            }
        }
    }
    
    public function getCA($periode = '', $format = false) 
    {
        if(!$periode)
            $periode = date('Y-m') ;
        
        $connection = Yii::$app->getDb();
        $command = $connection->createCommand('
            SELECT SUM(IF(produit.vrac,0,commande_produit.prix * commande_produit.quantite)) AS CA
            FROM commande, commande_produit, production, produit
            WHERE commande.id = commande_produit.id_commande
            AND production.id_etablissement = :id_etablissement
            AND commande.id_production = production.id
            AND commande_produit.id_produit = produit.id
            AND production.date > :date_debut
            AND production.date < :date_fin', 
                [
                    ':date_debut' => date('Y-m-31', strtotime("-1 month", strtotime($periode))),
                    ':date_fin' => date('Y-m-01', strtotime("+1 month", strtotime($periode))),
                    ':id_etablissement' => $this->id
                ]);

        $result = $command->queryOne();
        $ca = $result['CA'] ;
        
        if($format)
            return number_format($ca, 2).' €' ;
        else
            return $ca ;
    }
    
    public function getMontantFacturer($periode = '', $ca = 0, $format = false) 
    {
        if(!$periode)
            $periode = date('Y-m') ;
        
        if(!$ca)
            $ca = $this->getCA($periode) ;
        
        if($ca < 500)
        {
            $montant = 0 ;
        }
        else {
            $montant = $ca * 0.02 ;
        }
        
        if($format)
        {
            return number_format($montant, 2).' €' ;
        }
        else {
            return $montant ;
        }
    }
    
    public function getFacture($periode = '')
    {
        if(!$periode)
            $periode = date('Y-m', strtotime('-1 month')) ;
        
        $facture = Facture::find()
                ->where('id_etablissement = :id_etablissement')
                ->andWhere('periode = :periode')
                ->addParams([
                    ':id_etablissement' => $this->id,
                    ':periode' => $periode,
                ])
                ->one() ;
        
        return $facture ;
    }
    
    public function factureMoisDernier()
    {
        return $this->getFacture(date('Y-m', strtotime('-1 month'))) ;
    }
    
    public static function getConfig($config = '')
    {
        if(strlen($config))
        {
            $etablissement = self::findOne(Yii::$app->user->identity->id_etablissement) ;
            if($etablissement)
            {
                return $etablissement->$config ;
            }
        }
        
        return false ;
    }
}