<?php


namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\Homeparty;
use App\Models\HomepartyUser;
use App\Models\HomepartyUserOrderItem;
use App\Models\Product;
use App\Models\ShippingCountry;
use App\Models\ShoppingInstance;
use App\Models\ShoppingOrder;
use App\Models\ShoppingUser;
use App\Models\UserHistory;
use App\Models\UserShop;
use App\Services\HomepartyCart;
use App\Services\Payment;
use App\Services\Util;
use App\User;
use Auth;
use Request;
use Validator;
use Yard;


class HomepartyController extends Controller
{

    public function __construct()
    {
        $this->middleware('superadmin');

        $this->middleware('active.account');
    }

    public function index()
    {
        $data = [
            'homepartys' => Homeparty::where('auth_user_id', '=', \Auth::user()->id)->get(),
        ];
        return view('user.homeparty.index', $data);
    }

    public function detail($id)
    {
        if($id === 'new'){
            $homeparty = new Homeparty();
        }else{
            $homeparty = $this->getHomparty($id);
        }
        if($homeparty->homeparty_host){
            $homeparty_user = $homeparty->homeparty_host;
        }else{
            $homeparty_user = new HomepartyUser();
            $homeparty_user->is_host = true;
        }

        if($homeparty->completed){
            abort(404);
        }

        $data = [
             'homeparty' => $homeparty,
             'homeparty_user' => $homeparty_user,

        ];
        return view('user.homeparty.detail', $data);
    }

    public function store($id = null)
    {
        $data = Request::all();
        if($data['action'] === 'homeparty-party-store'){
            $rules = array(
                'date' => 'required',
                'name' => 'required',
                'place' => 'required'
            );
        }
        if($data['action'] === 'homeparty-user-store'){
            $rules = array(
                'billing_salutation' => 'required',
                'billing_firstname' => 'required',
                'billing_lastname' => 'required',
                'billing_address' => 'required',
                'billing_zipcode' => 'required',
                'billing_city' => 'required',
                'billing_country_id' => 'required',
            );
            if (!Request::get('same_as_billing')) {
                $rules = array_merge($rules, [
                    'shipping_firstname' => 'required',
                    'shipping_lastname' => 'required',
                    'shipping_address' => 'required',
                    'shipping_zipcode' => 'required',
                    'shipping_city' => 'required',
                    'shipping_salutation' => 'required',
                    'shipping_country_id' => 'required'
                ]);
            }
        }

        $validator = Validator::make(Request::all(), $rules);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(Request::all());
        }

        if($data['action'] === 'homeparty-party-store'){
            if(!$id){
                //first save create and empty user/host
                do {
                    $token = Util::uuidToken();
                } while( Homeparty::where('token', $token)->count() );
                $data['token'] = $token;
                $data['auth_user_id'] = \Auth::user()->id;
                $homeparty = Homeparty::create($data);

                $homeparty_user = HomepartyUser::create([
                    'homeparty_id' => $homeparty->id,
                    'auth_user_id' => \Auth::user()->id,
                    'is_host' => true,
                ]);
            }else {
                $homeparty = $this->getHomparty($id);
                $homeparty->fill($data)->save();
            }
        }

        if($data['action'] === 'homeparty-user-store'){
            $homeparty = $this->getHomparty($id);
            $data['same_as_billing'] = isset($data['same_as_billing']) ? true : false;
            $data['shipping_country_id'] = isset($data['shipping_country_id']) ? $data['shipping_country_id'] : $data['billing_country_id'];
            $homeparty_user = $homeparty->homeparty_host;
            $homeparty_user->fill($data)->save();
        }

        \Session()->flash('alert-save', '1');
        return redirect(route('user_homeparty_detail', $homeparty->id));
    }


    public function guests($id = null)
    {
        $homeparty = $this->getHomparty($id);
        $data = [
            'homeparty' => $homeparty,
        ];
        return view('user.homeparty.guests', $data);
    }


    public function guestDetail($id = null, $gid = null)
    {
        $homeparty = $this->getHomparty($id);
        if($gid === 'new'){
            $homeparty_user = new HomepartyUser();
        }else{
            $homeparty_user = HomepartyUser::findOrFail($gid);
            if($homeparty->id !== $homeparty_user->homeparty_id){
                abort(404);
            }
        }
        if($homeparty->completed){
            abort(404);
        }
        $data = [
            'homeparty' => $homeparty,
            'homeparty_user' => $homeparty_user,
        ];
        return view('user.homeparty.guest_detail', $data);
    }

    public function guestStore($id = null, $gid = null)
    {
        $data = Request::all();
        $rules = array(
            'billing_salutation' => 'required',
            'billing_firstname' => 'required',
            'billing_lastname' => 'required',
            'billing_address' => 'required',
            'billing_zipcode' => 'required',
            'billing_city' => 'required',
            'billing_country_id' => 'required',
        );
        if (!Request::get('same_as_billing')) {
            $rules = array_merge($rules, [
                'shipping_firstname' => 'required',
                'shipping_lastname' => 'required',
                'shipping_address' => 'required',
                'shipping_zipcode' => 'required',
                'shipping_city' => 'required',
                'shipping_salutation' => 'required',
                'shipping_country_id' => 'required'
            ]);
        }
        $validator = Validator::make(Request::all(), $rules);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(Request::all());
        }

        $homeparty = $this->getHomparty($id);
        if($gid === null){
            $homeparty_user = HomepartyUser::create([
                'homeparty_id' => $homeparty->id,
                'auth_user_id' => \Auth::user()->id,
                'is_host' => false,
                ]);
        }else{
            $homeparty_user = HomepartyUser::findOrFail($gid);
        }
        if($homeparty->id !== $homeparty_user->homeparty_id){
            abort(404);
        }
        $data['same_as_billing'] = isset($data['same_as_billing']) ? true : false;
        $data['shipping_country_id'] = isset($data['shipping_country_id']) ? $data['shipping_country_id'] : $data['billing_country_id'];
        $homeparty_user->fill($data)->save();
        \Session()->flash('alert-save', '1');
        return redirect(route('user_homeparty_guests', [$homeparty->id]));
    }


    public function order($id = null)
    {
        $user = User::find(Auth::user()->id);

        $homeparty = $this->getHomparty($id);
        HomepartyCart::calculateHomeparty($homeparty);
        $userHistoryPaymentOrder = UserHistory::whereUserId($user->id)->whereAction('payment_homeparty')->where('referenz', $homeparty->id)->get()->last();
        $data = [
            'homeparty' => $homeparty,
            'userHistoryPaymentOrder' => $userHistoryPaymentOrder,
        ];
        return view('user.homeparty.order', $data);
    }
    //perform Request
    public function orderStore($id = null)
    {

        $homeparty = $this->getHomparty($id);



        if(Request::ajax()) {
            $data = Request::all();

            if($data['action'] === 'addProduct') {
                if($data['homeparty_id'] == $homeparty->id){
                    $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                    if($homeparty_user->homeparty_id !== $homeparty->id){
                        abort(404);
                    }
                    if($product = Product::find($data['product_id'])){
                        $margin = 0;
                        if(\Auth::user() && \Auth::user()->user_level){
                            $margin = \Auth::user()->user_level->margin;
                        }
                        $HomepartyUserOrderItem = HomepartyUserOrderItem::where('homeparty_user_id', $homeparty_user->id)->where('product_id', $product->id)->first();
                        if($HomepartyUserOrderItem){
                            $HomepartyUserOrderItem->qty = $HomepartyUserOrderItem->qty+1;
                            $HomepartyUserOrderItem->save();
                        }else{
                            $HomepartyUserOrderItem = HomepartyUserOrderItem::create([
                                'homeparty_id' => $homeparty->id,
                                'homeparty_user_id' => $homeparty_user->id,
                                'product_id' => $product->id,
                                'qty' => 1,
                                'price' => $product->price,
                                'price_net' => $product->getPriceWith(true, false),
                                'tax_rate' => $product->tax,
                                'points' => $product->points,
                                'margin' => $margin,
                                'ek-price' => $product->getPriceWith(false, true),
                                'slug' => $product->slug

                            ]);
                        }

                    }

                }
                $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                HomepartyCart::calculateHomeparty($homeparty);
                $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
                $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
                $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
                $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
                return response()->json(['response' =>  true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
            }

            if($data['action'] === 'updateCart') {
                if($data['homeparty_id'] == $homeparty->id){
                    $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                    if($homeparty_user->homeparty_id !== $homeparty->id){
                        abort(404);
                    }
                    if(isset($data['product_id']) && $product = Product::find($data['product_id'])){
                        if(isset($data['order_item_id']) && $HomepartyUserOrderItem = HomepartyUserOrderItem::find($data['order_item_id'])){
                            if(isset($data['qty'])){
                                $qty = (int) $data['qty'];
                                $qty = $qty < 1 ? 1 : $qty;
                                $qty = $qty > 100 ? 100 : $qty;
                                $HomepartyUserOrderItem->qty = $qty;
                                $HomepartyUserOrderItem->save();
                            }
                        }
                    }
                }
                $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                HomepartyCart::calculateHomeparty($homeparty);
                $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
                $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
                $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
                $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
                return response()->json(['response' =>  true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
            }

            if($data['action'] === 'removeFromCart') {
                if($data['homeparty_id'] == $homeparty->id){
                    $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                    if($homeparty_user->homeparty_id !== $homeparty->id){
                        abort(404);
                    }
                    if(isset($data['product_id']) && $product = Product::find($data['product_id'])){
                        if(isset($data['order_item_id']) && $HomepartyUserOrderItem = HomepartyUserOrderItem::find($data['order_item_id'])){
                            $HomepartyUserOrderItem->delete();
                        }
                    }
                }
                $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                HomepartyCart::calculateHomeparty($homeparty);
                $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
                $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
                $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
                $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
                return response()->json(['response' =>  true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
            }

            if($data['action'] === 'updateDeliveryOption') {
                if($data['homeparty_id'] == $homeparty->id){
                    $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                    if($homeparty_user->homeparty_id !== $homeparty->id){
                        abort(404);
                    }
                    if(isset($data['delivery'])){
                        $homeparty_user->delivery = $data['delivery'];
                        $homeparty_user->save();
                    }
                }
                $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
                HomepartyCart::calculateHomeparty($homeparty);
                $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
                $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
                $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
                $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
                return response()->json(['response' =>  true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
            }


            return response()->json(['response' =>  false, 'data'=>$data]);
        }

        HomepartyCart::calculateHomeparty($homeparty);
        if(\App\Services\HomepartyCart::$price === 0){
           \Session()->flash('alert-error', 'Dein Warenkorb ist leer, bitte füge erst Produkte hinzu.');
           return redirect(route('user_homeparty_order', [$homeparty->id]));
        }

        //save the calucalte card!
        $time = time();
        $date = date('d.m.Y H:i:s', $time);
        $user = User::find(Auth::user()->id);
        Yard::instance('shopping')->destroy();
        Yard::instance('shopping')->add($homeparty->id, 'Bestellung Homeparty '.$date, 1, \App\Services\HomepartyCart::$price, ['image' => "", 'slug' => $time, 'weight' => 0]);
        do {
            $identifier = Util::getToken();
        } while( ShoppingInstance::where('identifier', $identifier)->count() );

        HomepartyCart::store($identifier, $date);

        $data = [];
        $data['is_from'] = 'homeparty';
        $data['shop_price_net'] = HomepartyCart::getFormattedPriceNet();
        $data['shop_price_tax'] = HomepartyCart::getFormattedPriceTax();
        $data['homeparty_id'] = $homeparty->id;
        $data['is_for'] = 'hp';

        ShoppingInstance::create([
            'identifier' => $identifier,
            'user_shop_id' => 1, //is first faker shop for nuy intern
            'auth_user_id' => Auth::user()->id,
            'payment' => 5, //Vertriebspartner Membership
            'subdomain' => url('/'),
            'country_id' => Yard::instance('shopping')->getShippingCountryId(),
            'shopping_data' => $data,
            'back' => url()->previous(),

        ]);

        HomepartyCart::store($identifier, $date);
        Yard::instance('shopping')->store($identifier);

        $path = route('checkout.checkout_card', ['identifier'=>$identifier]);
        UserHistory::create(['user_id' => $user->id, 'action'=>'payment_homeparty', 'status'=>1, 'referenz'=>$homeparty->id, 'identifier'=>$identifier]);
        //$path = str_replace('http', 'https', $path);
        return redirect()->secure($path);
    }


    public function delete($do, $id = null, $gid=null)
    {
        $homeparty = $this->getHomparty($id);

        if($do === 'hpu'){
            $homeparty_user = HomepartyUser::findOrFail($gid);
            if($homeparty->id !== $homeparty_user->homeparty_id){
                abort(404);
            }
            $homeparty_user->save();
            $homeparty_user->delete();
            \Session()->flash('alert-success', "Homeparty Gast gelöscht");
            return redirect(route('user_homeparty_guests', [$homeparty->id]));

        }
        if($do === 'hp') {

            foreach ($homeparty->homeparty_users as $homeparty_user){
                if ($homeparty->id !== $homeparty_user->homeparty_id) {
                    abort(404);
                }
                $homeparty_user->save();
                $homeparty_user->delete();
            }
            $homeparty->delete();
            \Session()->flash('alert-success', "Homeparty gelöscht");
            return redirect(route('user_homepartys'));

        }
        abort(404);
    }

    private function getHomparty($id){
        $homeparty = Homeparty::findOrFail($id);
        if($homeparty->auth_user_id !== \Auth::user()->id){
            abort(404);
        }
        return $homeparty;
    }

    public function datatable(){
        $query = Product::select('products.*')->where('active', true)->where(function ($q) {
            $q->where('show_at', '=', 0)
                ->orWhere('show_at', '=', 1);
        });

        return \DataTables::eloquent($query)

            ->addColumn('add_card', function (Product $product) {
                return '<button type="button" class="btn btn-sm btn-md-extra btn-secondary add-product-basket" data-product-id="'.$product->id.'">
                            <strong>&euro; '.$product->getFormattedPriceWith(false, false).'</strong>&nbsp; +<span class="ion ion-md-cart"></span>
                        </button>';
            })
            ->addColumn('picture', function (Product $product) {
                if(count($product->images)){
                    return '<img class="img-fluid img-extra" alt="" src="'.route('product_image', [$product->images->first()->slug]).'">';
                }
                return "";
            })
            ->addColumn('price_net', function (Product $product) {
                return $product->getFormattedPriceWith(true, true). " €";
            })
            ->addColumn('price_gross', function (Product $product) {
                return $product->getFormattedPriceWith(false, true). " €";
            })
            ->addColumn('price_vk_gross', function (Product $product) {
                return $product->getFormattedPriceWith(false, false). " €";
            })
            ->addColumn('action', function (Product $product) {
                return '<button class="btn btn-default btn-sm icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg" 
                        data-toggle="modal" data-target="#modals-load-content" data-id="'.$product->id.'" data-route="'.route('modal_load').'"
                        data-action="user-order-show-product" data-view="customer"><i class="ion ion-md-eye"></i></button>';
            })
            ->filterColumn('product', function($query, $keyword) {
                if($keyword != ""){
                    $query->where('name', 'LIKE', '%'.$keyword.'%');
                }
            })
            ->orderColumn('name', 'name $1')
            ->orderColumn('product', 'name $1')
            ->orderColumn('number', 'number $1')
            ->orderColumn('points', 'points $1')
            ->orderColumn('price_net', 'price_net $1')
            ->orderColumn('price_gross', 'price_gross $1')
            ->orderColumn('price_vk_gross', 'price $1')
            ->orderColumn('contents_total', 'contents_total $1')
            ->orderColumn('weight', 'weight $1')

            ->rawColumns(['add_card', 'product', 'quantity', 'picture', 'action'])
            ->make(true);
    }

}