<?php
namespace App\Services;


use App\Models\Country;
use App\Models\ShippingCountry;
use App\Models\ShoppingUser;
use Gloudemans\Shoppingcart\CartItem;

class Shop
{
    public static function userOrders() {
        $shopping_users = ShoppingUser::whereHas('shopping_order', function($q) {
            $q->where('txaction', 'paid')->OrWhere('txaction', 'appointed')->OrWhere('txaction', 'extern')->OrWhere('txaction', 'invoice_open')->OrWhere('txaction', 'invoice_paid');
        })->where('orders', '=', NULL)->get();
        foreach ($shopping_users as $shopping_user) {
            if ($shopping_user->number) {
                $orders = ShoppingUser::where('number', '=', $shopping_user->number)->max('orders');
                $orders = $orders + 1;
            } else {
                $orders = ShoppingUser::where('billing_email', '=', $shopping_user->billing_email)->max('orders');
                $orders = $orders + 1;
            }
            $shopping_user->orders = $orders;
            $shopping_user->save();
        }
    }

    public static function newUserOrder($number){
        if($number > 0){
            $shopping_users = ShoppingUser::where('number', '=', $number)->get();
            $orders = 1;
            foreach ($shopping_users as $shopping_user) {
                if($shopping_user->shopping_order && ($shopping_user->shopping_order->txaction === 'paid' || $shopping_user->shopping_order->txaction === 'appointed' || $shopping_user->shopping_order->txaction === 'extern')){
                    $shopping_user->orders = $orders++;

                }else{
                    $shopping_user->orders = NULL;
                }
                $shopping_user->save();

            }
        }
    }


    public static function getShippingCountryCountryId($shipping_country_id){
        $shippingCountry = ShippingCountry::find($shipping_country_id);
        if($shippingCountry && $shippingCountry->country){
            return $shippingCountry->country->id;
        }
        return 1; //default DE
    }

    public static function getCountryShippingCountryId($country_id){
        $shippingCountry = ShippingCountry::whereCountryId($country_id)->first();
        if($shippingCountry){
            return $shippingCountry->id;
        }
        if($ShippingCountry = ShippingCountry::all()->first()){
            $ShippingCountry->id;
        }
        return 1;
    }

}