<?php


namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
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\Payment;
use App\Services\Util;
use App\User;
use Auth;
use Request;
use Validator;
use Yard;


class OrderController extends Controller
{

    public function __construct()
    {
        $this->middleware('active.account');
    }

    public function index()
    {

        $data = [
        ];
        return view('user.order.index', $data);
    }

    public function detail($id)
    {
        $user = User::find(\Auth::user()->id);
        $shopping_order = ShoppingOrder::findOrFail($id);
        if($shopping_order->auth_user_id !== $user->id){
            abort(404);
        }
        $shopping_order->getLastShoppingPayment();

        $data = [
             'shopping_order' => $shopping_order,
             'isAdmin' => false,
        ];
        return view('user.order.detail', $data);
    }

    public function ordersDatatable(){

        $user = User::find(\Auth::user()->id);
        $query = ShoppingOrder::with('shopping_user', 'shopping_payments')->select('shopping_orders.*')->where('auth_user_id', '=', $user->id)->where('txaction', '!=', NULL);

        return \DataTables::eloquent($query)
            ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
                return '<a href="' . route('user_order_detail', [$ShoppingOrder->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
            })
            ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->created_at->format("d.m.Y");
            })
            ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getShoppingOrderBadge($ShoppingOrder);
            })
            ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getFormattedTotalShipping()." €";
            })
            ->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
            })
            ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
                return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
            })
            ->addColumn('is_for', function (ShoppingOrder $ShoppingOrder) {
                if($ShoppingOrder->shopping_user->is_for === 'me'){
                    return '<span class="badge badge-pill badge-secondary">Vertriebspartnerbestellung</span>';
                }
                if($ShoppingOrder->shopping_user->is_for === 'ot'){
                    return '<span class="badge badge-pill badge-info">Kundenbestellung</span>';
                }
                if($ShoppingOrder->shopping_user->is_for === 'hp'){
                    return '<span class="badge badge-pill badge-dark">Homepartybestellung</span>';
                }
                return '-';
            })
            ->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getLastShoppingPayment('reference');
            })
            ->orderColumn('id', 'id $1')
            ->orderColumn('txaction', 'txaction $1')
            ->orderColumn('shipped', 'shipped $1')
            ->orderColumn('total_shipping', 'total_shipping $1')
            ->rawColumns(['id', 'txaction', 'is_for', 'shipped'])
            ->make(true);
    }


    public function delivery($for, $id=null)
    {
        $user = User::find(\Auth::user()->id);

        $shopping_user = null;
        $delivery_id = null;
        if($for === 'ot'){
            $shopping_user = $this->checkShoppingUser($id, $user);
            $delivery_id = $shopping_user->id;
            if(!$this->checkShoppingCountry($for, $delivery_id) && !\Session()->has('custom-error')){
                \Session()->flash('custom-error', __('validation.custom.shipping_not_found'));
                return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
            }
        }

        if(Request::get('action') === 'next'){
            Yard::instance('shopping')->destroy();
            if(Request::get('switchers-radio-is-for') === 'ot'){
                $delivery_id = $id;
            }
            return redirect(route('user_order_my_list', [Request::get('switchers-radio-is-for'), $delivery_id]));
        }

        $data = [
            'shopping_user' => $shopping_user,
            'isAdmin' => false,
            'isView' => 'customer',
            'for' => $for,
            'delivery_id' => $delivery_id,
        ];
        return view('user.order.delivery', $data);
    }

    public function list($for, $id=null)
    {
        $user = User::find(\Auth::user()->id);
        $shopping_user = null;
        $delivery_id = null;

        if($for === 'ot'){
            $shopping_user = $this->checkShoppingUser($id, $user);
            $delivery_id = $shopping_user->id;
        }
        $shipping_country_id = $this->checkShoppingCountry($for, $id);
        if(!$shipping_country_id){
            \Session()->flash('custom-error', __('validation.custom.shipping_not_found'));
            return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
        }

        Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id, $for);
        Yard::instance('shopping')->setShoppingUser($user, true);


        $data = [
            'shopping_user' => $shopping_user,
            'user' => $user,
            'isAdmin' => false,
            'isView' => 'customer',
            'for' => $for,
            'delivery_id' => $delivery_id,
            //'comp_products' => $this->getCompProducts($for),
        ];
        return view('user.order.list', $data);
    }

    public function payment($for, $id=null){
        $data = Request::all();
        $user = User::find(Auth::user()->id);
        $rules = array(
            'shipping_salutation' => 'required',
            'shipping_firstname'=>'required',
            'shipping_lastname'=>'required',
            'shipping_address'=>'required',
            'shipping_zipcode'=>'required',
            'shipping_city' => 'required',
            'shipping_state' => 'required',
        );
        $validator = Validator::make(Request::all(), $rules);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(Request::all());
        }

        /* if(Yard::instance('shopping')->getNumComp() > 0){
            if(!isset($data['switchers-comp-product'])){
                $validator->errors()->add('switchers-comp-product', __('Bitte wähle ein Kompensationsprodukt aus'));
            }else{
                if(!is_array($data['switchers-comp-product'])){
                    $validator->errors()->add('switchers-comp-product', __('Bitte wähle ein Kompensationsprodukt aus'));
                }else{
                    if(count($data['switchers-comp-product']) !== Yard::instance('shopping')->getNumComp()){
                        $validator->errors()->add('switchers-comp-product', __('Bitte wähle :count Kompensationsprodukte aus', ['count'=>Yard::instance('shopping')->getNumComp()]));
                    }
                }
            }
            if ($validator->errors()->count()) {
                return back()->withErrors($validator)->withInput(Request::all());
            }
        }
        */
        /*do {
            $identifier = Util::getToken();
        } while( ShoppingInstance::where('identifier', $identifier)->count() );*/
        $identifier = Util::getToken();
        $data['is_from'] = 'user_order';
        $data['is_for'] = $for;
        $data['shopping_user_id'] = $id;
        unset($data['quantity']);
        unset($data['_token']);

        Yard::instance('shopping')->putYardExtra('shopping_data', $data);

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

        ]);
        Yard::instance('shopping')->store($identifier);
        */
        //add to DB
        //$path = route('checkout.checkout_card', ['identifier'=>$identifier]);
        UserHistory::create(['user_id' => $user->id, 'action'=>'user_order_payment', 'status'=>1, 'product_id'=>null, 'identifier'=>$identifier]);
        //$path = str_replace('http', 'https', $path);
        //return redirect()->secure($path);
        return redirect(route('user_checkout', [$identifier]));
    }

    private function checkShoppingCountry($for, $id=null){

        $country_id = null;
        if($for === 'me'){
            $user = User::find(\Auth::user()->id);
            if($user->same_as_billing){
                $country_id = $user->account->country_id;
            }else{
                $country_id = $user->account->shipping_country_id;
            }
        }
        if($for === 'ot' && $id){
            $shopping_user = ShoppingUser::findOrFail($id);
            if($shopping_user->same_as_billing){
                $country_id = $shopping_user->billing_country_id;
            }else{
                $country_id = $shopping_user->shipping_country_id;
            }
        }

        if($country_id){
            if($shipping_country = ShippingCountry::whereCountryId($country_id)->first()){
                return $shipping_country->id;
            }
        }
        return false;
    }

    private function checkShoppingUser($id, $user){
        if($id === null){
            abort(403, 'Error: Keine User ID');
        }
        $shopping_user = ShoppingUser::findOrFail($id);
        if($shopping_user->member_id !== $user->id){
            abort(403, 'Error: Falsche User ID');
        }
        $shopping_user = ShoppingUser::findOrFail($id);
        if($shopping_user->is_like){
            abort(403, 'Error: Kunde in Prüfung');
        }
        return $shopping_user;
    }

    public function datatable(){

        $show_at = 1;

      //  $user = User::find(\Auth::user()->id);
       ;

        if(Request::get('shipping_is_for') === 'me'){
            $query = Product::select('products.*')->where('active', true)->where(function ($q) {
                $q->where('show_at', '=', 1)
                    ->orWhere('show_at', '=', 2)
                    ->orWhere('show_at', '=', 6);

            });

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



            //Kunden und Vertriebspartner
            //->orWhere('show_at', '=', 2); // Nur Vertriebspartner
            //->orderBy('pos', 'DESC')
            //->orderBy('id', 'DESC');

        return \DataTables::eloquent($query)

            ->addColumn('product', function (Product $product) {

                $cartItem = Yard::instance('shopping')->getCartItemByProduct($product->id);
                $qty = isset($cartItem->qty) ? $cartItem->qty : 0;
                $rowId = isset($cartItem->rowId) ? $cartItem->rowId : '';
                return '<strong>'.$product->name.'</strong><br><div class="no-line-break input-group-min-w">
                        <div class="input-group d-inline-flex w-auto">
                            <span class="input-group-prepend">
                              <button type="button" class="btn btn-secondary icon-btn md-btn-extra remove-product-basket" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'">-</button>
                            </span>
                            <input type="text" class="form-control text-center input-extra table-input-event-onchange" name="product_qty_'.$product->id.'" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'" value="'.$qty.'">
                            <span class="input-group-append">
                              <button type="button" class="btn btn-secondary icon-btn md-btn-extra add-product-basket" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'">+</button>
                            </span>
                        </div>
                        </div>';
            })
            /*

            ->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().'</strong>&nbsp; +<span class="ion ion-md-cart"></span>
                        </button>';
            })
            ->addColumn('quantity', function (Product $product) {
                $cartItem = Yard::instance('shopping')->getCartItemByProduct($product->id);
                $qty = isset($cartItem->qty) ? $cartItem->qty : 0;
                $rowId = isset($cartItem->rowId) ? $cartItem->rowId : '';
                return '<div class="no-line-break input-group-min-w">
                        <div class="input-group d-inline-flex w-auto">
                            <span class="input-group-prepend">
                              <button type="button" class="btn btn-secondary icon-btn md-btn-extra remove-product-basket" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'">-</button>
                            </span>
                            <input type="text" class="form-control text-center input-extra table-input-event-onchange" name="product_qty_'.$product->id.'" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'" value="'.$qty.'">
                            <span class="input-group-append">
                              <button type="button" class="btn btn-secondary icon-btn md-btn-extra add-product-basket" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'">+</button>
                            </span>
                        </div>
                        </div>';

            })*/

            ->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('single_commission', function (Product $product) {
                return $product->single_commission ? '<span class="badge badge-warning">Handelspanne: '.$product->getFormattedValueCommission().' %</span>' : '<span class="badge badge-primary">Staffelprovision</span> <button class="btn btn-default btn-xs icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg" 
                        data-toggle="modal" data-target="#modals-load-content" data-id="'.Auth::user()->id.'" data-route="'.route('modal_load').'"
                        data-action="user-order-show-user-level-margin" data-view="customer"><i class="ion ion-md-eye"></i></button>';
            })


            ->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('single_commission', 'single_commission $1')
            ->orderColumn('weight', 'weight $1')

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

    public function performRequest(){

        if(Request::ajax()) {

            $data = Request::all();
            $is_for = isset($data['shipping_is_for']) ? $data['shipping_is_for'] : 'ot';
           // $data['comp_products'] = $this->getCompProducts($is_for);

            if($data['action'] === 'updateCart' && isset($data['product_id'])){
                if($product = Product::find($data['product_id'])){
                    $image = "";
                    if($product->images->count()){
                        $image = $product->images->first()->slug;
                    }

                    //get the card item
                    $cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->getPriceWith(false, true), $product->tax,
                        [
                            'image' => $image,
                            'slug' => $product->slug,
                            'weight' => $product->weight,
                            'single_commission' => $product->single_commission,
                            'amount_commission' => $product->amount_commission,
                            'value_commission' => $product->value_commission,
                            'partner_commission' => $product->partner_commission,
                        ]);
                    Yard::setTax($cartItem->rowId, $product->tax);

                    if(isset($data['qty'])  && $data['qty'] > 0){
                        Yard::instance('shopping')->update($cartItem->rowId, $data['qty']);
                    }else{
                        //if 0 get the item by qty:1 and remove it
                        Yard::instance('shopping')->remove($cartItem->rowId);
                    }
                    //
                    Yard::instance('shopping')->reCalculate();
                    $html_card = view("user.order.yard_view_form", $data)->render();

                    return response()->json(['response' =>  true, 'data'=>$data, 'html_card'=>$html_card, 'html_comp'=>'']);
                }
            }
            if($data['action'] === 'clearCart') {
                Yard::instance('shopping')->destroy();
                return response()->json(['response' =>  true, 'data'=>Yard::instance('shopping')->count(), 'html_card'=>'', 'html_comp'=>'']);
            }

            if($data['action'] === 'updateShippingCountry') {
                if(isset($data['shipping_country_id'])){
                    if($shipping_country = ShippingCountry::find($data['shipping_country_id'])){
                        Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country->id, $is_for);
                        //$this->checkCompProduct(Yard::instance('shopping')->getNumComp());
                    }
                }
                $html_card = view("user.order.yard_view_form", $data)->render();
                //$html_comp = view("user.order.comp_product", $data)->render();
                return response()->json(['response' =>  true, 'data'=>$data, 'html_card'=>$html_card, 'html_comp'=>'']);
            }
            return response()->json(['response' =>  false, 'data'=>$data]);
        }
    }

   /* private function checkCompProduct($count_comp_products){
        foreach (Yard::instance('shopping')->content() as $row) {
            //wenn gleich löschen, da neue Versandkosten
            if($row->options->comp > $count_comp_products) {
                Yard::instance('shopping')->remove($row->rowId);
            }
        }
    }
    private function updateCompProduct($data){
          //clear old
          foreach (Yard::instance('shopping')->content() as $row) {
              //wenn kleiner wurde ein produkt entfernt aufgrund der Anzahl
              //wenn gleich löschen, da neue Versandkosten
              if($row->options->comp === $data['comp_num'] || $row->options->comp > $data['count_comp_products']) {
                  Yard::instance('shopping')->remove($row->rowId);
              }
          }

          if(isset($data['comp_product_id'])) {
                if ($product = Product::find($data['comp_product_id'])) {
                    $image = "";
                    if ($product->images->count()) {
                        $image = $product->images->first()->slug;
                    }
                    $cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, 0,
                        ['image' => $image, 'slug' => $product->slug, 'weight' => 0, 'points' => 0,
                            'comp' => $data['comp_num'], 'product_id' => $product->id]);
                    Yard::setTax($cartItem->rowId, 0);
                }
            }
    }

    */
}