Completed
Push — development ( c2ff46...95cb59 )
by Ashutosh
28:29 queued 18:30
created

MailChimpController::postMailChimpSettings()   A

Complexity

Conditions 2
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 15
rs 9.9332
c 0
b 0
f 0
cc 2
nc 4
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\Model\Common\Country;
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\Common\StatusSetting;
14
use App\Model\Product\Product;
15
use App\User;
16
use Exception;
17
use Illuminate\Http\Request;
18
19
class MailChimpController extends BaseMailChimpController
20
{
21
    protected $mail_api_key;
22
    protected $mailchimp;
23
    protected $mailchimp_field_model;
24
    protected $mailchimp_set;
25
    protected $list_id;
26
    protected $lists;
27
    protected $relation;
28
29
    public function __construct()
30
    {
31
        $mailchimp_set = new MailchimpSetting();
32
        $this->mailchimp_set = $mailchimp_set->firstOrFail();
33
        $this->mail_api_key = $this->mailchimp_set->api_key;
34
        $this->list_id = $this->mailchimp_set->list_id;
35
        $this->product_group_id = $this->mailchimp_set->group_id_products;
36
        $this->is_paid_group_id = $this->mailchimp_set->group_id_is_paid;
37
38
        $mailchimp_filed_model = new MailchimpField();
39
        $this->mailchimp_field_model = $mailchimp_filed_model;
40
41
        $lists = new MailchimpLists();
42
        $this->lists = $lists;
43
44
        $groups = new MailchimpGroup();
45
        $this->groups = $groups;
46
47
        $relation = new MailchimpFieldAgoraRelation();
48
        $this->relation = $relation->firstOrFail();
49
50
        $groupRelation = new MailchimpGroupAgoraRelation();
51
        $this->groupRelation = $groupRelation;
52
53
        $this->mailchimp = new \Mailchimp\Mailchimp($this->mail_api_key);
54
    }
55
56
    public function addSubscriber($email)
57
    {
58
        try {
59
            $merge_fields = $this->field($email);
60
            $interestGroupIdForNo = $this->relation->is_paid_no; //Interest GroupId for IsPaid Is No
61
              $interestGroupIdForYes = $this->relation->is_paid_yes; //Interest GroupId for IsPaid Is Yes
62
            $result = $this->mailchimp->post("lists/$this->list_id/members", [
63
                'status'        => $this->mailchimp_set->subscribe_status,
64
                'email_address' => $email,
65
                'merge_fields'  => $merge_fields,
66
67
                'interests'         => [$interestGroupIdForNo => true, $interestGroupIdForYes=>false],
68
69
            ]);
70
71
            return $result;
72
        } catch (Exception $ex) {
73
            $exe = json_decode($ex->getMessage(), true);
74
            if ($exe['status'] == 400) {
75
                throw new Exception("$email is already subscribed to newsletter", 400);
76
            }
77
        }
78
    }
79
80
    //Update to Mailchimp For Paid Product
81
    public function addSubscriberByClientPanel(Request $request)
82
    {
83
        $this->validate($request, [
84
            'email' => 'required|email',
85
        ]);
86
87
        try {
88
            $email = $request->input('email');
89
            $result = $this->mailchimp->post("lists/$this->list_id/members", [
90
                'status'        => $this->mailchimp_set->subscribe_status,
91
                'email_address' => $email,
92
93
            ]);
94
95
            return redirect()->back()->with('success', 'email added to mailchimp');
96
        } catch (Exception $ex) {
97
            $exe = json_decode($ex->getMessage(), true);
98
            if ($exe['status'] == 400) {
99
                $error = "$email is already subscribed to newsletter";
100
101
                return redirect()->back()->with('warning', $error);
102
            }
103
104
            return redirect()->back()->with('fails', $ex->getMessage());
105
        }
106
    }
107
108
    public function field($email)
109
    {
110
        try {
111
            $user = new User();
112
            $setting = new Setting();
113
            $user = $user->where('email', $email)->first();
114
            $country = Country::where('country_code_char2', $user->country)->pluck('nicename')->first();
115
            if ($user) {
116
                $fields = ['first_name', 'last_name', 'company', 'mobile',
117
                 'address', 'town', 'country', 'state', 'zip', 'active', 'role', 'source', ];
118
                $relation = $this->relation;
119
                $merge_fields = [];
120
                foreach ($fields as $field) {
121
                    if ($relation->$field) {
122
                        $merge_fields[$relation->$field] = $user->$field;
123
                    }
124
                }
125
                $merge_fields[$relation->source] = $setting->findorFail(1)->title;
126
127
                return $merge_fields;
128
            } else {
129
                return redirect()->back()->with('fails', 'user not found');
130
            }
131
        } catch (Exception $ex) {
132
            return redirect()->back()->with('fails', $ex->getMessage());
133
        }
134
    }
135
136
    public function addFieldsToAgora()
137
    {
138
        try {
139
            /** @scrutinizer ignore-call */
140
            $fields = $this->getMergeFields($this->list_id);
141
            $mailchimp_field_in_agora = $this->mailchimp_field_model->get();
142
            if (count($mailchimp_field_in_agora) > 0) {
143
                foreach ($mailchimp_field_in_agora as $field) {
144
                    $field->delete();
145
                }
146
            }
147
            foreach ($fields['merge_fields'] as $key => $value) {
148
                $merge_id = $value->merge_id;
149
                $name = $value->name;
150
                $type = $value->type;
151
                $required = $value->required;
152
                $list_id = $value->list_id;
153
                $tag = $value->tag;
154
155
                $this->mailchimp_field_model->create([
156
                    'merge_id' => $merge_id,
157
                    'tag'      => $tag,
158
                    'name'     => $name,
159
                    'type'     => $type,
160
                    'required' => $required,
161
                    'list_id'  => $list_id,
162
                ]);
163
            }
164
        } catch (Exception $ex) {
165
            return redirect()->back()->with('fails', $ex->getMessage());
166
        }
167
    }
168
169
170
 
171
172
    public function mapField()
173
    {
174
        try {
175
            $model = $this->relation;
176
            $model2 = $this->groupRelation;
177
            $this->addFieldsToAgora();
178
179
            $mailchimp_fields = $this->mailchimp_field_model
180
            ->where('list_id', $this->list_id)->pluck('name', 'tag')->toArray();
181
            $agoraProducts = Product::pluck('name', 'id')->toArray();
182
183
            $mailchimpProducts = $this->mailchimp->get("lists/$this->list_id/interest-categories");
184
            $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...
185
            $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...
186
            foreach ($allGroups['categories']  as $key => $value) {
187
                $display[] = (['id'=> $value->id, 'title'=>$value->title]);
188
            }
189
190
            $this->addProductInterestFieldsToAgora(); //add all the fields in Product Section of Groups to the db
191
            $group_fields = $this->groups->where('list_id', $this->list_id)
192
          ->select('category_name', 'category_option_id', 'category_id')->get()->toArray();
193
            // dd($group_fields[0]);
194
            $relations = MailchimpGroupAgoraRelation::where('id', '!=', 0)
195
          ->select('agora_product_id', 'mailchimp_group_cat_id')
196
          ->orderBy('id', 'asc')->get()->toArray();
197
            $productList = [];
198
            $categoryList = [];
199
            if (count($relations) != 0) {
200
                foreach ($relations as $key => $value) {
201
                    $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...
202
                    $productList[] = Product::where('id', $value['agora_product_id'])->pluck('name')->first();
203
                }
204
            }
205
            $isPaidYesId = MailchimpFieldAgoraRelation::first()->pluck('is_paid_yes')->toArray();
206
            $selectedIsPaid[] = $isPaidYesId ? MailchimpGroup::where('category_option_id', $isPaidYesId)->pluck('category_id')->first() : '';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$selectedIsPaid was never initialized. Although not strictly required by PHP, it is generally a good practice to add $selectedIsPaid = array(); before regardless.
Loading history...
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...
207
            $status = StatusSetting::select('mailchimp_product_status', 'mailchimp_ispaid_status')->first();
208
209
            return view('themes.default1.common.mailchimp.map', compact('mailchimp_fields', 'model2', 'model', 'agoraProducts', 'display', 'selectedProducts', 'relations', 'group_fields', 'categoryList', 'productList', 'status', 'selectedIsPaid'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 248 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...
210
        } catch (Exception $ex) {
211
            return redirect()->back()->with('fails', $ex->getMessage());
212
        }
213
    }
214
215
    public function addInterestFieldsToAgora(Request $request, $value)
216
    {
217
        $groupInterests = $this->mailchimp->get("lists/$this->list_id/interest-categories/$value/interests?count=20");
218
        echo '<option value="">Choose a Category</option>';
219
        if (count($groupInterests) > 0) {
220
            foreach ($groupInterests['interests'] as $key=>$value) {
0 ignored issues
show
introduced by
$value is overwriting one of the parameters of this function.
Loading history...
221
                $fields[] = (['category_id' => $value->category_id,
222
                'list_id'                   => $value->list_id,
223
                'category_option_id'        => $value->id,
224
                'category_option_name'      => $value->name,
225
            ]);
226
            }
227
            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 220. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
228
                $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...
229
                echo '<option value='.$field['category_option_id'].'>'.$field['category_option_name'].'</option>';
230
            }
231
        }
232
    }
233
234
    public function addProductInterestFieldsToAgora()
235
    {
236
        $checkCategory = ($this->mailchimp->get("lists/$this->list_id/interest-categories")['categories']);
237
        if (count($checkCategory) > 0) {
238
            foreach ($checkCategory as $interest) {
239
                $groupInterests = $this->mailchimp->get("lists/$this->list_id/interest-categories/$interest->id/interests?count=20");
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...
240
                if (count($groupInterests['interests']) > 0) {
241
                    foreach ($groupInterests['interests'] as $key => $value) {
242
                        $category_id = $value->category_id;
243
                        $list_id = $value->list_id;
244
                        $category_option_id = $value->id;
245
                        $category_option_name = $value->name;
246
                        $this->groups->updateOrCreate([
247
                'category_id'        => $category_id,
248
                'list_id'            => $list_id,
249
                'category_option_id' => $category_option_id,
250
                'category_name'      => $category_option_name,
251
            ]);
252
                    }
253
                }
254
            }
255
        }
256
    }
257
258
    public function postMapField(Request $request)
259
    {
260
        try {
261
            $this->relation->fill($request->input())->save();
262
263
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
264
        } catch (Exception $ex) {
265
            return redirect()->back()->with('fails', $ex->getMessage());
266
        }
267
    }
268
269
    public function postGroupMapField(Request $request)
270
    {
271
        try {
272
            MailchimpGroupAgoraRelation::where('id', '!=', 0)->delete();
273
            foreach ($request->row as $key => $value) {
274
                MailchimpGroupAgoraRelation::create(['agora_product_id'=> $value[0],
275
             'mailchimp_group_cat_id'                                  => $value[1], ]);
276
            }
277
278
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
279
        } catch (Exception $ex) {
280
            return redirect()->back()->with('fails', $ex->getMessage());
281
        }
282
    }
283
284
    public function postIsPaidMapField(Request $request)
285
    {
286
        try {
287
            $group = $request->input('group');
288
            $groupInterests = $this->mailchimp->get("lists/$this->list_id/interest-categories/$group/interests?count=20")['interests'];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 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...
289
            foreach ($groupInterests as $interest) {
290
                //IS Paid Should be either Yes/No or True/False
291
                if ((strcasecmp($interest->name, 'Yes') == 0) || (strcasecmp($interest->name, 'True') == 0)) {
292
                    MailchimpFieldAgoraRelation::find(1)->update(['is_paid_yes'=>$interest->id]);
293
                } elseif ((strcasecmp($interest->name, 'No') == 0) || (strcasecmp($interest->name, 'False') == 0)) {
294
                    MailchimpFieldAgoraRelation::find(1)->update(['is_paid_no'=>$interest->id]);
295
                } else {
296
                    return redirect()->back()->with('fails', 'The Group Should have Dropdown with values either Yes/No or True/False');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 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...
297
                }
298
            }
299
300
            return redirect()->back()->with('success', 'Settings Updated Successfully');
301
        } catch (Exception $ex) {
302
            return redirect()->back()->with('fails', $ex->getMessage());
303
        }
304
    }
305
}
306