<?php

namespace App\Http\Controllers\Web;

use Yard;
use Request;
use Response;
use Validator;
use App\Services\Util;
use App\Models\Product;
use App\Models\Category;
use App\Services\Payment;
use App\Models\UserHistory;
use App\Models\PaymentMethod;
use App\Models\PromotionUser;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Services\UserCart;
use App\Models\PaymentTransaction;
use App\Http\Controllers\Controller;
use App\Repositories\CheckoutRepository;

class PromotionController extends Controller
{

    public function __construct()
    {

    }

    public function serve($path = null)
    {
        if(!isset($path)){
            $path = 'grueneseele';
            //abort(402);

        }

        if($path === 'impressum'){
            return view('web.legal.impressum');
        }
        if($path === 'datenschutzerklaerung'){
            return view('web.legal.datenschutzerklaerung');
        }
        if($path === 'widerrufsbelehrung'){
            return view('web.legal.widerrufsbelehrung');
        }
        if($path === 'versandarten'){
            return view('web.legal.versandarten');
        }
        //search for promo
        $PromotionUser = PromotionUser::where('url', trim($path))->whereNull('user_deleted_at')->first();
        if(!$PromotionUser){
            abort(402);
        }
        if(!$PromotionUser->promotion_admin->isActive() || $PromotionUser->checkOutOfStock()){
            $data = [
                'promotion_user' => $PromotionUser,
            ];
            return view('web.promotion.outofstock', $data);
        }
        UserCart::initYard('prom', null, $PromotionUser);

        $first_category_id = false;
        if(Request::get('catid')){
            $first_category_id = Request::get('catid');
        }

        //$first_category =  Category::where('active', true)->whereJsonContains('show_on', ['3'])->orderBy('pos', 'DESC')->first();
        //$first_category_id = isset($first_category->id) ? $first_category->id : false;
        $shop_products = $this->getShowProducts($first_category_id);
       
        $data = [
            'promotion_user' => $PromotionUser,
            'shop_products' =>  $shop_products,
            'user_payment_methods' => PaymentMethod::getDefaultAsArray()->toArray(),
            'first_category_id' => $first_category_id,
            'categories_by_show_on' => '3'
        ];
        return view('web.promotion.index', $data);
    }

    public function goto($load, $id, $transactionId=false, $reference=false, $identifier=false){
        $PromotionUser = PromotionUser::findOrFail($id);
        $data = [
            'promotion_user' => $PromotionUser,
        ];

        if($load === 'thanksreminder'){
            return view('web.promotion.thanksreminder', $data);
        }
        if($load === 'notactive'){
            return view('web.promotion.notactive', $data);
        }
        if($load === 'thanksorder'){
            $payt = PaymentTransaction::findOrFail($transactionId);
            if($payt->shopping_payment->reference != $reference){
                abort(404);
            }
            Yard::instance('shopping')->destroy();
            $checkRepo = new CheckoutRepository();
            $checkRepo->destroy();
            if(($payt->status === 'fnc' || $payt->status === 'vor'  || $payt->status === 'pp' || $payt->status === 'non') && $payt->txaction === 'prev'){
                $this->directPaymentStatus($payt, $identifier);
            }
            $data = [
                'promotion_user' => $PromotionUser,
                'order_reference' => $payt->shopping_payment->reference,
                'pay_trans' => $payt,
            ];
            return view('web.promotion.thanksorder', $data);
        }
        
    }
    public function store($id){

        $PromotionUser = PromotionUser::findOrFail($id);
        $data = Request::all();

        if(!isset($data['action'])){
            abort(402);
        }
        if($data['action'] === 'submit-reminder-service'){
            return redirect(route('web_promotion_goto', ['thanksreminder', $PromotionUser->id]));
        }
        if($data['action'] === 'submit-promotion-order'){
                $rules = array(
                    'billing_firstname'=>'required',
                    'billing_lastname'=>'required',
                    'billing_address'=>'required',
                    'billing_zipcode'=>'required',
                    'billing_city' => 'required',
                    'billing_state' => 'required',
                    'billing_email'=>'required|email',
                );

                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'
                    ]);
                }
                $validator = Validator::make(Request::all(), $rules);

                if ($validator->fails()) {
                    return back()->withErrors($validator)->withInput(Request::all());
                }    
                $identifier = Util::getToken();
                $data['is_from'] = 'shopping';
                $data['is_for'] = 'pr';
                unset($data['_token']);
                Yard::instance('shopping')->putYardExtra('shopping_data', $data);

                UserHistory::create(['user_id' => $PromotionUser->user_id, 'action'=>'web_promotion_payment', 'status'=>1, 'product_id'=>null, 'identifier'=>$identifier]);
                $checkRepo = new CheckoutRepository();
                $checkRepo->setPromotion(7, $PromotionUser);
                $checkRepo->init($identifier, $data);
                return $checkRepo->makePayment();
        }
    }

    private function directPaymentStatus(PaymentTransaction $payt, $identifier){

        if(isset($payt->transmitted_data['param'])){
            $shopping_order = ShoppingOrder::find($payt->transmitted_data['param']);
            $shopping_payment = ShoppingPayment::where('reference', $payt->transmitted_data['reference'])->first();

            $shopping_order->txaction = 'open';
            $shopping_order->save();
            $payt->txaction = "open";

            //is Promotion Handel it
            if($shopping_order->promotion_user_id > 0){
                Payment::handelPromotionProduct($shopping_order);
            }
            if($shopping_payment){
                //Payment::handelUserPayCredits($shopping_order, 'deduction');
                if($payt->status === 'vor'){
                    $shopping_payment->txaction = 'open';
                    $shopping_order->txaction = 'open';
                    $payt->txaction = "open";
                    $shopping_order->save();

                }
                if($payt->status === 'pp'){
                    $send_link = Payment::paymentStatusPaidAction($shopping_order, true);
                    $shopping_payment->txaction = 'paid';
                    $shopping_order->txaction = 'paid';
                    $payt->txaction = "paid";
                    $shopping_order->save();
                }    
                if($payt->status === 'fnc'){
                    $send_link = Payment::paymentStatusPaidAction($shopping_order, true);
                    $shopping_payment->txaction = 'paid';
                    $shopping_order->txaction = 'paid';
                    $payt->txaction = "paid";
                    $shopping_order->save();

                }         
                if($payt->status === 'non'){
                    $send_link = Payment::paymentStatusPaidAction($shopping_order, true);
                    $shopping_payment->txaction = 'paid';
                    $shopping_order->txaction = 'paid';
                    $payt->txaction = "paid";
                    $shopping_order->save();
                    \App\Services\Shop::newUserOrder($shopping_order->shopping_user->number);
                }   
                $shopping_payment->save();
            }
            $payt->save();
            $data = [
               'mode' => $payt->transmitted_data['mode'],
                'txaction' => $payt->txaction,
                'send_link' => false,
            ];
            Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
        }
    }
    
    public function load(){
        $data = Request::all();
        $ret = "";
        $status = false;

        if(Request::ajax()){
            if($data['action'] === 'web-show-product'){
                $product = Product::find($data['id']); //current user form order
                $ret = view("web.promotion.show_product", compact('product', 'data'))->render();
            }
            if(isset($data['perform'])){
                if($data['action'] === 'switch-show_products'){
                    $category_id = isset($data['show_products_option']) ? $data['show_products_option'] : false;
                    $shop_products = $this->getShowProducts($category_id);
                    $shop_products_view = view("web.promotion._shop_products_inner", compact('shop_products'))->render();
                    return response()->json(['response' => $data, 'shop_products_view'=>$shop_products_view, 'status'=>$status]);
                }
                if($data['action'] === 'switch-free-product'){
                    \App\Services\UserCart::updateFeeProduct($data);
                }
                if($data['action'] === 'add-shop-product'){
                    $data['qty'] = \App\Services\UserCart::updateProduct($data, true);
                }
                if($data['action'] === 'update-shop-product'){
                    $data['qty'] = \App\Services\UserCart::updateProduct($data);
                }
                if($data['action'] === 'remove-shop-product'){
                    \App\Services\UserCart::updateProduct($data);
                    $data['qty'] = 0;
                }
                if($data['action'] === 'clear-cart'){
                    \App\Services\UserCart::clearCart($data);
                }
                if($data['action'] === 'switch-shipping'){
                    \App\Services\UserCart::switchShipping($data);
                }
                if($data['action'] === 'change-state-shipping'){
                    \App\Services\UserCart::changeStateShipping($data, 'prom');
                }
            
                $cart = view("web.promotion._promotion_cart", compact('data'))->render();
                if(Yard::instance('shopping')->isQuickShipping()){
                    $invoice = view("web.components._invoice_details_quick")->render();
                }else{
                    $invoice = view("web.components._invoice_details")->render();
                }
                $checkout = view("web.components._checkout")->render();
                $data['shipping_price_formated'] = UserCart::getCurrentShippingPrice(2); //shipping_for === 2 promotion , 3 shop

                return response()->json(['response' => $data, 'cart'=>$cart, 'invoice'=>$invoice, 'checkout'=>$checkout, 'status'=>$status, 'basketqty'=>Yard::instance('shopping')->count()]);
            }
            return response()->json(['response' => $data, 'html'=>$ret, 'status'=>$status]);
        }
    }

    private function getShowProducts($category_id = false){
        $shop_products = [];
        if($category_id){
            $shop_products =  Product::where('active', true)->whereJsonContains('show_on', ['3'])
            ->whereHas('categories', function ($query) use ($category_id) {
                $query->where('category_id', $category_id); //->whereJsonContains('show_on', ['3']);
            })->orderBy('pos', 'ASC')->get();
        }else{
            $shop_products =  Product::where('active', true)->whereJsonContains('show_on', ['3'])
            ->orderBy('pos', 'ASC')->get();
        }
        return $shop_products;
    }
}