<?php

namespace App\Http\Controllers\Master\Payment;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Master\Sellers;
use App\Models\Master\SellerHistory;
use App\Models\Master\Useractionlog;
use App\Models\Master\Billingdetails;
use App\Models\Master\Billingdetailsint;
use App\Models\Master\Plans;
use App\Models\Master\SellerPlan;
use App\Models\Master\PaymentHistory;
use App\Models\Amazon\Azsellers;
use App\Models\Amazon\Useractionlog as UseractionlogAmazon;
use Cartalyst\Stripe\Laravel\Facades\Stripe;
use Stripe\Error\Card;
use App\Helpers\Helper;
use Illuminate\Http\Request;
use View;
use Auth;
use Log;

class PaymentController extends Controller
{
	public function postSubscriptions(Request $request){

		$seller_idd = Helper::encryptor('decrypt',$request->get('seller_id'));
        $input = $request->all();
        $checkstrip = $this->fetchStripeCredential($seller_idd); 
        $stripe = Stripe::make($checkstrip);

        try{
	        $sellers = Sellers::where('id',Helper::encryptor('decrypt',$request->get('seller_id')))->first();
	        
	        if($sellers->marketplace_name == 'tlaz')
                $UseractionlogObj = new UseractionlogAmazon();
            else
            	$UseractionlogObj = new Useractionlog();

            $UseractionlogObj->user_id = Auth::user()->id;
            $UseractionlogObj->seller_id = Helper::encryptor('decrypt',$request->get('seller_id'));
            $UseractionlogObj->action = 'Seller Plan Subscribe - '.$sellers->seller_name;
            $UseractionlogObj->save();

	        if($request->get('address1') != ''){                    
		        $obj = new Billingdetails;
		        $obj->name = $request->get('fullname');
		        $obj->companyname = $request->get('companyname');
		        $obj->address_line1 = $request->get('address1');
		        $obj->address_line2 = $request->get('address2');
		        $obj->city = $request->get('city');
		        $obj->state = ($request->get('state') != '') ?  $request->get('state') : $request->get('state1');
		        $obj->country = $request->get('country');
		        $obj->pincode = $request->get('pincode');
		        $obj->save();

		        $objint = new Billingdetailsint;
		        $objint->user_id = Auth::user()->id;
		        $objint->seller_id = Helper::encryptor('decrypt',$request->get('seller_id'));
		        $objint->billing_address_id = $obj->id;
		        $objint->save();
		    }else{
		        $objint = Billingdetailsint::where('user_id',Auth::user()->id)->where('seller_id',Helper::encryptor('decrypt',$request->get('seller_id')))->where('billing_address_id',$request->get('billing_address_id'))->first();
		        if(empty($objint)){
		            $objint = new Billingdetailsint;
		        }
		        $objint->user_id = Auth::user()->id;
		        $objint->seller_id = Helper::encryptor('decrypt',$request->get('seller_id'));
		        $objint->billing_address_id = $request->get('billing_address_id');
		        $objint->save();                    
		    }

		    $change_plans = $request->get('change_plans');
		    $plan_id = $request->get('plan_id');
	        $plan_id_primary = $request->get('plan_id_primary');

	        $plans = Plans::where('id',$plan_id_primary)->first();

	        $subscriptions = $updatedSubscriptions = array();
	        $checksubtryal = SellerPlan::CheckTrial($seller_idd,$plan_id_primary);

	        if($change_plans == 1){
	        	$checkCurrentPlan = SellerPlan::where('seller_id', $seller_idd)->orderby('created_at','desc')->first();
                if($checkCurrentPlan->gateway == 'stripe' && $checkCurrentPlan->plan_price > 0){
                    $checkstrip = $this->fetchStripeCredential($seller_idd);
                    $stripe = Stripe::make($checkstrip);
                    try {
                        $stripe_customer_id = $checkCurrentPlan->stripe_customer_id;
                        if($stripe_customer_id != '' && $checkCurrentPlan->subscriptions_id != '' && $checkCurrentPlan->plan_type!="PAYG"){
                            $subscription = $stripe->subscriptions()->find($stripe_customer_id,$checkCurrentPlan->subscriptions_id);

                            $subscription_lineitem_id = '';

                            if(isset($subscription['items']['data'])){
                                foreach ($subscription['items']['data'] as $key => $value) {
                                    if(in_array($value['plan']['name'], config('app.planName'))) {
                                        $subscription_lineitem_id = $value['id'];
                                    }
                                }
                            }
                            if($subscription_lineitem_id != ''){
                                $updatedSubscriptions = $stripe->subscriptionItems()->update($subscription_lineitem_id,array('plan'=>$request->get('plan_id')));
                            }
                            
                        }else{  
                            if($sellers->marketplace_name == 'tlaz')   
                            $UseractionlogObj = new UseractionlogAmazon();
                            else
                            $UseractionlogObj = new Useractionlog();      
                            $UseractionlogObj->user_id = Auth::user()->id;
                            $UseractionlogObj->seller_id = $seller_idd;
                            $UseractionlogObj->action = 'Seller Unsubscribe/Uninstall but we are not able to unsubscribe plan from stripe gateway. Need to take action.';
                            $UseractionlogObj->data = 'Need to take action. Seller unsubscribe/uninstall from our panel but his/her plan in stripe gateway does not get cancelled.';
                            $UseractionlogObj->save();
                            Log::info('Seller Unsubscribe/Uninstall but we are not able to unsubscribe plan from stripe gateway. Need to take action.');
                        }
                        $update_subscribe_plan = SellerPlan::DeletePlan($seller_idd);
                    } catch (Exception $e) {
                        Log::info('Error While Unsubscribe Plan.');
                    }
                } else {
                    if($checkCurrentPlan->plan_price == 0){
                        $updateSubscribePlan = SellerPlan::DeletePlan($seller_idd);
                    }
                }

                if(!empty($updatedSubscriptions)){
		        	//inactive prev seller plan and make new entry
	                $updatedSubscriptions['id'] = $updatedSubscriptions['subscription'];
	                $updatedSubscriptions['plan_id_primary'] = $plan_id_primary;
	                $updatedSubscriptions['seller_id'] =$seller_idd;
	                $updatedSubscriptions['plan_id'] =$request->get('plan_id');
	                $updatedSubscriptions['gateway'] ='stripe';
	                if(!isset($updatedSubscriptions['plan_name']))
	                $updatedSubscriptions['plan_name'] = (isset($updatedSubscriptions['plan']['name'])) ? $updatedSubscriptions['plan']['name']: $request->get('plan_name');

	                $billingId = isset($obj->id) ? $obj->id : '';
	                if($billingId != ''){                    
	                    $checkcustomer = $this->getCheckCustomer($seller_idd,$request,$billingId);
	                    Billingdetails::where('id',$billingId)->update(['stripe_customer_id'=>$checkcustomer]);
	                }else{
	                    //get customer id from billing details table                    
	                    $billingDetails = Billingdetails::where('id',$request->get('billing_address_id'))->first();
		                 if(!empty($billingDetails))
	                    $checkcustomer = $billingDetails->stripe_customer_id;
	    			    elseif($stripe_customer_id != '')
	    			    $checkcustomer = $stripe_customer_id;
	                }

	                //SellerPlan::InactivePrevScriptions($seller_idd);
	                
	                $savesubscriptions = SellerPlan::SavesubScriptions($updatedSubscriptions,$plan_id_primary,$checkcustomer);
	                $updateselerdetails = Sellers::UpdateBillingdate($updatedSubscriptions,$plan_id_primary);

	                /*fetch default card details*/
	                $checkstrip = $this->fetchStripeCredential($seller_idd);            
	                $stripe = Stripe::make($checkstrip);
	                $cardList = $stripe->Customers()->find($checkcustomer);
	                if(!empty($cardList)){
	                    $default_source = $cardList['default_source'];
	                    foreach ($cardList['sources']['data'] as $dkey => $dvalue) {
	                        if($default_source == $dvalue['id']){
	                            SellerPlan::where('id',$savesubscriptions->id)->update(['exp_month'=>$dvalue['exp_month'],'exp_year'=>$dvalue['exp_year'],'card_last_digits'=>$dvalue['last4']]);
	                        }
	                    }
	                }
	                $SellerHistory = new SellerHistory;
	                $SellerHistory->user_id = Auth::user()->id;
	                $SellerHistory->seller_id = $seller_idd;
	                $SellerHistory->module = $sellers->marketplace_name;
	                $SellerHistory->plan_name = (isset($updatedSubscriptions['plan']['name'])) ? $updatedSubscriptions['plan']['name']: (isset($updatedSubscriptions['plan_name']) ? $updatedSubscriptions['plan_name'] : '');
	                $SellerHistory->plan_amount = (isset($updatedSubscriptions['plan']['amount']))?$updatedSubscriptions['plan']['amount']/100:$updatedSubscriptions['amount']/100;
	                $SellerHistory->action = 'updateSubscription';
	                $SellerHistory->save();

	                return redirect()->route('plans',array("seller_id"=>$request->get('seller_id')))->with('success', 'Subscription Updated!!');
		        }
	        } else {
	        	$subscriptions['status'] = '';
	            $subscriptions['plan_id_primary'] = $plan_id_primary;
	            if($request->get('gateway') == 'stripe'){
	                $billingId = isset($obj->id) ? $obj->id : '';
	                if($billingId != ''){
	                    $checkcustomer = $this->getCheckCustomer($seller_idd,$request,$billingId);
	                    Billingdetails::where('id',$billingId)->update(['stripe_customer_id'=>$checkcustomer]);
	                }else{
	                    //get customer id from billing details table                    
	                    $billingDetails = Billingdetails::where('id',$request->get('billing_address_id'))->first();
	                    $checkcustomer = $billingDetails->stripe_customer_id;
	                }
	            	
	                if($plans->plan_type =='PAYG'){

	                    $charge_amt =$request->get('charge_amt');
	                    $orders_limit =$request->get('orders_limit');                  
	                    
	                    $subscriptions = $stripe->charges()->create([
		                    'customer' => $checkcustomer,
		                    'currency' => 'USD',
		                    'amount'   => $charge_amt,
		                    'description' => 'usage change applied',
	                    ]);
	                    $subscriptions['charge_amt'] = $charge_amt;
	                    $subscriptions['orders_limit'] = $orders_limit;

	                    $subscriptions['plan_name']=$plans->name;
	                    $subscriptions['plan_duration']=30;
	                    $subscriptions['max_orders_allowed']=$orders_limit;

	                } else if($checksubtryal == 'current'){
	                  	$subscriptions = $stripe->subscriptions()->create($checkcustomer,[
		                    'card' => $request->stripeToken,
		                    'plan' => $request->get('plan_id')
	                	]);
	               }else{
		                $subscriptions = $stripe->subscriptions()->create($checkcustomer,[
		                    'card' => $request->stripeToken,
		                    'plan' => $request->get('plan_id'),
		                    'trial_end'=>$checksubtryal
		                ]);
	               }
	               $stripe1 = Stripe::make($checkstrip);
	               $paymentintent = $stripe1->PaymentIntents()->create([
	                  'amount' => $plans->price,
	                  'currency' => 'usd',
	                  'payment_method_types' => ['card'],
	                ]);

	               $subscriptions['gateway'] = 'stripe';
	            }

	            if(!empty($subscriptions)){
		        	if($subscriptions['status'] == 'succeeded' || $subscriptions['status'] == 'trialing' || $subscriptions['status'] == 'active')
		            {
		                $subscriptions['seller_id'] =$seller_idd;
		                $subscriptions['plan_id'] =$request->get('plan_id');
			            if(!isset($subscriptions['plan_name']))
		                $subscriptions['plan_name'] = (isset($subscriptions['plan']['name'])) ? $subscriptions['plan']['name']: $request->get('plan_name');

		                $savesubscriptions = SellerPlan::SavesubScriptions($subscriptions,$plan_id_primary,$checkcustomer);
		                $updateselerdetails = Sellers::UpdateBillingdate($subscriptions,$plan_id_primary);

		                $SellerHistory = new SellerHistory;
		                $SellerHistory->user_id = Auth::user()->id;
		                $SellerHistory->seller_id = $seller_idd;
		                $SellerHistory->module = $sellers->marketplace_name;
		                $SellerHistory->plan_name = (isset($subscriptions['plan']['name'])) ? $subscriptions['plan']['name']: (isset($subscriptions['plan_name']) ? $subscriptions['plan_name'] : '');
		                $SellerHistory->plan_amount = (isset($subscriptions['plan']['amount']))?$subscriptions['plan']['amount']/100:$subscriptions['amount']/100;
		                $SellerHistory->action = 'subscribed';
		                $SellerHistory->save();

		                $sellerDetail = Sellers::where('id',$seller_idd)->first();
		                if($sellerDetail->marketplace_name == 'tlaz')
		                    Azsellers::where('id',$seller_idd)->update(['payment_status'=>'Paid']);
		                
		                $subscriptions['SellerPlan_id'] = $savesubscriptions->id;
		                $PaymentHistory = PaymentHistory::SavePaymentHistory($subscriptions,$plan_id_primary);
		                /*fetch default card details*/
		                $checkstrip = $this->fetchStripeCredential($seller_idd);            
		                $stripe = Stripe::make($checkstrip);
		                $cardList = $stripe->Customers()->find($checkcustomer);

		                if(!empty($cardList)){
		                    $default_source = $cardList['default_source'];
		                    foreach ($cardList['sources']['data'] as $dkey => $dvalue) {
		                        if($default_source == $dvalue['id']){
		                            SellerPlan::where('id',$savesubscriptions->id)->update(['exp_month'=>$dvalue['exp_month'],'exp_year'=>$dvalue['exp_year'],'card_last_digits'=>$dvalue['last4']]);
		                        }
		                    }
		                }
		              if($change_plans != 0){
		                if($sellerDetail->marketplace_name == 'tlaz')
		                    return redirect()->route('accountdetails',array("seller_id"=>$request->get('seller_id')))->with('success', 'Thank you for change you plan subscription!');
		              }else{
		                if(strpos($sellers->marketplace_name, 'tl') !== false){
		                    return redirect()->route('tyauth','seller_id='.$request->get('seller_id'))->with('success', 'Thank you for your subscription!');
		                }else{
		                    return redirect()->route('sellers')->with('error', 'If you are facing problem in payment then contact to our support team from contact us page.');
		                }
		              }

		            }
	            } else {
		        	return redirect()->route('plans',array("seller_id"=>$request->get('seller_id')))->with('error', 'Subscription not created!!');
		        }
	        } 

        } catch (\Exception $e) {
                Log::info('Postsubscriptions error: '.$e->getMessage().' - Request: '.print_r($input, true).' - Server Info:'.json_encode($_SERVER).' - line no:'.$e->getLine());
                return redirect()->route('plans',array("seller_id"=>$request->get('seller_id')))->with('error', 'We are facing some issue in processing your request. Please contact our support team if you are facing this again.');
            } catch(\Cartalyst\Stripe\Exception\CardErrorException $e) {
                
                return redirect()->route('plans',array("seller_id"=>$request->get('seller_id')))->with('error', $e->getMessage());
            } catch(\Cartalyst\Stripe\Exception\MissingParameterException $e) {
                
                return redirect()->route('plans',array("seller_id"=>$request->get('seller_id')))->with('error', $e->getMessage());
            }
	}

	/**
        check strip allready created get customer id
    */
	public function getCheckCustomer($seller_id='',$request=null,$seller_billing_id='')
    {
        $user = User::where('id',Auth::user()->id)->first();        
        $customer_id = $this->CreateStripeCustomer($user,$seller_id,$request,$seller_billing_id);    
        return $customer_id;
    }
     /**
        Creat stripe Customer and get customer id
    */
    public function CreateStripeCustomer($user='',$seller_id,$request=null,$seller_billing_id)
    { 
        $checkstrip = $this->fetchStripeCredential($seller_id);
        $Billingdetails = Billingdetails::where('id',$seller_billing_id)->first();  

        $stripe = Stripe::make($checkstrip);
        if($request->plan_type =='PAYG'){
             $create_customer = $stripe->Customers()->create([
                    'email' => $request->get('stripeEmail'),
                    'name' => $Billingdetails->name,
                    //'card'=>$request->stripeToken,
                    'address' => ['line1'=>$Billingdetails->address_line1,'line2'=>$Billingdetails->address_line2,
                    'city'=>$Billingdetails->city,'country'=>$Billingdetails->country,'postal_code'=>$Billingdetails->pincode,'state'=> $Billingdetails->state],                    
                    //'card'=>$request->get('stripeToken')
                ]);
        }else{
             $create_customer = $stripe->Customers()->create([
                    'email' => $request->get('stripeEmail'),
                    'name' => $Billingdetails->name,
                    //'card'=>$request->stripeToken,
                    'address' => ['line1'=>$Billingdetails->address_line1,'line2'=>$Billingdetails->address_line2,
                    'city'=>$Billingdetails->city,'country'=>$Billingdetails->country,'postal_code'=>$Billingdetails->pincode,'state'=> $Billingdetails->state],
                    //'card'=>$request->get('stripeToken')
                ]);
        }        
        return $create_customer['id'];
    }

    public function postFreeSubscriptions(Request $request)
    {
    	$input = $request->all();
    	$seller_id = Helper::encryptor('decrypt',$request->get('seller_id'));
        $change_plans =$request->get('change_plans');
        $plan_id =$request->get('plan_id');
        $plan_id_primary = $request->get('plan_id_primary');
        
        $checkCurrentPlan = SellerPlan::where('seller_id', $seller_id)->where('status', 'Active')->orderby('created_at','desc')->first();
        if(!empty($checkCurrentPlan) && $checkCurrentPlan->gateway == 'stripe' && $checkCurrentPlan->plan_price > 0){
        	$checkstrip = $this->fetchStripeCredential($seller_id);            
        	$stripe = Stripe::make($checkstrip);

        	$subscription = $stripe->subscriptions()->find($checkCurrentPlan->stripe_customer_id,$checkCurrentPlan->subscriptions_id);
	        if(!empty($subscription)){
                $updatedSubscriptions = $stripe->subscriptions()->cancel($checkCurrentPlan->stripe_customer_id,$checkCurrentPlan->subscriptions_id);
                if(!empty($updatedSubscriptions)){
                	$update_subscribe_plan = SellerPlan::DeletePlan($seller_id);
                }
            }
        }
        $subscriptions=array();
        $subscriptions['plan_id_primary'] =$plan_id_primary;
        $subscriptions['change_plans'] =$change_plans;
        $subscriptions['seller_id'] =$seller_id;
        $subscriptions['plan_id'] =$request->get('plan_id');
        $subscriptions['plan_name'] =$request->get('plan_name');
        $subscriptions['plan_duration'] =$request->get('plan_duration');
        $subscriptions['amount'] =0;
        $subscriptions['gateway'] = $request->get('gateway');

        $savesubscriptions = SellerPlan::SavesubScriptions($subscriptions,$plan_id_primary,null);
        Sellers::where('id',$seller_id)->update(['payment_status'=>'Paid']);
                      
        $sellerDetail = Sellers::where('id',$seller_id)->first();
        if($sellerDetail->marketplace_name == 'tlaz'){
            Azsellers::where('id',$seller_id)->update(['payment_status'=>'Paid']);
            $UseractionlogObj = new UseractionlogAmazon();
        }
        
        $subscriptions['SellerPlan_id'] = $savesubscriptions->id;
        $subscriptions['plan']['amount'] =$savesubscriptions->plan_price;
        $subscriptions['plan']['id']=$request->get('plan_id');

        $PaymentHistory = PaymentHistory::SavePaymentHistory($subscriptions,$plan_id_primary);
        
        $SellerHistory = new SellerHistory;
        $SellerHistory->user_id = Auth::user()->id;
        $SellerHistory->seller_id = $seller_id;
        $SellerHistory->module = $sellerDetail->marketplace_name;
        $SellerHistory->plan_name = $request->get('plan_name');
        $SellerHistory->plan_amount = 0;
        $SellerHistory->action = 'subscribed';
        $SellerHistory->save();

        if(strpos($sellerDetail->marketplace_name, 'tl') !== false){            
            return redirect()->route('tyauth','seller_id='.$request->get('seller_id'))->with('success', 'Thank you for your subscription!');
        }else{
            return redirect()->route('sellers')->with('error', 'If you are facing problem in payment then contact to our support team from contact us page.');
        }
    }   
}
