<?php

use App\Box;
use App\BoxOrder;
use App\CalendarTemplate;
use App\Company;
use App\Invoice;
use App\PaymentType;
use App\Pricing;
use App\Repositories\BoxRepository;
use App\Repositories\PreferenceRepository;
use App\Role;
use App\TrainingRoom;
use App\TrainingType;
use App\TrainingWorkout;
use App\TrainingWorkoutSection;
use App\UserSubscription;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use App\User;
use Faker\Factory as Faker;


class BoxesTableSeeder extends Seeder {
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        foreach(Company::all() as $i => $company) {
            //discount
            $company->discounts()->saveMany(factory(App\Discount::class, 2)->make());

            $company->boxes()->saveMany(factory(App\Box::class, 2)->make())->each(function ($box) use(&$company) {
                $faker = Faker::create();

                //pricings
                $box->pricing()->saveMany(factory(App\Pricing::class,2)->create([
                    "company_id"        => $company->id
                ]))->each(function ($p) use (&$faker, &$company, &$box){
                    $p->user_subscriptions()->saveMany(factory(App\UserSubscription::class, 10)->create([
                        "role_id"       => Role::where("slug", "athlete")->first()->id,
                        "wod_counter"   => $p->wod_counter,
                        "open_counter"  => $p->open_counter,
                        "total_counter" => $p->total_counter
                    ]))->each(function(UserSubscription $s) use(&$faker, &$p, &$box) {
                        factory(App\BoxOrder::class, $faker->numberBetween(1,3))->create([
                            'payment_id'    => factory(App\Payment::class)->create()->id,
                            'user_id'       => User::all()->random()->first()->id,
                            'box_id'        => $box->id
                        ])->each(function(BoxOrder $bo) use(&$s) {
                            $bo->lines()->save(factory(App\BoxOrderLine::class)->make([
                                'user_subscription_id' => $s->id
                            ]));
                            $bo->payment->update(["charged" => true]);
                            //la factura ja es crea sola
                        });
                    });
                });

                //bonos
                $box->pricing()->save(factory(App\Pricing::class)->create([
                    "name"              => "Bono",
                    "company_id"        => $company->id,
                    "recharge_weekly"   => false,
                    "days"              => null
                ]));

                //Create calendar templates for the box
                $box->calendarTemplates()->saveMany(factory(App\CalendarTemplate::class,3)->make())
                    ->each( function ($calendarTemplate){
                                $calendarTemplate->calendarTemplateExclusions()->saveMany(factory(App\CalendarTemplateExclusion::class,1)->make());
                            });

                //Products
                $box->boxProducts()->saveMany(factory(App\BoxProduct::class,2)->create([
                    'box_id' => $box->id
                ]));

                //Product image and variant
                $box->boxProducts()->each(function ($product){
                   $product->boxProductVariants()->saveMany(factory(App\BoxProductVariant::class,2)->create([
                       'box_product_id' => $product->id
                   ]));

                   $product->boxProductVariants()->each(function ($variant){
                      $variant->boxProductImages()->saveMany(factory(App\BoxProductImage::class,2)->make());
                   });
                });

                //Orders
                $box->boxOrders()->saveMany(factory(App\BoxOrder::class,60)->create([
                    'payment_id'    => factory(App\Payment::class)->create()->id,
                    'box_id'        => $box->id
                ]))->each(function ($boxOrder) use (&$box, &$company, &$faker){
                    //Orders Lines
                    $boxOrder->lines()->saveMany(factory(App\BoxOrderLine::class,2)->create([
                        'box_order_id'              => $boxOrder->id,
                        'box_product_variant_id'    => $box->boxProducts()->get()->random()->boxProductVariants()->get()->random()->id
                    ]));

                    $boxOrder->payment->update(["charged" => true]);

                    //la factura ja es crea sola
                });

                Invoice::all()->each( function ($invoice) use (&$faker) {
                    $invoice->update(["emitted_date" => $faker->dateTimeBetween('-100 days','now')]);
                });

                //training rooms
                $box->trainingRooms()->saveMany(factory(App\TrainingRoom::class, 2)->make());

                //box news
                $box->news()->saveMany(factory(App\News::class, 5)->create());

                //workouts
                $box->trainingWorkouts()->saveMany(factory(App\TrainingWorkout::class, 4)->make())->each(function(TrainingWorkout $w) {
                    $w->trainingWorkoutSections()->saveMany(factory(App\TrainingWorkoutSection::class, 1)->make())->each(function(TrainingWorkoutSection $s) {
                        $s->lines()->saveMany(factory(App\TrainingWorkoutLine::class, 3)->make());
                    });
                });

                //training types
                // Ara ja no fem servir training types per box, sino que son genèrics. Pero en farem algún d'extra.
                //$box->trainingTypes()->save(factory(App\TrainingType::class)->make());

                //Creem coaches
                factory(App\User::class, 2)->create()->each(function($coach) use(&$box, &$faker) {
                    $coach->user_subscriptions()->save(factory(App\UserSubscription::class)->create([
                        "user_id" => $coach->id,
                        "role_id" => Role::where("slug", "coach")->first()->id,
                        "pricing_id" => Pricing::whereHas("boxes", function($query) use($box) {
                                            $query->where("box_id", $box->id);
                                        })->get()->random()->first()->id,
                        "renew" => false,
                        "start_date" => Carbon::now()->addDays($faker->numberBetween(-30, -1)),
                        "end_date" => null,
                        "price" => null
                    ]));
                });

                //Ara generem una setmana real d'entrenaments
                //BoxRepository::generateSessions($box->id, Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek(), CalendarTemplate::where("box_id", $box->id)->first()->id, TrainingRoom::where("box_id", $box->id)->first()->id);
            });
        }

    }
}
