<?php

namespace App\Repositories;

use App\Models\BusinessProductsOrdersDetails;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;

class BusinessProductsOrdersDetailsRepository
{
    public function __construct(
        BusinessProductsCategoryValuesRepository $businessProductsCategoryValuesRepository,
        BusinessProductsOrdersDetails $businessProductsOrdersDetails,
        Filesystem $filesystem,
        Mailer $mailer
    ) {
        $this->businessProductsCategoryValuesRepository = $businessProductsCategoryValuesRepository;
        $this->model = $businessProductsOrdersDetails;
        $this->file = $filesystem;
        $this->mailer = $mailer;
    }

    public function getById($id)
    {
        return $this->model->where('id', $id)->first();
    }

    public function addProduct($order_id,
        $productId,
        $pageId,
        $userid,
        $cartQuantity,
        $subTotal,
        $productPrice,
        $productDiscount,
        $shipping_cost,
        $community_id,
        $business_id,
        $order_date_time,
        $productsizeid,
        $product_color_id)
    {

        $sizeData = $this->businessProductsCategoryValuesRepository->getById($productsizeid);
        // $colorData=$this->businessProductsCategoryValuesRepository->getById($product_color_id);

        $order = $this->model->newInstance();
        $order->order_id = $order_id;
        $order->product_id = $productId;
        $order->business_id = $pageId;
        $order->user_id = $userid;
        $order->quantity = $cartQuantity;
        $order->amount = $subTotal;
        $order->price = $productPrice;
        $order->discount = $productDiscount;
        $order->shipping_cost = $shipping_cost;
        $order->community_id = $community_id;
        $order->community_business_id = $business_id;
        $order->order_date_time = $order_date_time;
        $order->productsizeid = $productsizeid;
        $order->product_color_id = $product_color_id;
        if ($sizeData) {
            $order->product_size = $sizeData->value;
        }

        if ($sizeData) {
            $order->product_color = $sizeData->color;
        }

        $order->save();
		
		return $order;
    }

    public function getByBusinessId($id, $community_id)
    {
        return $this->model->where('order_id', $id)->where('community_id', $community_id)->groupBy('community_business_id')->get();
    }

    public function getByBusinessIdAll($id, $community_business_id)
    {
        return $this->model->where('order_id', $id)->where('community_business_id', $community_business_id)->get();
    }

    public function getByCommunityBusinessId($community_business_id)
    {
        return $this->model->where('community_business_id', $community_business_id)->get();
    }
	
	public function getOtherCycles($recurring_parent_order_id)
    {
        return $this->model->where('recurring_parent_order_id', $recurring_parent_order_id)->get();
    }

    public function getByOrderId($order_id)
    {
        return $this->model->where('order_id', $order_id)->get();
    }
	
	public function makeSubscriptionPayment()
    {
        $todaysDate = date('Y-m-d');

        $recurringPayments = $this->model->where('subscription_cycle', '>', 'completed_cycles')->where('order_type', '=', 1)->where('next_payment_date', '=', $todaysDate)->where('subscription_payment_failed', '=', 0)->where('stop_recurring', '=', 0)->where('stop_payment', '=', 0)->where('stop_payment_seller', '=', 0)->get();

		//dd(count($recurringPayments));
        if (count($recurringPayments) > 0) {
            foreach ($recurringPayments as $orderDetails) {
				$order=app('App\\Repositories\\BusinessProductsOrdersRepository')->getById($orderDetails->order_id);
				//dd($order);
                if ($order and $order->card_customer_id) {
                    if ($order->own_account_transfer == 0) {
                        // 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']);
                    } else {
                        $payment_settings = app('App\\Repositories\\CommunityPaymentSettingRepository')->getByCmId($order->community_id);
                        $community = app('App\\Repositories\\CommunityRepository')->getById($order->community_id);

                        if ($payment_settings and $payment_settings->activate_stripe == 1 and $community and $community->take_community_payment_in_own_account == 1) {
                            $stripe = [
                                'secret_key' => $payment_settings->stripe_secret_key,
                                'publishable_key' => $payment_settings->stripe_publishable_key,
                            ];

                            if ($payment_settings->stripe_mode == 'test') {
                                $source_token = 'tok_visa';
                            } else {
                                $source_token = '';
                            }
                        } else {
                            $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 = '';
                            }
                        }
                    }

                    $orderId = rand(111111, 999999);

                    $payingAmount = $orderDetails->recurring_amount * 100;

                    try {
                        $payDetails = \Stripe\Charge::create([
                            'customer' => $order->card_customer_id,
                            'amount' => $payingAmount,
                            'currency' => 'USD',
                            'description' => 'Product subscription',
                            '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
                    }

                    $paymenyResponse = $payDetails->jsonSerialize();
                    if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                        $amountPaid = $paymenyResponse['amount'];
                        $paymentStatus = $paymenyResponse['status'];
                        $amountPaid = $amountPaid / 100;

                        if ($paymentStatus == 'succeeded') {
                            if ($orderDetails->subscription_type == 1) {
                                $next_payment_date = date('Y-m-d', strtotime('+7 day'));
                            } elseif ($orderDetails->subscription_type == 2) {
                                $next_payment_date = date('Y-m-d', strtotime('+15 day'));
                            } else {
                                // $next_payment_date=date('Y-m-d', strtotime("+1 Month"));
                                $next_payment_date = getRecurringMonthDate(date('Y-m-d'));
                            }

                            $orderDetails->next_payment_date = $next_payment_date;
                            $orderDetails->completed_cycles = $orderDetails->completed_cycles + 1;
                            $orderDetails->save();

                            $neworder = $this->model->newInstance();
                            $neworder->recurring_amount = $amountPaid;
                            $neworder->order_date_time = date('Y-m-d');
                            $neworder->recurring_order_id = $orderId;
                            $neworder->recurring_parent_order_id = $orderDetails->id;
                            $neworder->transaction_id = $paymenyResponse['balance_transaction'];
                            $neworder->save();
                        } else {
                            $orderDetails->subscription_payment_failed = 1;
                            $orderDetails->save();
                        }
                    } else {
                        $orderDetails->subscription_payment_failed = 1;
                        $orderDetails->save();
                    }
                } else {
                    $orderDetails->subscription_payment_failed = 1;
                    $orderDetails->save();
                }
            }
        }
    }
}
