<?php

use App\Box;
use App\Repositories\BoxRepository;
use App\Repositories\TrainingWorkoutRepository;
use App\TrainingType;
use App\TrainingWorkout;
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;

class TrainingSessionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        $faker = Faker::create();
        foreach(Box::all() as $box) {
            $box->trainingSessions()->saveMany(factory(App\TrainingSession::class, 10)->make([
                "coach_id"              => sizeof($coaches = collect(BoxRepository::coachesActive($box->id)))>0 ? $coaches->random()->first()->id : null,
                "box_id"                => $box->id,
            ]))->each(function($session) use(&$box, &$workout_id, &$faker) {
                //set training room and type
                $session->update([
                    "training_room_id" => $box->trainingRooms()->get()->random()->id,
                ]);

                //Apuntar users
                foreach(BoxRepository::users($box->id, true) as $u) {
                    if($faker->boolean(70)) {
                        if(!$u->trainingSessions->contains($session->id))  {
                            $session->users()->attach($u->id,["type" => TrainingType::find($session->training_type_id)->slug]);
                            if($faker->boolean(10)) {
                                $workout_id = $session->training_workout_id;
                                $session->userBenchmarks()->save(factory(App\UserBenchmark::class)->make(
                                    [
                                        "user_id" => $u->id,
                                        "training_workout_id" => $session->training_workout_id
                                    ]
                                ))->each(function($benchmark) use(&$workout_id) {
                                    $benchmark->user_benchmark_sections()->saveMany(factory(App\UserBenchmarkSection::class, count(TrainingWorkoutRepository::find($workout_id)->trainingWorkoutSections))->make([
                                        "training_workout_section_id" => TrainingWorkout::find($workout_id)->trainingWorkoutSections()->get()->random()->id
                                    ]))->each(function ($benchmarkSection) use (&$workout_id) {
                                        $benchmarkSection->user_benchmark_lines()->saveMany(factory(App\UserBenchmarkLine::class, 1)->make([
                                            'training_workout_line_id' => TrainingWorkout::find($workout_id)->trainingWorkoutSections()->get()->random()->lines()->get()->random()->id
                                        ]));
                                    });
                                });
                            }
                        }
                    }
                }

            });
        }
    }
}
