<?php

/**
 * Copyright distrib (2018)
 *
 * contact@opendistrib.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 common\models;

use common\helpers\Debug;
use common\helpers\GlobalParam;
use common\helpers\Price;
use Yii;
use common\components\ActiveRecordCommon;

/**
 * This is the model class for table "product".
 *
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property integer $active
 * @property string $photo
 * @property double $price
 * @property double $pweight
 * @property string $recipe
 * @property string $unit
 * @property double $step
 */
class Product extends ActiveRecordCommon
{
        public $total = 0;
        public $apply_distributions = true;

        public $price_with_tax = 0 ;
        public $wording_unit = '' ;

        public static $unitsArray = [
                'piece' => [
                        'unit' => 'piece',
                        'wording_unit' => 'la pièce',
                        'wording' => 'pièce(s)',
                        'wording_short' => 'p.',
                        'coefficient' => 1
                ],
                'g' => [
                        'unit' => 'g',
                        'wording_unit' => 'le g',
                        'wording' => 'g',
                        'wording_short' => 'g',
                        'coefficient' => 1000
                ],
                'kg' => [
                        'unit' => 'kg',
                        'wording_unit' => 'le kg',
                        'wording' => 'kg',
                        'wording_short' => 'kg',
                        'coefficient' => 1
                ],
                'mL' => [
                        'unit' => 'mL',
                        'wording_unit' => 'le mL',
                        'wording' => 'mL',
                        'wording_short' => 'mL',
                        'coefficient' => 1000
                ],
                'L' => [
                        'unit' => 'L',
                        'wording_unit' => 'le litre',
                        'wording' => 'L',
                        'wording_short' => 'L',
                        'coefficient' => 1
                ],
        ];

        /**
         * @inheritdoc
         */
        public static function tableName()
        {
                return 'product';
        }

        /**
         * @inheritdoc
         */
        public function rules()
        {
                return [
                        [['name', 'id_producer', 'id_tax_rate'], 'required'],
                        [['active', 'order', 'quantity_max', 'id_producer', 'id_tax_rate'], 'integer'],
                        [['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'unavailable', 'apply_distributions'], 'boolean'],
                        [['price', 'weight', 'step'], 'number'],
                        [['photo'], 'file'],
                        [['name', 'description', 'photo', 'unit'], 'string', 'max' => 255],
                        [['recipe'], 'string', 'max' => 1000],
                        ['step', 'required', 'message' => 'Champs obligatoire', 'when' => function ($model) {
                                if ($model->unit != 'piece') {
                                        return true;
                                }
                                return false;
                        }],
                        [['price_with_tax', 'wording_unit'], 'safe']
                ];
        }

        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
                return [
                        'id' => 'ID',
                        'name' => 'Nom',
                        'description' => 'Description',
                        'active' => 'Actif',
                        'photo' => 'Photo',
                        'price' => 'Prix (€) TTC',
                        'weight' => 'Poids',
                        'recipe' => 'Recette',
                        'monday' => 'Lundi',
                        'tuesday' => 'Mardi',
                        'wednesday' => 'Mercredi',
                        'thursday' => 'Jeudi',
                        'friday' => 'Vendredi',
                        'saturday' => 'Samedi',
                        'sunday' => 'Dimanche',
                        'order' => 'Ordre',
                        'quantity_max' => 'Quantité max par défaut',
                        'unavailable' => 'Épuisé',
                        'apply_distributions' => 'Appliquer ces modifications dans les distributions futures',
                        'unit' => 'Unité',
                        'step' => 'Pas',
                        'id_tax_rate' => 'TVA'
                ];
        }

        public function afterFind() {
                if ($this->taxRate == null) {
                        $this->populateRelation('taxRate', GlobalParam::getCurrentProducer()->taxRate);
                }

                $this->wording_unit = Product::strUnit($this->unit) ;
                $this->price_with_tax = $this->getpriceWithTax() ;

                parent::afterFind();
        }

        public function getProductDistribution()
        {
                return $this->hasMany(ProductDistribution::className(), ['id_product' => 'id']);
        }

        public function getProductSubscription()
        {
                return $this->hasMany(ProductSubscription::className(), ['id_product' => 'id']);
        }

        public function getTaxRate()
        {

                return $this->hasOne(TaxRate::className(), ['id' => 'id_tax_rate']);
        }

        /**
         * Retourne les options de base nécessaires à la fonction de recherche.
         *
         * @return array
         */
        public static function defaultOptionsSearch()
        {
                return [
                        'with' => ['taxRate'],
                        'join_with' => [],
                        'orderby' => 'order ASC',
                        'attribute_id_producer' => 'product.id_producer'
                ];
        }

        /**
         * Retourne la description du produit.
         *
         * @return string
         */
        public function getDescription()
        {
                $description = $this->description;
                if (isset($this->weight) && is_numeric($this->weight) && $this->weight > 0) {
                        if ($this->weight >= 1000) {
                                $description .= ' (' . ($this->weight / 1000) . 'kg)';
                        } else {
                                $description .= ' (' . $this->weight . 'g)';
                        }
                }
                return $description;
        }

        /**
         * Retourne le libellé (admin) du produit.
         * @return type
         */
        public function getStrWordingAdmin()
        {
                return $this->name;
        }

        /**
         * Enregistre le produit.
         *
         * @param boolean $runValidation
         * @param array $attributeNames
         * @return boolean
         */
        public function save($runValidation = true, $attributeNames = NULL)
        {
                $this->id_producer = GlobalParam::getCurrentProducerId();
                return parent::save($runValidation, $attributeNames);
        }

        /**
         * Retourne les produits d'une production donnée.
         *
         * @param integer $idDistribution
         * @return array
         */
        public static function searchByDistribution($idDistribution)
        {
                return Product::find()
                        ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
                        ->where([
                                'id_producer' => GlobalParam::getCurrentProducerId(),
                                'product_distribution.id_distribution' => $idDistribution
                        ])
                        ->orderBy('product_distribution.active DESC, product.order ASC')
                        ->all();
        }

        /**
         * Retourne le nombre de produits du producteur courant.
         *
         * @return integer
         */
        public static function count()
        {
                return self::searchCount();
        }

        /**
         * Retourne le produit "Don".
         *
         * @return Product
         */
        public static function getProductGift()
        {
                $productGift = Product::find()
                        ->where([
                                'product.id_producer' => 0
                        ])
                        ->andFilterWhere(['like', 'product.name', 'Don'])
                        ->one();

                return $productGift;
        }

        /**
         * Retourne le libellé d'une unité.
         *
         * @param $format wording_unit, wording, short
         * @param $unitInDb Unité stockée en base de données (ex: si g > kg, si mL > L)
         * @return $string Libellé de l'unité
         */
        public static function strUnit($unit, $format = 'wording_short', $unitInDb = false)
        {
                $strUnit = '';

                if ($unitInDb) {
                        if ($unit == 'g') {
                                $unit = 'kg';
                        }
                        if ($unit == 'mL') {
                                $unit = 'L';
                        }
                }

                if (isset(self::$unitsArray[$unit]) && isset(self::$unitsArray[$unit][$format])) {
                        $strUnit = self::$unitsArray[$unit][$format];
                }

                return $strUnit;
        }

        /**
         * Retourne le prix du produit avec taxe
         */
        public function getPriceWithTax()
        {

                return Price::getPriceWithTax($this->price, $this->taxRate->value);
        }


}