Completed
Push — development ( c72a58...bbb3cb )
by Ashutosh
10:50 queued 12s
created

CheckoutController::checkregularPaymentOrRenewal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Front;
4
5
use App\ApiKey;
6
use App\Http\Controllers\Common\MailChimpController;
7
use App\Http\Controllers\Common\TemplateController;
8
use App\Model\Common\Setting;
9
use App\Model\Common\State;
10
use App\Model\Common\Template;
11
use App\Model\Order\Invoice;
12
use App\Model\Order\InvoiceItem;
13
use App\Model\Order\Order;
14
use App\Model\Payment\Plan;
15
use App\Model\Product\Price;
16
use App\Model\Product\Product;
17
use App\Model\Product\Subscription;
18
use App\User;
19
use Bugsnag;
20
use Cart;
21
use Illuminate\Http\Request;
22
23
class CheckoutController extends InfoController
24
{
25
    public $subscription;
26
    public $plan;
27
    public $templateController;
28
    public $product;
29
    public $price;
30
    public $user;
31
    public $setting;
32
    public $template;
33
    public $order;
34
    public $addon;
35
    public $invoice;
36
    public $invoiceItem;
37
    public $mailchimp;
38
39
    public function __construct()
40
    {
41
        $subscription = new Subscription();
42
        $this->subscription = $subscription;
43
44
        $plan = new Plan();
45
        $this->plan = $plan;
46
47
        $templateController = new TemplateController();
48
        $this->templateController = $templateController;
49
50
        $product = new Product();
51
        $this->product = $product;
52
53
        $price = new Price();
54
        $this->price = $price;
55
56
        $user = new User();
57
        $this->user = $user;
58
59
        $setting = new Setting();
60
        $this->setting = $setting;
61
62
        $template = new Template();
63
        $this->template = $template;
64
65
        $order = new Order();
66
        $this->order = $order;
67
68
        $invoice = new Invoice();
69
        $this->invoice = $invoice;
70
71
        $invoiceItem = new InvoiceItem();
72
        $this->invoiceItem = $invoiceItem;
73
74
        // $mailchimp = new MailChimpController();
75
        // $this->mailchimp = $mailchimp;
76
    }
77
78
    /*
79
      * When Proceed to chekout button clicked first request comes here
80
     */
81
    public function checkoutForm(Request $request)
82
    {
83
        if (!\Auth::user()) {//If User is not Logged in then send him to login Page
84
            $url = $request->segments(); //The requested url (chekout).Save it in Session
85
            \Session::put('session-url', $url[0]);
86
            $content = Cart::getContent();
87
            $domain = $request->input('domain');
88
            if ($domain) {
89
                foreach ($domain as $key => $value) {
90
                    \Session::put('domain'.$key, $value); //Store all the domains Entered in Cart Page in Session
91
                }
92
            }
93
            \Session::put('content', $content);
94
95
            return redirect('auth/login')->with('fails', 'Please login');
96
        }
97
        if (\Session::has('items')) {
98
            $content = \Session::get('items');
99
            $attributes = $this->getAttributes($content);
100
        } else {
101
            $content = Cart::getContent();
102
            $attributes = $this->getAttributes($content);
103
104
            $content = Cart::getContent();
105
        }
106
107
        try {
108
            $domain = $request->input('domain');
109
            if ($domain) {//Store the Domain  in session when user Logged In
110
                foreach ($domain as $key => $value) {
111
                    \Session::put('domain'.$key, $value);
112
                }
113
            }
114
115
            return view('themes.default1.front.checkout', compact('content', 'attributes'));
116
        } catch (\Exception $ex) {
117
            app('log')->error($ex->getMessage());
118
            Bugsnag::notifyException($ex);
119
120
            return redirect()->back()->with('fails', $ex->getMessage());
121
        }
122
    }
123
124
    /**
125
     * Get all the Attributes Sent From the cart along with Tax Conditions.
126
     *
127
     * @param array $content Collection of the Cart Values
128
     *
129
     * @return array Items along with their details,Attributes(Currency,Agents) and Tax Conditions
130
     */
131
    public function getAttributes($content)
132
    {
133
        try {
134
            if (count($content) > 0) {//after ProductPurchase this is not true as cart is cleared
135
                foreach ($content as $key => $item) {
136
                    $attributes[] = $item->attributes;
137
                    $cart_currency = $attributes[0]['currency']['currency']; //Get the currency of Product in the cart
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $attributes seems to be defined later in this foreach loop on line 136. Are you sure it is defined here?
Loading history...
138
                    $currency = \Auth::user()->currency != $cart_currency ? \Auth::user()->currency : $cart_currency; //If User Currency and cart currency are different the currency es set to user currency.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 206 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
139
                    if ($cart_currency != $currency) {
140
                        $id = $item->id;
141
                        Cart::remove($id);
142
                    }
143
                    $require_domain = $this->product->where('id', $item->id)->first()->require_domain;
144
                    $require = [];
145
                    if ($require_domain == 1) {
146
                        $require[$key] = $item->id;
147
                    }
148
                    $cont = new CartController();
149
                    $taxConditions = $cont->checkTax($item->id); //Calculate Tax Condition by passing ProductId
150
                    Cart::remove($item->id);
151
152
                    //Return array of Product Details,attributes and their conditions
153
                    $items[] = ['id' => $item->id, 'name' => $item->name, 'price' => $item->price,
154
                    'quantity'       => $item->quantity, 'attributes' => ['currency'=> $attributes[0]['currency'],
155
                    'agents'                                                        => $attributes[0]['agents'], 'tax'=>$taxConditions['tax_attributes'], ], 'conditions'=>$taxConditions['conditions'], ];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 203 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
156
                }
157
                Cart::add($items);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $items seems to be defined by a foreach iteration on line 135. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
158
            }
159
        } catch (\Exception $ex) {
160
            app('log')->error($ex->getMessage());
161
            Bugsnag::notifyException($ex);
162
163
            return redirect()->back()->with('fails', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ls', $ex->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type array.
Loading history...
164
        }
165
    }
166
167
    public function payNow($invoiceid)
168
    {
169
        try {
170
            $invoice = $this->invoice->find($invoiceid);
171
            $items = new \Illuminate\Support\Collection();
172
            // dd($items);
173
            if ($invoice) {
174
                $items = $invoice->invoiceItem()->get();
175
                if (count($items) > 0) {
176
                    $product = $this->product($invoiceid);
177
                }
178
            }
179
180
            return view('themes.default1.front.paynow', compact('invoice', 'items', 'product'));
181
        } catch (\Exception $ex) {
182
            app('log')->error($ex->getMessage());
183
            Bugsnag::notifyException($ex);
184
185
            return redirect()->back()->with('fails', $ex->getMessage());
186
        }
187
    }
188
189
    public function postCheckout(Request $request)
190
    {
191
        $invoice_controller = new \App\Http\Controllers\Order\InvoiceController();
192
        $info_cont = new \App\Http\Controllers\Front\InfoController();
193
        $payment_method = $request->input('payment_gateway');
194
        \Session::put('payment_method', $payment_method);
195
        $paynow = $this->checkregularPaymentOrRenewal($request->input('invoice_id'));
196
        $cost = $request->input('cost');
197
        $state = $this->getState();
198
        try {
199
            if ($paynow === false) {
200
                /*
201
                 * Do order, invoicing etc
202
                 */
203
204
                $invoice = $invoice_controller->generateInvoice();
205
206
                $pay = $this->payment($payment_method, $status = 'pending');
207
                $payment_method = $pay['payment'];
208
                $status = $pay['status'];
209
                $invoice_no = $invoice->number;
210
                $date = $this->getDate($invoice);
211
                $invoiceid = $invoice->id;
212
                $amount = $invoice->grand_total;
213
                $url = '';
214
                $cart = Cart::getContent();
215
                $invoices = $this->invoice->find($invoiceid);
216
                $items = new \Illuminate\Support\Collection();
217
                if ($invoices) {
218
                    $items = $invoice->invoiceItem()->get();
219
                    $product = $this->product($invoiceid);
220
                    $content = Cart::getContent();
221
                    $attributes = $this->getAttributes($content);
222
                }
223
            } else {
224
                $items = new \Illuminate\Support\Collection();
225
                $invoiceid = $request->input('invoice_id');
226
                $invoice = $this->invoice->find($invoiceid);
227
                $date = $this->getDate($invoice);
228
                $items = $invoice->invoiceItem()->get();
229
                $product = $this->product($invoiceid);
230
                $amount = $invoice->grand_total;
231
                $content = Cart::getContent();
232
                $attributes = $this->getAttributes($content);
233
            }
234
            if (Cart::getSubTotal() != 0 || $cost > 0) {
235
                $this->validate($request, [
236
                    'payment_gateway'=> 'required',
237
                    ],[
238
                        'payment_gateway.required'=> 'Please Select a Payment Gateway',
239
                    ]);
240
                if ($payment_method == 'razorpay') {
241
                    $rzp_key = ApiKey::where('id', 1)->value('rzp_key');
242
                    $rzp_secret = ApiKey::where('id', 1)->value('rzp_secret');
243
                    $apilayer_key = ApiKey::where('id', 1)->value('apilayer_key');
244
245
                    return view(
246
                        'themes.default1.front.postCheckout',
247
                        compact(
248
                            'amount',
249
                            'invoice_no',
250
                            ' invoiceid',
251
                            ' payment_method',
252
                            'phone',
253
                            'invoice',
254
                            'items',
255
                            'product',
256
                            'paynow',
257
                            'content',
258
                            'attributes',
259
                            'rzp_key',
260
                            'rzp_secret',
261
                            'apilayer_key'
262
                        )
263
                    );
264
                } else {
265
                    \Event::fire(new \App\Events\PaymentGateway(['request' => $request, 'cart' => Cart::getContent(), 'order' => $invoice]));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 141 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
266
                }
267
            } else {
268
                if ($paynow == false) {//Regular Payment for free Product
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
269
                     $action = $this->checkoutAction($invoice);
270
                 } else {//Renewal Payment for free Product
271
                     $control = new \App\Http\Controllers\Order\RenewController();
272
                    $control->successRenew($invoice);
273
                    $payment = new \App\Http\Controllers\Order\InvoiceController();
274
                    $payment->postRazorpayPayment($invoice->id, $invoice->grand_total);
275
276
                 }
277
               
278
                // $check_product_category = $this->product($invoiceid);
279
                $url = '';
280
                // if ($check_product_category->category) {
281
                    $url = view('themes.default1.front.postCheckoutTemplate', compact(
282
                        'invoice',
283
                        'date',
284
                        'product',
285
                        'items',
286
                        'attributes',
287
                        'state'
288
                    ))->render();
289
                // }
290
291
                \Cart::clear();
292
293
                return redirect()->back()->with('success', $url);
294
            }
295
        } catch (\Exception $ex) {
296
            app('log')->error($ex->getMessage());
297
            Bugsnag::notifyException($ex);
298
299
            return redirect()->back()->with('fails', $ex->getMessage());
300
        }
301
    }
302
303
    public function checkregularPaymentOrRenewal($invoiceid)
304
    {
305
        $paynow = false;
306
         if ($invoiceid) {
307
            $paynow = true;
308
        }
309
        return $paynow;
310
    }
311
312
    public function checkoutAction($invoice)
313
    {
314
        try {
315
            //get elements from invoice
316
            $invoice_number = $invoice->number;
317
            $invoice_id = $invoice->id;
318
            $invoice->status = 'success';
319
            $invoice->save();
320
            $user_id = \Auth::user()->id;
321
322
            $url = '';
323
324
            $url = url("download/$user_id/$invoice->number");
325
            $payment = new \App\Http\Controllers\Order\InvoiceController();
326
            $payment->postRazorpayPayment($invoice_id, $invoice->grand_total);
327
            //execute the order
328
            $order = new \App\Http\Controllers\Order\OrderController();
329
            $order->executeOrder($invoice->id, $order_status = 'executed');
330
            return 'success';
331
        } catch (\Exception $ex) {
332
            app('log')->error($ex->getMessage());
333
            Bugsnag::notifyException($ex);
334
335
            return redirect()->back()->with('fails', $ex->getMessage());
336
        }
337
    }
338
339
    public function product($invoiceid)
340
    {
341
        try {
342
            $invoice = $this->invoiceItem->where('invoice_id', $invoiceid)->first();
343
            $name = $invoice->product_name;
344
            $product = $this->product->where('name', $name)->first();
345
346
            return $product;
347
        } catch (\Exception $ex) {
348
            app('log')->error($ex->getMessage());
349
            Bugsnag::notifyException($ex);
350
351
            throw new \Exception($ex->getMessage());
352
        }
353
    }
354
355
}
356