<?php


namespace App\Repositories;


use App\UserBenchmark;
use App\UserBenchmarkLine;
use App\UserBenchmarkSection;
use Illuminate\Support\Facades\DB;

class UserBenchmarkRepository implements RepositoryInterface
{
    public static function all() {
        return UserBenchmark::all();
    }

    public static function create(array $data) {

        DB::beginTransaction();
        try {
            $userBenchmark = UserBenchmark::create($data);
            if(isset($data['user_benchmark_sections'])){
                foreach ($data['user_benchmark_sections'] as $section) {
                    if(!isset($section["user_benchmark_lines"])) throw new \Exception("Please provide some lines for the section.");
                    $lines = $section["user_benchmark_lines"];
                    unset($section["user_benchmark_lines"]);

                    $section["user_benchmark_id"] = $userBenchmark->id;
                    $createdUserBenchmarkSection = UserBenchmarkSection::create($section);

                    foreach ($lines as $line) {
                        $line['user_benchmark_section_id'] = $createdUserBenchmarkSection->id;
                        UserBenchmarkLine::create($line);
                    }
                }
            }
        }
        catch(\Exception $e) {
            DB::rollBack();
            throw $e;
        }
        DB::commit();
        return UserBenchmark::find($userBenchmark->id);
    }

    public static function update(array $data, $id) {
        return UserBenchmark::where("id",$id)->update($data);
    }

    public static function delete($id){
        return UserBenchmark::destroy($id);
    }

    public static function find($id){
        return UserBenchmark::findOrFail($id);
    }

    public static function user($id) {
        return UserBenchmark::findOrFail($id)->user;
    }

    public static function box($id) {
        return UserBenchmark::findOrFail($id)->box;
    }

    public static function trainingSession($id) {
        return UserBenchmark::findOrFail($id)->trainingSession;
    }

    public static function trainingWorkout($id) {
        return UserBenchmark::findOrFail($id)->trainingWorkout;
    }
}
