Completed
Pull Request — development (#571)
by Ashutosh
10:22
created

MailChimpController::addInterestFieldsToAgora()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 20
rs 9.9
c 0
b 0
f 0
cc 4
nc 5
nop 2
1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\Http\Controllers\Controller;
6
use App\Model\Common\Mailchimp\MailchimpField;
7
use App\Model\Common\Mailchimp\MailchimpFieldAgoraRelation;
8
use App\Model\Common\Mailchimp\MailchimpGroup;
9
use App\Model\Common\Mailchimp\MailchimpGroupAgoraRelation;
10
use App\Model\Common\Mailchimp\MailchimpLists;
11
use App\Model\Common\Mailchimp\MailchimpSetting;
12
use App\Model\Common\Setting;
13
use App\Model\Product\Product;
14
use App\User;
15
use Exception;
16
use Illuminate\Http\Request;
17
18
class MailChimpController extends Controller
19
{
20
    protected $mail_api_key;
21
    protected $mailchimp;
22
    protected $mailchimp_field_model;
23
    protected $mailchimp_set;
24
    protected $list_id;
25
    protected $lists;
26
    protected $relation;
27
28
    public function __construct()
29
    {
30
        $mailchimp_set = new MailchimpSetting();
31
        $this->mailchimp_set = $mailchimp_set->firstOrFail();
32
        $this->mail_api_key = $this->mailchimp_set->api_key;
33
        $this->list_id = $this->mailchimp_set->list_id;
34
        $this->product_group_id = $this->mailchimp_set->group_id_products;
0 ignored issues
show
Bug introduced by
The property group_id_products does not seem to exist on App\Model\Common\Mailchimp\MailchimpSetting. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
35
        $this->is_paid_group_id = $this->mailchimp_set->group_id_is_paid;
0 ignored issues
show
Bug introduced by
The property group_id_is_paid does not seem to exist on App\Model\Common\Mailchimp\MailchimpSetting. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
36
37
        $mailchimp_filed_model = new MailchimpField();
38
        $this->mailchimp_field_model = $mailchimp_filed_model;
39
40
        $lists = new MailchimpLists();
41
        $this->lists = $lists;
42
43
        $groups = new MailchimpGroup();
44
        $this->groups = $groups;
45
46
        $relation = new MailchimpFieldAgoraRelation();
47
        $this->relation = $relation->firstOrFail();
48
49
        $groupRelation = new MailchimpGroupAgoraRelation();
50
        $this->groupRelation = $groupRelation;
51
52
        $this->mailchimp = new \Mailchimp\Mailchimp($this->mail_api_key);
53
    }
54
55
    public function getLists()
56
    {
57
        try {
58
            $result = $this->mailchimp->request('lists');
59
60
            return $result;
61
        } catch (Exception $ex) {
62
            dd($ex);
63
64
            return redirect()->back()->with('fails', $ex->getMessage());
65
        }
66
    }
67
68
    public function getListById()
69
    {
70
        try {
71
            $result = $this->mailchimp->request("lists/$this->list_id");
72
73
            return $result;
74
        } catch (Exception $ex) {
75
            return redirect()->back()->with('fails', $ex->getMessage());
76
        }
77
    }
78
79
    public function addSubscriber($email)
80
    {
81
        try {
82
            $merge_fields = $this->field($email);
83
            $interestGroupIdForNo = $this->relation->is_paid_no; //Interest GroupId for IsPaid Is No
0 ignored issues
show
Bug introduced by
The property is_paid_no does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
84
              $interestGroupIdForYes = $this->relation->is_paid_yes; //Interest GroupId for IsPaid Is Yes
0 ignored issues
show
Bug introduced by
The property is_paid_yes does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
85
            $result = $this->mailchimp->post("lists/$this->list_id/members", [
86
                'status'        => $this->mailchimp_set->subscribe_status,
87
                'email_address' => $email,
88
                'merge_fields'  => $merge_fields,
89
90
                'interests'         => [$interestGroupIdForNo => true, $interestGroupIdForYes=>false],
91
92
            ]);
93
94
            return $result;
95
        } catch (Exception $ex) {
96
            $exe = json_decode($ex->getMessage(), true);
97
            if ($exe['status'] == 400) {
98
                throw new Exception("$email is already subscribed to newsletter", 400);
99
            }
100
        }
101
    }
102
103
    //Update to Mailchimp For Free Product
104
    public function updateSubscriberForFreeProduct($email, $productid)
105
    {
106
        try {
107
            $merge_fields = $this->field($email);
108
            $interestGroupIdForNo = $this->relation->is_paid_no; //Interest GroupId for IsPaid Is No
0 ignored issues
show
Bug introduced by
The property is_paid_no does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
109
              $interestGroupIdForYes = $this->relation->is_paid_yes; //Interest GroupId for IsPaid Is Yes
0 ignored issues
show
Bug introduced by
The property is_paid_yes does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
110
              $productGroupId = $this->groupRelation->where('agora_product_id', $productid)
111
              ->pluck('mailchimp_group_cat_id')->first();
112
            $hash = md5($email);
113
            $result = $this->mailchimp->patch("lists/$this->list_id/members/$hash", [
114
                 'interests'         => [$interestGroupIdForNo => true, $interestGroupIdForYes=>false, $productGroupId =>true],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 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...
115
                 //refer to https://us7.api.mailchimp.com/playground
116
              ]);
117
        } catch (Exception $ex) {
118
            $exe = json_decode($ex->getMessage(), true);
119
        }
120
    }
121
122
    //Update to Mailchimp For Paid Product
123
    public function updateSubscriberForPaidProduct($email, $productid)
124
    {
125
        try {
126
            $merge_fields = $this->field($email);
127
            $interestGroupIdForNo = $this->relation->is_paid_no; //Interest GroupId for IsPaid Is No
0 ignored issues
show
Bug introduced by
The property is_paid_no does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
128
              $interestGroupIdForYes = $this->relation->is_paid_yes; //Interest GroupId for IsPaid Is Yes
0 ignored issues
show
Bug introduced by
The property is_paid_yes does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
129
               $productGroupId = $this->groupRelation->where('agora_product_id', $productid)
130
              ->pluck('mailchimp_group_cat_id')->first();
131
132
            $hash = md5($email);
133
            $result = $this->mailchimp->patch("lists/$this->list_id/members/$hash", [
134
                 'interests' => [$interestGroupIdForNo => false, $interestGroupIdForYes=>true, $productGroupId =>true],
135
136
                 //refer to https://us7.api.mailchimp.com/playground
137
              ]);
138
        } catch (Exception $ex) {
139
            $exe = json_decode($ex->getMessage(), true);
140
        }
141
    }
142
143
    public function addSubscriberByClientPanel(Request $request)
144
    {
145
        $this->validate($request, [
146
            'email' => 'required|email',
147
        ]);
148
149
        try {
150
            $email = $request->input('email');
151
            $result = $this->mailchimp->post("lists/$this->list_id/members", [
152
                'status'        => $this->mailchimp_set->subscribe_status,
153
                'email_address' => $email,
154
155
            ]);
156
157
            return redirect()->back()->with('success', 'email added to mailchimp');
158
        } catch (Exception $ex) {
159
            $exe = json_decode($ex->getMessage(), true);
160
            if ($exe['status'] == 400) {
161
                $error = "$email is already subscribed to newsletter";
162
163
                return redirect()->back()->with('warning', $error);
164
            }
165
166
            return redirect()->back()->with('fails', $ex->getMessage());
167
        }
168
    }
169
170
    public function field($email)
171
    {
172
        try {
173
            $user = new User();
174
            $setting = new Setting();
175
            $user = $user->where('email', $email)->first();
176
            if ($user) {
177
                $fields = ['first_name', 'last_name', 'company', 'mobile',
178
                 'address', 'town', 'state', 'zip', 'active', 'role', 'source', ];
179
                $relation = $this->relation;
180
                $merge_fields = [];
181
                foreach ($fields as $field) {
182
                    if ($relation->$field) {
183
                        $merge_fields[$relation->$field] = $user->$field;
184
                    }
185
                }
186
                $merge_fields[$relation->source] = $setting->findorFail(1)->title;
0 ignored issues
show
Bug introduced by
The property source does not seem to exist on App\Model\Common\Mailchi...chimpFieldAgoraRelation. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
187
188
                return $merge_fields;
189
            } else {
190
                return redirect()->back()->with('fails', 'user not found');
191
            }
192
        } catch (Exception $ex) {
193
            //dd($ex);
194
            return redirect()->back()->with('fails', $ex->getMessage());
195
        }
196
    }
197
198
    public function getMergeFields()
199
    {
200
        try {
201
            $result = $this->mailchimp->get("lists/$this->list_id/merge-fields");
202
203
            return $result;
204
        } catch (Exception $ex) {
205
            return redirect()->back()->with('fails', $ex->getMessage());
206
        }
207
    }
208
209
    public function addFieldsToAgora()
210
    {
211
        try {
212
            /** @scrutinizer ignore-call */
213
            $fields = $this->getMergeFields($this->list_id);
214
215
            $mailchimp_field_in_agora = $this->mailchimp_field_model->get();
216
            if (count($mailchimp_field_in_agora) > 0) {
217
                foreach ($mailchimp_field_in_agora as $field) {
218
                    $field->delete();
219
                }
220
            }
221
            foreach ($fields['merge_fields'] as $key => $value) {
222
                $merge_id = $value->merge_id;
223
                $name = $value->name;
224
                $type = $value->type;
225
                $required = $value->required;
226
                $list_id = $value->list_id;
227
                $tag = $value->tag;
228
229
                $this->mailchimp_field_model->create([
230
                    'merge_id' => $merge_id,
231
                    'tag'      => $tag,
232
                    'name'     => $name,
233
                    'type'     => $type,
234
                    'required' => $required,
235
                    'list_id'  => $list_id,
236
                ]);
237
            }
238
        } catch (Exception $ex) {
239
            return redirect()->back()->with('fails', $ex->getMessage());
240
        }
241
    }
242
243
    public function addListsToAgora()
244
    {
245
        try {
246
            $lists = $this->getLists();
247
            $agora_lists = $this->lists->get();
248
            if (count($agora_lists) > 0) {
249
                foreach ($agora_lists as $agora) {
250
                    $agora->delete();
251
                }
252
            }
253
            foreach ($lists['lists'] as $list) {
254
                $name = $list->name;
255
                $list_id = $list->id;
256
                $this->lists->create([
257
                    'name'    => $name,
258
                    'list_id' => $list_id,
259
                ]);
260
            }
261
            //return redirect()->back()->with('success', \Lang::get('message.mailchimp-list-added-to-agora'));
262
        } catch (Exception $ex) {
263
            return redirect()->back()->with('fails', $ex->getMessage());
264
        }
265
    }
266
267
    public function mailChimpSettings()
268
    {
269
        try {
270
            $set = $this->mailchimp_set;
271
            $lists = $this->lists->pluck('name', 'list_id')->toArray();
272
273
            return view('themes.default1.common.mailchimp.settings', compact('set', 'lists'));
274
        } catch (Exception $ex) {
275
            return redirect()->back()->with('fails', $ex->getMessage());
276
        }
277
    }
278
279
    public function postMailChimpSettings(Request $request)
280
    {
281
        $this->validate($request, [
282
            'api_key' => 'required',
283
            //'list_id'=>'required',
284
        ]);
285
286
        try {
287
            $this->mailchimp_set->fill($request->input())->save();
288
            $this->addListsToAgora();
289
290
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
291
        } catch (Exception $ex) {
292
            return redirect()->back()->with('fails', $ex->getMessage());
293
        }
294
    }
295
296
    public function mapField()
297
    {
298
        try {
299
            $model = $this->relation;
300
            $model2 = $this->groupRelation;
301
            $this->addFieldsToAgora();
302
303
            $mailchimp_fields = $this->mailchimp_field_model
304
            ->where('list_id', $this->list_id)->pluck('name', 'tag')->toArray();
305
            $agoraProducts = Product::pluck('name', 'id')->toArray();
306
307
            // $ProductsMailchimp = $this->mailchimp->get("lists/$this->list_id/interest-categories/$this->product_group_id/interests");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 136 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...
308
309
            // foreach ($ProductsMailchimp['interests'] as $mailchimpProduct) {
310
            //    $mailchimpProductsList[] = ([$mailchimpProduct->name => $mailchimpProduct->id]);
311
            // }
312
            //  $oneDimensionalArray = call_user_func_array('array_merge', $mailchimpProductsList);
313
314
            $mailchimpProducts = $this->mailchimp->get("lists/$this->list_id/interest-categories");
315
316
            $selectedProducts = MailchimpGroupAgoraRelation::select('agora_product_id', 'mailchimp_group_cat_id')->orderBy('id', 'asc')->get()->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 154 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...
317
318
            $allGroups = $this->mailchimp->get("lists/$this->list_id/interest-categories"); //Get all the groups(interest-categories for a list)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 144 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...
319
            foreach ($allGroups['categories']  as $key => $value) {
320
                $display[] = (['id'=> $value->id, 'title'=>$value->title]);
321
            }
322
323
            // dd($selectedProduct);
324
325
            $this->addProductInterestFieldsToAgora(); //add all the fields in Product Section of Groups to the db
326
            // this->addIsPaidInterestFieldsToAgora();
327
328
            $group_fields = $this->groups->where('list_id', $this->list_id)
329
          ->select('category_name', 'category_option_id', 'category_id')->get()->toArray();
330
            // dd($group_fields[0]);
331
            $relations = MailchimpGroupAgoraRelation::where('id', '!=', 0)
332
          ->select('agora_product_id', 'mailchimp_group_cat_id')
333
          ->orderBy('id', 'asc')->get()->toArray();
334
            $productList = [];
335
            $categoryList = [];
336
            if (count($relations) != 0) {
337
                foreach ($relations as $key => $value) {
338
                    $categoryList[] = $this->groups->where('category_option_id', $value['mailchimp_group_cat_id'])->pluck('category_name')->first();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 148 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...
339
                    $productList[] = Product::where('id', $value['agora_product_id'])->pluck('name')->first();
340
                    // code...
341
                }
342
                // dd(count($categoryList));
343
         // dd($productList);
344
            }
345
346
            // $relations = MailchimpGroupAgoraRelation::where('id', '!=', 0)->orderBy('id', 'asc')->get()->toArray();
347
            // dd($relations);
348
            //
349
350
            return view('themes.default1.common.mailchimp.map', compact('mailchimp_fields', 'model2', 'model', 'agoraProducts', 'display', 'selectedProducts', 'relations', 'group_fields', 'categoryList', 'productList'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 220 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...
351
        } catch (Exception $ex) {
352
            return redirect()->back()->with('fails', $ex->getMessage());
353
        }
354
    }
355
356
    public function addInterestFieldsToAgora(Request $request, $value)
357
    {
358
        $groupInterests = $this->mailchimp->get("lists/$this->list_id/interest-categories/$value/interests");
359
360
        echo '<option value="">Choose a Category</option>';
361
        if (count($groupInterests) > 0) {
362
            foreach ($groupInterests['interests'] as $key=>$value) {
0 ignored issues
show
introduced by
$value is overwriting one of the parameters of this function.
Loading history...
363
                $fields[] = (['category_id' => $value->category_id,
364
                'list_id'                   => $value->list_id,
365
                'category_option_id'        => $value->id,
366
                'category_option_name'      => $value->name,
367
            ]);
368
            }
369
            foreach ($fields as $field) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fields seems to be defined by a foreach iteration on line 362. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
370
                $selectedCategory = MailchimpGroupAgoraRelation::where('mailchimp_group_cat_id', $field['category_option_id'])->pluck('mailchimp_group_cat_id')->first();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 169 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...
371
                //   if( $selectedCategory){
372
                //     echo '<option selected= "selected" value='. $selectedCategory .'>'.$field['category_option_name'].'</option>';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 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...
373
                // }
374
375
                echo '<option value='.$field['category_option_id'].'>'.$field['category_option_name'].'</option>';
376
377
                // array_push($responseData, (['selectedCat'=>$selectedCategory, 'catId'=>$field['category_option_id'],'catName'=>$field['category_option_name']]
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 161 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...
378
                  //  ));
379
            }
380
            // return $responseData;
381
        }
382
383
        // return $a;
384
    }
385
386
    public function addProductInterestFieldsToAgora()
387
    {
388
        $groupProductInterests = $this->mailchimp->get("lists/$this->list_id/interest-categories/$this->product_group_id/interests");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 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...
389
        $groupIsPaidInterests = $this->mailchimp->get("lists/$this->list_id/interest-categories/$this->is_paid_group_id/interests");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 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...
390
        //Now Merge interests of both the groups
391
        $groupInterests = (array_merge($groupProductInterests['interests'], $groupIsPaidInterests['interests']));
392
        //get all the fields for Product Group
393
        if (count($groupInterests) > 0) {
394
            foreach ($groupInterests as $key=>$value) {
395
                $category_id = $value->category_id;
396
                $list_id = $value->list_id;
397
                $category_option_id = $value->id;
398
                $category_option_name = $value->name;
399
                $this->groups->updateOrCreate([
400
                'category_id'        => $category_id,
401
                'list_id'            => $list_id,
402
                'category_option_id' => $category_option_id,
403
                'category_name'      => $category_option_name,
404
            ]);
405
            }
406
        }
407
    }
408
409
    public function postMapField(Request $request)
410
    {
411
        try {
412
            $this->relation->fill($request->input())->save();
413
414
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
415
        } catch (Exception $ex) {
416
            dd($ex);
417
418
            return redirect()->back()->with('fails', $ex->getMessage());
419
        }
420
    }
421
422
    public function postGroupMapField(Request $request)
423
    {
424
        try {
425
            MailchimpGroupAgoraRelation::where('id', '!=', 0)->delete();
426
            foreach ($request->row as $key => $value) {
427
                MailchimpGroupAgoraRelation::create(['agora_product_id'=> $value[0],
428
             'mailchimp_group_cat_id'                                  => $value[1], ]);
429
            }
430
431
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
432
        } catch (Exception $ex) {
433
            dd($ex);
434
435
            return redirect()->back()->with('fails', $ex->getMessage());
436
        }
437
    }
438
}
439