<?php

use yii\db\Migration;

class m190226_084104_lien_utilisateur_point_de_vente extends Migration
{
    public function up()
    {
        $producersArray = \common\models\Producer::find()->all() ;
        
        foreach($producersArray as $producer) {
            $pointsSaleArray = common\models\PointSale::find()
                ->where([
                    'id_producer' => $producer->id
                ])
                ->all();
            
            foreach($pointsSaleArray as $pointSale) {
                $usersArray = common\models\User::find()->innerJoin(
                    'order', 
                    'user.id = order.id_user AND order.id_point_sale = :id_point_sale',
                    [':id_point_sale' => $pointSale->id]
                )
                ->groupBy('user.id')
                ->all();
                
                foreach($usersArray as $user) {
                    $userPointSale = \common\models\UserPointSale::find()
                            ->where([
                                'id_user' => $user->id,
                                'id_point_sale' => $pointSale->id
                            ])->one() ;
                    
                    if(!$userPointSale) {
                        $userPointSale = new \common\models\UserPointSale() ;
                        $userPointSale->id_user = $user->id ;
                        $userPointSale->id_point_sale = $pointSale->id ;
                        $userPointSale->save() ;
                    }
                }
            }
        }
        
    }

    public function down()
    {
        echo "m190226_084104_lien_utilisateur_point_de_vente cannot be reverted.\n";
        return false;
    }
}
