<?php

namespace App;

use App\Repositories\BoxRepository;
use App\Repositories\PricingRepository;
use App\Repositories\UserRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class Box extends Model
{
    protected $table = 'boxes';

    protected $primaryKey = 'id';

    protected $fillable = [
        "company_id", "name", "address", "country", "county", "postal_code", "phone", "email", "city"
    ];

    protected $appends = [
        "unjoin_session_before_minutes",
        "join_session_before_days",
        "user_subscription_expires_after_days",
        "workouts_visible_before_session",
        "tax_prcnt_box_order",
        "generate_box_orders_before_renew",
        "usage"
    ];

    /**
     * EVENTS
     */
    public static function boot() {
        parent::boot();

        static::created(function(Box $b) { //Quan es crei una nova instancia de box, assigna els box settings auto
            foreach (BoxSettings::all() as $box_settings){
                $b->box_settings()->attach($box_settings["id"],["value" => $box_settings["default_value"]]);
            }
        });
    }

    /**
     * ATRIBUTS FICTICIS
     */
    public function getUsageAttribute() {

        $n_admins = 0;
        $n_athletes = 0;
        $n_boxes = 0;
        $n_coaches = 0;

        $pricing_ids = DB::table('pricing_box')
            ->select('pricing_id')
            ->where('box_id',$this->id)
            ->get();

        foreach ($pricing_ids as $pid) {
            $p = PricingRepository::find($pid->pricing_id);

            foreach ($p->user_subscriptions as $us) {
                if ($us->active) {
                    switch ($us->role_id) {
                        case 2:
                            $n_admins += 1;
                            break;
                        case 3:
                            $n_admins += 1;
                            break;
                        case 4:
                            $n_coaches += 1;
                            break;
                        case 5:
                            $n_athletes += 1;
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        return [
            "n_admins" => $n_admins,
            "n_athletes" => $n_athletes,
            "n_boxes" => $n_boxes,
            "n_coaches" => $n_coaches,
        ];
    }

    public function getUnjoinSessionBeforeMinutesAttribute() {
        return DB::table("box_box_settings")->where([
            ["box_setting_id", 1],
            ["box_id", $this->id]
        ])->first()->value;
    }

    public function getJoinSessionBeforeDaysAttribute() {
        return DB::table("box_box_settings")->where([
            ["box_setting_id", 2],
            ["box_id", $this->id]
        ])->first()->value;
    }

    public function getUserSubscriptionExpiresAfterDaysAttribute() {
        return DB::table("box_box_settings")->where([
            ["box_setting_id", 3],
            ["box_id", $this->id]
        ])->first()->value;
    }

    public function getWorkoutsVisibleBeforeSessionAttribute() {
        return DB::table("box_box_settings")->where([
            ["box_setting_id", 4],
            ["box_id", $this->id]
        ])->first()->value;
    }

    public function getTaxPrcntBoxOrderAttribute() {
        return DB::table("box_box_settings")->where([
            ["box_setting_id", 5],
            ["box_id", $this->id]
        ])->first()->value;
    }

    public function getGenerateBoxOrdersBeforeRenewAttribute() {
        return DB::table("box_box_settings")->where([
            ["box_setting_id", 6],
            ["box_id", $this->id]
        ])->first()->value;
    }

    /**
     * RELATIONSHIPS
     */
    public function company() {
        return $this->belongsTo("App\Company", "company_id");
    }

    public function box_settings(){
        return $this->belongsToMany("App\BoxSettings",'box_box_settings','box_id','box_setting_id')->withPivot("value")->withTimestamps();
    }

    public function trainingRooms() {
        return $this->hasMany("App\TrainingRoom", "box_id", "id");
    }

    public function trainingSessions() {
        return $this->hasMany("App\TrainingSession", "box_id", "id");
    }

    public function calendarTemplates() {
        return $this->hasMany("App\CalendarTemplate", "box_id", "id");
    }

    //pricing
    public function pricing(){
        return $this->belongsToMany('App\Pricing','pricing_box');
    }

    //box orders
    public function boxOrders(){
        return $this->hasMany(BoxOrder::class,'box_id')->orderByDesc("id");
    }

    //box workouts
    public function trainingWorkouts(){
        return $this->hasMany("App\TrainingWorkout","box_id");
    }

    //box products
    public function boxProducts(){
        return $this->hasMany("App\BoxProduct", "box_id");
    }

    //sessions
    public function sessions(){
        return $this->hasMany("App\TrainingSession","box_id");
    }

    public function news() {
        return $this->hasMany("App\News");
    }

    public function userSubscriptions() {
        $user_subscriptions = [];
        foreach($this->pricing as $p) {
            foreach($p->user_subscriptions as $s) {
                $s->user = UserRepository::find($s->user_id);
                array_push($user_subscriptions, $s);
            }
        }
        return $user_subscriptions;
    }

    public function activeUserSubscriptions() {
        $user_subscriptions = [];
        foreach($this->pricing as $p) {
            foreach($p->user_subscriptions as $s) {
                if ($s->active) array_push($user_subscriptions, $s);
            }
        }
        return $user_subscriptions;
    }

    public function user_benchmarks() {
        return $this->hasManyThrough("App\UserBenchmark", "App\TrainingSession");
    }

    public function boxProductVariants() {
        return $this->hasManyThrough("App\BoxProductVariant", "App\BoxProduct");
    }

    public function boxProductImages() {
        $res = [];
        foreach($this->boxProductVariants as $pv) {
            foreach($pv->boxProductImages as $bpi) {
                $res[] = $bpi;
            }
        }
        return $res;
    }

}
