<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

/**
 * Class PromotionUser
 *
 * @property int $id
 * @property int $promotion_admin_id
 * @property string $name
 * @property string|null $description
 * @property string|null $url
 * @property bool $pick_up
 * @property float|null $used_budget_total
 * @property int|null $sell_items_total
 * @property bool $active
 * @property Carbon|null $user_deleted_at
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property PromotionAdmin $promotion_admin
 * @property Collection|Product[] $products
 * @package App\Models
 * @property-read int|null $products_count
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser query()
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereActive($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereDescription($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser wherePickUp($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser wherePromotionAdminId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereSellItemsTotal($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereUrl($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereUsedBudgetTotal($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereUserDeletedAt($value)
 * @property int $user_id
 * @property string|null $user_address
 * @property-read Collection|\App\Models\PromotionUserProduct[] $promotion_user_products
 * @property-read int|null $promotion_user_products_count
 * @property-read Collection|\App\Models\PromotionUserProduct[] $promotion_user_products_active
 * @property-read int|null $promotion_user_products_active_count
 * @property-read \App\User $user
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereUserAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereUserId($value)
 * @property string|null $about_you
 * @property string|null $internal_name
 * @property string|null $internal_description
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereAboutYou($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereInternalDescription($value)
 * @method static \Illuminate\Database\Eloquent\Builder|PromotionUser whereInternalName($value)
 * @property-read Collection<int, \App\Models\PromotionUserOrder> $promotion_user_orders
 * @property-read int|null $promotion_user_orders_count
 * @mixin \Eloquent
 */
class PromotionUser extends Model
{
	protected $table = 'promotion_users';

	protected $casts = [
		'promotion_admin_id' => 'int',
		'user_id' => 'int',
		'pick_up' => 'bool',
		'used_budget_total' => 'float',
		'sell_items_total' => 'int',
		'active' => 'bool',
	];

	protected $dates = [
		'user_deleted_at'
	];

	protected $fillable = [
		'promotion_admin_id',
		'user_id',
		'name',
		'description',
		'about_you',
		'internal_name',
		'internal_description',
		'url',
		'pick_up',
		'user_address',
		'used_budget_total',
		'sell_items_total',
		'active',
		'user_deleted_at'
	];

	public function promotion_admin()
	{
		return $this->belongsTo(PromotionAdmin::class);
	}

	public function user()
	{
		return $this->belongsTo(\App\User::class);
	}

	public function products()
	{
		return $this->belongsToMany(Product::class, 'promotion_user_products')
					->withPivot('id', 'promotion_admin_id', 'promotion_admin_product_id', 'open_items', 'sell_items', 'used_budget_total', 'active')
					->withTimestamps();
	}

	public function promotion_user_products()
	{
		return $this->hasMany(PromotionUserProduct::class);
	}
	public function promotion_user_products_active()
	{
		return $this->hasMany(PromotionUserProduct::class)->where('active', 1);
	}

	public function promotion_user_orders()
	{
		return $this->hasMany(PromotionUserOrder::class);
	}

	public function getPromotionUserOrders($shopping_order_id)
	{
		return PromotionUserOrder::where('promotion_user_id', $this->id)->where('shopping_order_id', $shopping_order_id)->get();
	}


	public function getUrlPreview()
	{
		return $this->url ? config('app.promo_url')."/".$this->url : "";
	}

	public function canDelete(){
			return true;
	}

	public function hasPromotionUserProducts($promotion_admin_product_id)
	{
		return $this->hasMany(PromotionUserProduct::class)->where('promotion_admin_product_id', $promotion_admin_product_id)->first();
	}
	public function calculateSell(){
		$price = 0;
        $price_net = 0;
		//used_budget_total
		//von den user produkte, inkl. der nicht aktiven!
		//ToDo der Preis vom verkauf muss eingesetzt werden, wird gespeichert beim Sale
		if($this->promotion_user_products){
			foreach($this->promotion_user_products as $promotion_user_product){
				$qty = $promotion_user_product->sell_items;
				$price += $promotion_user_product->promotion_admin_product->getPriceWith(false) * intval($qty);
				$price_net += $promotion_user_product->promotion_admin_product->getPriceWith(true) * intval($qty);
					
			}
		}
		return ['price' => $price, 'price_net' => $price_net];
	}

	public function calculateCart(){
		$price = 0;
        $price_net = 0;
		if(isset($this->promotion_admin->promotion_admin_products_active)){
			foreach($this->promotion_admin->promotion_admin_products_active as $promotion_admin_product){
				if($promotion_user_product = $this->hasPromotionUserProducts($promotion_admin_product->id)){
					if($promotion_user_product->active){
						$qty = $promotion_user_product->open_items;
						$price += $promotion_admin_product->getPriceWith(false) * intval($qty);
						$price_net += $promotion_admin_product->getPriceWith(true) * intval($qty);
					}
				}
			}
		}
		return ['price' => $price, 'price_net' => $price_net];
	}

	public function getCountOpenItems(){
		//hier die aktiven
		return $this->promotion_user_products_active->sum('open_items');
	}

	public function getCountSellItems(){
		//hier alle zusammenziehen
		return $this->promotion_user_products->sum('sell_items');
	}

	public function checkPaymentCredit()
	{
		if($this->promotion_user_products_active->count() > 0 && $this->getCountOpenItems() > 0){
			$prices = $this->calculateCart();
			if(isset($prices['price']) && $prices['price'] == 0){
				return "okay";
			}
			$payment_credit = $this->user->payment_credit;
			if($payment_credit <= 0){
				return "empty";
			}
	
			if(isset($prices['price']) && $prices['price'] > 0){
				if($payment_credit >= $prices['price']){
					return "okay";
				}
			}
			return 'not';
		}
		return false;
	}

	public function checkOutOfStock(){
		if(!$this->active){
			return true;
		}
		if($this->getCountOpenItems() < 1){
			return true;
		}
		if($this->checkPaymentCredit() !== 'okay'){
			return true;
		}

		return false;
	}

	public static function preCheckPaymentCredit($values, $user){
		if($values['count_items'] > 0 && $values['sum_items'] > 0){
			if(isset($values['price']) && $values['price'] == 0){
				return "okay";
			}
			$payment_credit = $user->payment_credit;
			if($payment_credit <= 0){
				return "empty";
			}
			if(isset($values['price']) && $values['price'] > 0){
				if($payment_credit >= $values['price']){
					return "okay";
				}
			}
			return 'not';
		}
		return false;
	}
	
	public static function preCalculateCart($value, $by = ''){
        $price = 0;
        $price_net = 0;
		$count_items = 0;
		$sum_items = 0;
        if($by === 'products'){
            foreach($value as $product){
                if(isset($product['product_id']) && isset($product['qty'])){
                    if($promotion_admin_product = PromotionAdminProduct::find($product['product_id'])){
						$count_items ++;
						$sum_items += intval($product['qty']);
                        $price += $promotion_admin_product->getPriceWith(false) * intval($product['qty']);
                        $price_net += $promotion_admin_product->getPriceWith(true) * intval($product['qty']);
                    }
                }
            }
        }
        if($by === 'user_promotion'){
           return $value->calculateCart();
        }
		return ['price' => $price, 'price_net' => $price_net, 'count_items' => $count_items, 'sum_items' => $sum_items];

    }
}
