<?php

namespace App\Repositories;

use App\Models\CommunityPricingPlan;
use Stripe;
use Illuminate\Support\Facades\Cache;

class CommunityPricingPlanRepository
{
    public function __construct(
        CommunityPricingPlan $communityPricingPlan
    ) {
        $this->model = $communityPricingPlan;
    }

    public function savePlan($community_id, $user_id, $pricing_plan, $plan_type = 'monthly')
    {
        $plan = $this->getByCommunityId($community_id);
        if (! $plan) {
            $plan = $this->model->newInstance();
        }
        $plan->community_id = $community_id;
        $plan->user_id = $user_id;
        $plan->plan_id = $pricing_plan;
        $plan->plan_type = $plan_type;
        $plan->registration_date = date('Y-m-d');
        $plan->save();
    }
	
	public function saveFreePlan($community,$community_id, $user_id, $pricing_plan, $plan_type = 'monthly')
    {
        $plan = $this->getByCommunityId($community_id);
        if (! $plan) {
            $plan = $this->model->newInstance();
			$plan->registration_date = date('Y-m-d');
        }
		
		$planStartDtate=date('Y-m-d');
		
		if ($plan_type == 'yearly') {
			$planEndDate = date('Y-m-d', strtotime('+365 days', strtotime($planStartDtate)));
		} else {
			$planEndDate = getRecurringMonthDate($planStartDtate);
		}
		
		$community->pricing_plan = $pricing_plan;
		$community->trial_start_date = '0000-00-00';
		$community->trial_days = 0;
		$community->skip_card_dtls = 0;
		$community->skip_card_till_date = '0000-00-00';
		$community->all_features_activated = 0;
		$community->save();
		
		$plan->plan_start_date = $planStartDtate;
        $plan->plan_end_date = $planEndDate;
        $plan->community_id = $community_id;
        $plan->user_id = $user_id;
        $plan->plan_id = $pricing_plan;
        $plan->plan_type = $plan_type;
        $plan->plan_id = $pricing_plan;
        $plan->plan_type = $plan_type;
		//$plan->stop_payment = 0;
        $plan->save();
		
		return $plan;
    }

    public function getByCommunityId($community_id)
    {
        return $this->model->where('community_id', $community_id)->first();
    }

    public function getByType($user_id, $add_payment_type)
    {
        return $this->model
            ->where('user_id', $user_id)
            ->where('add_payment_type', $add_payment_type)->first();
    }

    public function getAllPayments()
    {
        // return $this->model->where('community_id','=',153)->get();
        return $this->model->where('stop_payment', '=', 0)->get();
    }

    public function makePlanPayment()
    {
        $communityPlans = $this->getAllPayments();

        $this->communityPricingPlanPaymentRepository = app('App\\Repositories\\CommunityPricingPlanPaymentRepository');

        $this->businessProductsOrdersRepository = app('App\\Repositories\\BusinessProductsOrdersRepository');
        $this->businessProductsOrdersRepository->makeSubscriptionPayment(); // product subscription payments

        $todaysDate = date('Y-m-d');

        // require_once app_path('library/stripe-php/init.php');
        $stripe = [
            'secret_key' => config('stripe_secret_key'),
            'publishable_key' => config('stripe_publishable_key'),
        ];

        if (config('stripe_mode') == 'test') {
            $source_token = 'tok_visa';
        } else {
            // $source_token=$stripeToken;
            $source_token = '';
        }

        \Stripe\Stripe::setApiKey($stripe['secret_key']);

        $todaysDate = date('Y-m-d');
        $todayStr = strtotime($todaysDate);

        $freePlanId = app('App\\Repositories\\PricingPlansRepository')->getFreePlanById();

        foreach ($communityPlans as $plan) {

            $planUser = '';
            $community = '';
            $planDetails = '';

            if ($plan->add_payment_type == 'community') {
                $community = app('App\\Repositories\\CommunityRepository')->getById($plan->community_id);
                if ($community) {
                    $planDetails = $community->present()->getPricingPlan($plan->plan_id);
                }
            } elseif ($plan->add_payment_type == 'askidea' || $plan->add_payment_type == 'idmeets' || $plan->add_payment_type == 'personaldomain') {
                $planUser = app('App\\Repositories\\UserRepository')->findById($plan->user_id);
            }

            if (($plan->plan_type == 'monthly' and $plan->plan_end_date <= $todaysDate) || ($plan->plan_type == 'yearly' and $plan->plan_end_date == $todaysDate)) {
                // if($plan->plan_end_date==$todaysDate){
                if ($plan->paid_for_plan == 1 and $plan->add_payment_type == 'community' and $plan->upcoming_plan_id != 0) {
                    $newPlanDetails = $community->present()->getPricingPlan($plan->upcoming_plan_id);

                    if ($newPlanDetails) {
                        $has_paid = $this->payingForPlanByCard($community, $newPlanDetails, $plan->upcoming_plan_type);
                        if ($has_paid and $community) {

                            $community->pricing_plan = $plan->upcoming_plan_id;
                            $community->save();
                            
                            // Clear community cache after downgrading pricing plan
                            Cache::forget('community_by_id_' . $community->id);
                            
                            // Clear community cache after updating pricing plan
                            Cache::forget('community_by_id_' . $community->id);ity->save();
                                        
                                        // Clear community cache after plan update
                                        Cache::forget('community_by_id_' . $community->id);                                // Clear community cache after updating pricing plan
                                Cache::forget('community_by_id_' . $community->id);                            $plan->plan_id = $plan->upcoming_plan_id;
                            $plan->plan_start_date = $plan->upcoming_plan_start_date;
                            $plan->plan_end_date = $plan->upcoming_plan_end_date;
                            $plan->plan_type = $plan->upcoming_plan_type;
                            $plan->payment_id = $plan->upcoming_payment_id;
                            $plan->upcoming_plan_id = 0;
                            $plan->upcoming_plan_start_date = '0000-00-00';
                            $plan->upcoming_plan_end_date = '0000-00-00';
                            $plan->upcoming_plan_type = '';
                            $plan->upcoming_payment_id = 0;
                            $plan->save();
                        }

                        if ($has_paid == '') {
                            $this->addCommunityPendingPayment($community, $plan);
                            /*$community->pricing_plan=$freePlanId;
                            $community->save();
                            $plan->plan_id=1;
                            $plan->save();*/
                        }
                    }
                    // $plan->save();
                } else {

                    if ($plan->paid_for_plan == 0 and $plan->add_payment_type == 'community' and $planDetails) {

                        $trialDays = $planDetails->trial_days;
                        $registrationDate = $plan->registration_date;
                        $trialExpiryDate = date('Y-m-d', strtotime($registrationDate.' + '.$trialDays.'days'));
                        $registrationStr = strtotime($trialExpiryDate);

                        if ($todayStr >= $registrationStr) {
                            $has_paid = $this->payingForPlan($community, $plan, $planDetails);
                            if ($has_paid == '') {
                                $this->addCommunityPendingPayment($community, $plan);
                                /*$community->pricing_plan=$freePlanId;
                                $community->save();
                                $plan->plan_id=1;
                                $plan->save();*/
                            }
                        }
                    } else {

                        $cardDetails = '';
                        if ($plan->add_payment_type == 'community' and $community) {
                            $cardDetails = $community->present()->getCardDetails();
                        } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                            $cardDetails = $planUser->present()->getCardDetails('askidea', 'askidea');
                        } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                            $cardDetails = $planUser->present()->getCardDetails('idmeets', 'idmeets');
                        } elseif ($planUser and $plan->add_payment_type == 'personaldomain') {
                            $cardDetails = $planUser->present()->getCardDetails('personaldomain', 'personaldomain');
                        }

                        $space_charges = config('community-space-monthly-charges-per-mb');
                        $purchased_space_charges = '';

                        $discounted_amount = '';
                        $discount_percentage = '';
                        $new_amount = '';

                        $netPayingAmount = '';
                        if ($cardDetails) {
                            $payingAmount = 0;
                            if ($plan->plan_type == 'yearly') {
                                if ($plan->add_payment_type == 'community' and $community) {
                                    $purchased_space = $community->purchased_space_in_mb;
                                    $payingAmount = $planDetails->price_yearly;
                                    $desc = $planDetails->plan_name;

                                    $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan();
                                    $communityMembers = $community->countMembers();
                                    $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                                    // $column_name="increased_member_limit_plan_".$plan->plan_id;
                                    $column_name = 'increased_member_limit';
                                    $increasedLimit = $community->$column_name;

                                    if ($extraMembers > 0) {
                                        $increasedLimit = $increasedLimit + $extraMembers;
                                    }

                                    if ($increasedLimit and $planDetails->monthly_price_per_extra_user) {
                                        $increasedAmount = $increasedLimit * 12 * $planDetails->monthly_price_per_extra_user;
                                        $payingAmount = $payingAmount + $increasedAmount;
                                    }

                                    if ($purchased_space and $space_charges) {
                                        $purchased_space_charges = $purchased_space * 12 * $space_charges;
                                        $payingAmount = $payingAmount + $purchased_space_charges;
                                    }

                                    $netPayingAmount = round($payingAmount, 2);

                                    $discount_percentage = $community->subscription_discount_percent;
                                    if ($discount_percentage) {
                                        $discounted_amount = ($payingAmount / 100) * $discount_percentage;
                                        $new_amount = $payingAmount - $discounted_amount;
                                        $discounted_amount = $discounted_amount;
                                        $new_amount = round($new_amount, 2);
                                        $payingAmount = $new_amount;
                                    }
                                } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                                    $payingAmount = config('interactive-profile-ideas-yearly-charge');
                                    $desc = 'Ask Idea';
                                } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                                    $payingAmount = config('idmmets-subscription-yearly-charge');
                                    $desc = 'Idmeets Subscription';
                                } elseif ($planUser and $plan->add_payment_type == 'personaldomain') {

                                    $resume = $planUser->present()->isResumeCreated($planUser->id);

                                    $payingAmount = config('personal-custom-domain-yearly-charges');
                                    $desc = 'Personal Domain Subscription';

                                    $netPayingAmount = round($payingAmount, 2);

                                    $discount_percentage = $resume->domain_purchase_discount;
                                    if ($discount_percentage) {
                                        $discounted_amount = ($payingAmount / 100) * $discount_percentage;
                                        $new_amount = $payingAmount - $discounted_amount;
                                        $discounted_amount = $discounted_amount;
                                        $new_amount = round($new_amount, 2);
                                        $payingAmount = $new_amount;
                                    }
                                }
                                $payingAmount = $payingAmount * 100;
                            } else {
                                if ($plan->add_payment_type == 'community' and $community and $planDetails) {
                                    $purchased_space = $community->purchased_space_in_mb;
                                    $payingAmount = $planDetails->price_monthly;
                                    $desc = $planDetails->plan_name;

                                    $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan();
                                    $communityMembers = $community->countMembers();
                                    $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                                    // $column_name="increased_member_limit_plan_".$plan->plan_id;
                                    $column_name = 'increased_member_limit';
                                    $increasedLimit = $community->$column_name;
                                    if ($extraMembers > 0) {
                                        $increasedLimit = $increasedLimit + $extraMembers;
                                    }

                                    if ($increasedLimit and $planDetails->monthly_price_per_extra_user) {
                                        $increasedAmount = $increasedLimit * 1 * $planDetails->monthly_price_per_extra_user;
                                        $payingAmount = $payingAmount + $increasedAmount;
                                    }

                                    if ($purchased_space and $space_charges) {
                                        $purchased_space_charges = $purchased_space * 1 * $space_charges;
                                        $payingAmount = $payingAmount + $purchased_space_charges;
                                    }

                                    $netPayingAmount = round($payingAmount, 2);

                                    $discount_percentage = $community->subscription_discount_percent;
                                    if ($discount_percentage) {
                                        $discounted_amount = ($payingAmount / 100) * $discount_percentage;
                                        $new_amount = $payingAmount - $discounted_amount;
                                        $discounted_amount = $discounted_amount;
                                        $new_amount = round($new_amount, 2);
                                        $payingAmount = $new_amount;
                                    }
                                } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                                    $payingAmount = config('interactive-profile-ideas-monthly-charge');
                                    $desc = 'Ask Idea';
                                } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                                    $payingAmount = config('idmmets-subscription-monthly-charge');
                                    $desc = 'Idmeets Subscription';
                                }
                                $payingAmount = $payingAmount * 100;
                            }

                            if ($payingAmount > 0) {
                                $orderId = rand(111111, 999999);

                                try {
                                    $payDetails = \Stripe\Charge::create([
                                        'customer' => $cardDetails->customer_id,
                                        'amount' => $payingAmount,
                                        'currency' => 'USD',
                                        'description' => $desc,
                                        'metadata' => [
                                            'order_id' => $orderId,
                                        ],
                                    ]);
                                /*} catch (\Stripe\Error\Base $e) {
                                    // echo ($e->getMessage());
                                    continue;
                                } catch (\Stripe\Error\Card $e) {
                                    // echo ($e->getMessage()); // I think this is the missing one
                                    continue;
                                } catch (\Stripe\Error\Authentication $e) {
                                    continue;
                                    // a good one to catch
                                } catch (\Stripe\Error\InvalidRequest $e) {
                                    continue;
                                    // and catch this one just in case
                                } catch (Exception $e) {
                                    continue;
                                    // catch any non-stripe exceptions
                                }*/
								
								} catch (\Stripe\Error\Base $e) {
									\Log::error('Stripe Base Error: ' . $e->getMessage());
									continue;
								} catch (\Stripe\Error\Card $e) {
									\Log::error('Stripe Card Error: ' . $e->getMessage());
									continue;
								} catch (\Stripe\Error\Authentication $e) {
									\Log::error('Stripe Authentication Error: ' . $e->getMessage());
									continue;
								} catch (\Stripe\Error\InvalidRequest $e) {
									\Log::error('Stripe Invalid Request Error: ' . $e->getMessage());
									continue;
								} catch (\Exception $e) {
									\Log::error('General Error: ' . $e->getMessage());
									continue;
								}

                                $paymenyResponse = $payDetails->jsonSerialize();
                                if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                                    $amountPaid = $paymenyResponse['amount'];

                                    $amountPaid = $amountPaid / 100;

                                    $balanceTransaction = $paymenyResponse['balance_transaction'];
                                    $paidCurrency = $paymenyResponse['currency'];
                                    $paymentStatus = $paymenyResponse['status'];
                                    $paymentDate = date('Y-m-d H:i:s');

                                    if ($plan->add_payment_type == 'community' and $community) {
                                        $customerName = $community->user->fullname;
                                        $customerEmail = $community->user->email_address;
                                    } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                                        $customerName = $planUser->fullname;
                                        $customerEmail = $planUser->email_address;
                                    } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                                        $customerName = $planUser->fullname;
                                        $customerEmail = $planUser->email_address;
                                    } elseif ($planUser and $plan->add_payment_type == 'personaldomain') {
                                        $customerName = $planUser->fullname;
                                        $customerEmail = $planUser->email_address;
                                    }

                                    $cardNumber = $cardDetails->card_number;
                                    $cardCVC = '';
                                    $cardExpMonth = $cardDetails->expiry_month;
                                    $cardExpYear = $cardDetails->expiry_year;
                                    $customer_id = $cardDetails->customer_id;

                                    if ($plan->add_payment_type == 'community' and $community) {
                                        $itemName = $planDetails->plan_name;
                                        $itemNumber = $planDetails->plan_id;
                                    } else {
                                        $itemName = $plan->add_payment_type;
                                        $itemNumber = $plan->plan_id;
                                    }

                                    $itemPrice = $amountPaid;
                                    $amountPaidNew = $amountPaid;

                                    $payment_for = 'plan';
                                    $transaction_payment_type = $plan->plan_type;
                                    $plan_id = $plan->plan_id;

                                    if ($paymentStatus == 'succeeded') {
                                        if ($plan->add_payment_type == 'community' and $community) {
                                            $pt = $this->communityPricingPlanPaymentRepository->addPayment($community, $community->user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, $plan_id);

                                            if ($pt and $discounted_amount != '' and $discount_percentage != '') {

                                                $pt->actual_amount = $netPayingAmount;
                                                $pt->discount_percentage = $discount_percentage;
                                                $pt->coupon_code = 'backend_discount_applied';
                                                $pt->coupon_applied = 1;
                                                $pt->save();

                                                $pyinvoice = app('App\\Repositories\\CommunityInvoiceRepository')->getBySubCmId($pt->invoice_id, $community->id);

                                                if ($pyinvoice) {
                                                    $pyinvoice->total_amount = $netPayingAmount;
                                                    $pyinvoice->actual_amount = $new_amount;
                                                    $pyinvoice->discount_percentage = $discount_percentage;
                                                    $pyinvoice->coupon_code = 'backend_discount_applied';
                                                    $pyinvoice->coupon_applied = 1;
                                                    $pyinvoice->save();
                                                }
                                            }
                                        } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                                            $this->communityPricingPlanPaymentRepository->addPayment('', $plan->user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, 0, $plan_id, 'askidea');
                                        } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                                            $this->communityPricingPlanPaymentRepository->addPayment('', $plan->user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, 0, $plan_id, 'idmeets');
                                        } elseif ($planUser and $plan->add_payment_type == 'personaldomain') {
                                            $pt = $this->communityPricingPlanPaymentRepository->addPayment('', $plan->user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, 0, $plan_id, 'personaldomain');

                                            if ($pt and $discounted_amount != '' and $discount_percentage != '') {
                                                $pt->actual_amount = $netPayingAmount;
                                                $pt->discount_percentage = $discount_percentage;
                                                $pt->coupon_code = 'firsttime_discount_applied';
                                                $pt->coupon_applied = 1;
                                                $pt->save();
                                            }

                                            $resume = $planUser->present()->isResumeCreated($planUser->id);
                                            if ($resume) {

                                                $domain_name = $resume->domain_name;

                                                $api_mode = config('personal-custom-domain-api-mode');
                                                $api_user = config('personal-custom-domain-api-user');
                                                $api_key = config('personal-custom-domain-api-key');
                                                $api_username = config('personal-custom-domain-api-username');

                                                // $api_ip=getUserClientIpAddr();
                                                // if(	$api_ip){
                                                $api_ip = config('personal-custom-domain-api-clientip');
                                                // }

                                                if ($api_mode == 'test') {
                                                    $api_url = 'https://api.sandbox.namecheap.com/xml.response';
                                                } else {
                                                    $api_url = 'https://api.namecheap.com/xml.response';
                                                }

                                                $curlUrl = $api_url.'?ApiUser='.$api_user.'&ApiKey='.$api_key.'&UserName='.$api_username.'&ClientIp='.$api_ip.'&Command=namecheap.domains.renew&DomainName='.$domain_name.'&Years=1';

                                                $curlx = curl_init();
                                                curl_setopt($curlx, CURLOPT_URL, $curlUrl);
                                                curl_setopt($curlx, CURLOPT_HEADER, 0);
                                                curl_setopt($curlx, CURLOPT_RETURNTRANSFER, 1);
                                                $resp = curl_exec($curlx);

                                                curl_close($curlx);

                                                $xml = simplexml_load_string($resp, null, LIBXML_NOCDATA);
                                                $json = json_encode($xml);
                                                $array = json_decode($json, true);

                                                // return $array; exit;

                                                // print_r($array);

                                                if (isset($array['CommandResponse']['DomainRenewResult'])) {
                                                    $data = $array['CommandResponse']['DomainRenewResult'];

                                                    if (! empty($data)) {
                                                        foreach ($data as $value) {
                                                            foreach ($value as $key => $val) {
                                                                if ($key == 'Renew' and $val == 'true') {
                                                                    $resume->domain_blocked = 0;
                                                                    $resume->save();
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        if ($plan->add_payment_type == 'community' and $community) {
                                            /*$community->pricing_plan=$freePlanId;
                                            $community->save();
                                            $plan->plan_id=1;
                                            $plan->save();	*/
                                            $this->addCommunityPendingPayment($community, $plan);

                                        } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                                            $plan->plan_id = 0;
                                            $plan->save();
                                            $planUser->ask_idea_plan = 0;
                                            $planUser->save();
                                        } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                                            $plan->plan_id = 0;
                                            $plan->save();
                                            $planUser->idmeet_plan = 0;
                                            $planUser->save();
                                        } elseif ($planUser and $plan->add_payment_type == 'personaldomain') {
                                            $resume = $planUser->present()->isResumeCreated($planUser->id);
                                            if ($resume) {
                                                $resume->domain_blocked = 1;
                                                $resume->save();
                                            }
                                        }
                                    }
                                } else {
                                    if ($plan->add_payment_type == 'community' and $community) {
                                        /*$community->pricing_plan=$freePlanId;
                                        $community->save();
                                        $plan->plan_id=1;
                                        $plan->save();*/
                                        $this->addCommunityPendingPayment($community, $plan);
                                    } elseif ($planUser and $plan->add_payment_type == 'askidea') {
                                        $plan->plan_id = 0;
                                        $plan->save();

                                        $planUser->ask_idea_plan = 0;
                                        $planUser->save();
                                    } elseif ($planUser and $plan->add_payment_type == 'idmeets') {
                                        $plan->plan_id = 0;
                                        $plan->save();

                                        $planUser->idmeet_plan = 0;
                                        $planUser->save();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function payingForPlan($community, $plan, $planDetails)
    {
        if ($planDetails and $planDetails->is_plan_free == 1) {
            return 1;
        }

        $cardDetails = $community->present()->getCardDetails();

        // require_once app_path('library/stripe-php/init.php');
        $stripe = [
            'secret_key' => config('stripe_secret_key'),
            'publishable_key' => config('stripe_publishable_key'),
        ];

        \Stripe\Stripe::setApiKey($stripe['secret_key']);

        $this->communityPricingPlanPaymentRepository = app('App\\Repositories\\CommunityPricingPlanPaymentRepository');

        $transaction_id = '';
        if ($cardDetails) {

            $purchased_space = $community->purchased_space_in_mb;
            $space_charges = config('community-space-monthly-charges-per-mb');
            $purchased_space_charges = '';

            if ($plan->plan_type == 'yearly') {
                $payingAmount = $planDetails->price_yearly;
                $desc = $planDetails->plan_name;

                $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan();
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                // $column_name="increased_member_limit_plan_".$plan->plan_id;
                $column_name = 'increased_member_limit';
                $increasedLimit = $community->$column_name;

                if ($extraMembers > 0) {
                    $increasedLimit = $increasedLimit + $extraMembers;
                }

                if ($increasedLimit and $planDetails->monthly_price_per_extra_user) {
                    $increasedAmount = $increasedLimit * 12 * $planDetails->monthly_price_per_extra_user;
                    $payingAmount = $payingAmount + $increasedAmount;
                }

                if ($purchased_space and $space_charges) {
                    $purchased_space_charges = $purchased_space * 12 * $space_charges;
                    $payingAmount = $payingAmount + $purchased_space_charges;
                }

                $payingAmount = $payingAmount * 100;
            } else {
                $payingAmount = $planDetails->price_monthly;
                $desc = $planDetails->plan_name;

                $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan();
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                // $column_name="increased_member_limit_plan_".$plan->plan_id;
                $column_name = 'increased_member_limit';
                $increasedLimit = $community->$column_name;
                if ($extraMembers > 0) {
                    $increasedLimit = $increasedLimit + $extraMembers;
                }

                if ($increasedLimit and $planDetails->monthly_price_per_extra_user) {
                    $increasedAmount = $increasedLimit * 1 * $planDetails->monthly_price_per_extra_user;
                    $payingAmount = $payingAmount + $increasedAmount;
                }

                if ($purchased_space and $space_charges) {
                    $purchased_space_charges = $purchased_space * 1 * $space_charges;
                    $payingAmount = $payingAmount + $purchased_space_charges;
                }

                $payingAmount = $payingAmount * 100;
            }

            $orderId = rand(111111, 999999);

            $payDetails = \Stripe\Charge::create([
                'customer' => $cardDetails->customer_id,
                'amount' => $payingAmount,
                'currency' => 'USD',
                'description' => $desc,
                'metadata' => [
                    'order_id' => $orderId,
                ],
            ]);

            $paymenyResponse = $payDetails->jsonSerialize();
            if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                $amountPaid = $paymenyResponse['amount'];

                $amountPaid = $amountPaid / 100;

                $balanceTransaction = $paymenyResponse['balance_transaction'];
                $paidCurrency = $paymenyResponse['currency'];
                $paymentStatus = $paymenyResponse['status'];
                $paymentDate = date('Y-m-d H:i:s');

                $customerName = $community->user->fullname;
                $customerEmail = $community->user->email_address;
                $cardNumber = $cardDetails->card_number;
                $cardCVC = '';
                $cardExpMonth = $cardDetails->expiry_month;
                $cardExpYear = $cardDetails->expiry_year;
                $customer_id = $cardDetails->customer_id;

                $itemName = $planDetails->plan_name;
                $itemNumber = $planDetails->plan_id;
                $itemPrice = $amountPaid;

                $amountPaidNew = $amountPaid;

                $payment_for = 'plan';
                $transaction_payment_type = $plan->plan_type;
                $plan_id = $plan->plan_id;

                if ($paymentStatus == 'succeeded') {
                    $this->communityPricingPlanPaymentRepository->addPayment($community, $community->user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, $plan_id);

                    $transaction_id = $balanceTransaction;
                }
            }
        }

        return $transaction_id;
    }

    public function payingForPlanByCard($community, $planDetails, $payment_type)
    {
        if ($planDetails->is_plan_free == 1) {
            return 1;
        }

        $cardDetails = $community->present()->getCardDetails();

        // require_once app_path('library/stripe-php/init.php');
        $stripe = [
            'secret_key' => config('stripe_secret_key'),
            'publishable_key' => config('stripe_publishable_key'),
        ];

        \Stripe\Stripe::setApiKey($stripe['secret_key']);

        $this->communityPricingPlanPaymentRepository = app('App\\Repositories\\CommunityPricingPlanPaymentRepository');

        $transaction_id = '';
        if ($cardDetails) {
            $plan_id = $planDetails->plan_id;

            $purchased_space = $community->purchased_space_in_mb;
            $space_charges = config('community-space-monthly-charges-per-mb');
            $purchased_space_charges = '';

            if ($payment_type == 'yearly') {
                $payingAmount = $planDetails->price_yearly;
                $desc = $planDetails->plan_name;

                $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan_id, $planDetails);
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                // $column_name="increased_member_limit_plan_".$plan_id;
                $column_name = 'increased_member_limit';
                $increasedLimit = $community->$column_name;

                if ($extraMembers > 0) {
                    $increasedLimit = $increasedLimit + $extraMembers;
                }

                if ($increasedLimit and $planDetails->monthly_price_per_extra_user) {
                    $increasedAmount = $increasedLimit * 12 * $planDetails->monthly_price_per_extra_user;
                    $payingAmount = $payingAmount + $increasedAmount;
                }

                if ($purchased_space and $space_charges) {
                    $purchased_space_charges = $purchased_space * 12 * $space_charges;
                    $payingAmount = $payingAmount + $purchased_space_charges;
                }

                $payingAmount = $payingAmount * 100;
            } else {
                $payingAmount = $planDetails->price_monthly;
                $desc = $planDetails->plan_name;

                $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan_id, $planDetails);
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                // $column_name="increased_member_limit_plan_".$plan_id;
                $column_name = 'increased_member_limit';
                $increasedLimit = $community->$column_name;
                if ($extraMembers > 0) {
                    $increasedLimit = $increasedLimit + $extraMembers;
                }

                if ($increasedLimit and $planDetails->monthly_price_per_extra_user) {
                    $increasedAmount = $increasedLimit * 1 * $planDetails->monthly_price_per_extra_user;
                    $payingAmount = $payingAmount + $increasedAmount;
                }

                if ($purchased_space and $space_charges) {
                    $purchased_space_charges = $purchased_space * 1 * $space_charges;
                    $payingAmount = $payingAmount + $purchased_space_charges;
                }

                $payingAmount = $payingAmount * 100;
            }

            $orderId = rand(111111, 999999);

            $payDetails = \Stripe\Charge::create([
                'customer' => $cardDetails->customer_id,
                'amount' => $payingAmount,
                'currency' => 'USD',
                'description' => $desc,
                'metadata' => [
                    'order_id' => $orderId,
                ],
            ]);

            $paymenyResponse = $payDetails->jsonSerialize();
            if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                $amountPaid = $paymenyResponse['amount'];

                $amountPaid = $amountPaid / 100;

                $balanceTransaction = $paymenyResponse['balance_transaction'];
                $paidCurrency = $paymenyResponse['currency'];
                $paymentStatus = $paymenyResponse['status'];
                $paymentDate = date('Y-m-d H:i:s');

                $customerName = $community->user->fullname;
                $customerEmail = $community->user->email_address;
                $cardNumber = $cardDetails->card_number;
                $cardCVC = '';
                $cardExpMonth = $cardDetails->expiry_month;
                $cardExpYear = $cardDetails->expiry_year;
                $customer_id = $cardDetails->customer_id;

                $itemName = $planDetails->plan_name;
                $itemNumber = $planDetails->plan_id;
                $itemPrice = $amountPaid;

                $amountPaidNew = $amountPaid;

                $payment_for = 'plan';
                $transaction_payment_type = $payment_type;
                $plan_id = $planDetails->plan_id;

                if ($paymentStatus == 'succeeded') {
                    $this->communityPricingPlanPaymentRepository->addPayment($community, $community->user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, $plan_id);

                    $transaction_id = $balanceTransaction;
                }
            }
        }

        return $transaction_id;
    }

    public function addCommunityPendingPayment($community, $planDetails)
    {
        $this->communityPricingPlanPaymentRepository->addCommunityPendingPayment($community, $planDetails);
    }

    public function getIdmeetsSubscriptions($limit = 10)
    {
        return $this->model
            ->where('add_payment_type', '=', 'idmeets')
            ->paginate($limit);
    }

    public function getIdmeetsById($id)
    {
        return $this->model
            ->where('add_payment_type', '=', 'idmeets')
            ->where('id', '=', $id)
            ->first();
    }

    public function doCommunitySubscriptionPendingPayment($community, $id)
    {
        $this->communityPricingPlanPaymentRepository = app('App\\Repositories\\CommunityPricingPlanPaymentRepository');
        $payment = $this->communityPricingPlanPaymentRepository->getByIdCommunityId($community->id, $id);

        $transaction_id = '';
        if ($payment) {
            $cardDetails = $community->present()->getCardDetails();

            // require_once app_path('library/stripe-php/init.php');
            $stripe = [
                'secret_key' => config('stripe_secret_key'),
                'publishable_key' => config('stripe_publishable_key'),
            ];

            \Stripe\Stripe::setApiKey($stripe['secret_key']);

            $this->communityPricingPlanPaymentRepository = app('App\\Repositories\\CommunityPricingPlanPaymentRepository');

            $payingAmount = $payment->item_price;

            if ($cardDetails) {
                $payingAmount = $payingAmount * 100;

                $orderId = rand(111111, 999999);

                $payDetails = \Stripe\Charge::create([
                    'customer' => $cardDetails->customer_id,
                    'amount' => $payingAmount,
                    'currency' => 'USD',
                    'description' => $payment->item_name,
                    'metadata' => [
                        'order_id' => $orderId,
                    ],
                ]);

                $paymenyResponse = $payDetails->jsonSerialize();
                if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                    $amountPaid = $paymenyResponse['amount'];
                    $amountPaid = $amountPaid / 100;

                    $transaction_id = $paymenyResponse['balance_transaction'];
                    $paidCurrency = $paymenyResponse['currency'];
                    $paymentStatus = $paymenyResponse['status'];
                    $paymentDate = date('Y-m-d H:i:s');

                    $customerName = $community->user->fullname;
                    $customerEmail = $community->user->email_address;
                    $cardNumber = $cardDetails->card_number;
                    $cardExpMonth = $cardDetails->expiry_month;
                    $cardExpYear = $cardDetails->expiry_year;
                    $customer_id = $cardDetails->customer_id;

                    if ($paymentStatus == 'succeeded') {
                        $payment->status = 'Paid';
                        $payment->transaction_id = $transaction_id;
                        $payment->amount = $amountPaid;
                        $payment->currency = $paidCurrency;
                        $payment->cust_name = $cardDetails->card_name;
                        $payment->card_number = $cardNumber;
                        $payment->card_exp_month = $cardExpMonth;
                        $payment->card_exp_year = $cardExpYear;
                        $payment->item_price = '';
                        $payment->payment_status = $paymentStatus;
                        $payment->item_number = $payment->plan_id;
                        $payment->save();

                        if ($payment->payment_type == 'yearly') {
                            $this->communityPricingPlanPaymentRepository->addPendingYearlyPayment($community, $payment);
                        }
                    }
                }
            }
        }

        return $transaction_id;
    }

    public function getCommunitySubscriptionsEnding($beforeDays)
    {
        $start_date = date('Y-m-d');
        $dateAfterDays = date('Y-m-d', strtotime('+'.$beforeDays.' days', strtotime($start_date)));

        $planData = $this->model
            ->where('add_payment_type', 'community')
            ->where('plan_end_date', $dateAfterDays)
            ->get();

        return $planData;
    }

    public function getCommunitySubscriptionsEndsOn($endDate)
    {
        $planData = $this->model
            ->with('community')
            ->where('add_payment_type', 'community')
        // ->where('plan_end_date',$endDate)
            ->where('plan_end_date', '<=', $endDate)
            ->get();

        return $planData;
    }
}
