Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 1012
0.00% covered (danger)
0.00%
0 / 45
CRAP
0.00% covered (danger)
0.00%
0 / 1
Companies
0.00% covered (danger)
0.00%
0 / 1012
0.00% covered (danger)
0.00%
0 / 45
37056
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 create_company
0.00% covered (danger)
0.00%
0 / 327
0.00% covered (danger)
0.00%
0 / 1
1980
 list_companies
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 get_company
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 get_company_users
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 get_user_companies
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
42
 update_company_users
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 update_company_selected
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 delete_company_users
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 update_company
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 update_company_blocked
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 upload_file
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
30
 delete_company
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 update_company_users_selected
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 create_company_users
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
42
 get_cc_bcc
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_blocked_domains
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 delete_blocked_domain
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 update_blocked_domain
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 create_blocked_domain
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 list_project_types
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 get_project_types
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
12
 update_project_types
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
30
 update_project_types_benchmarks
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 delete_project_types
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 list_workflow_project_types
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_project_types
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 delete_workflow_project_types
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 list_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 delete_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 list_workflow_questions
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_questions
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 get_company_executive
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_all_details
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
6
 list_all_companies
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 update_company_permission
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
20
 list_facility_settings
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 update_facility_settings
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
90
 list_trade_alignment_settings
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 update_trade_alignment_settings
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblUsers;
6use App\Models\TblCompanies;
7use App\Models\TblCompanyUsers;
8use App\Models\TblBudgetStatus;
9use App\Models\TblCustomerTypes;
10use App\Models\TblBudgetTypes;
11use App\Models\TblSources;
12use App\Models\TblEmailConfiguration;
13use App\Models\TblCcBcc;
14use App\Models\TblBlockedDomains;
15use App\Models\TblProjectTypes;
16use App\Models\TblWorkflowProjectTypes;
17use App\Models\TblWorkflowCustomerTypes;
18use App\Models\TblWorkflowQuestions;
19use App\Models\TblQuotations;
20use App\Models\TblOngoingJobs;
21use App\Models\TblApprovers;
22use App\Models\TblApproversV2;
23use App\Models\TblCcAcceptanceNotifications;
24use App\Models\TblCcBccNotifications;
25use App\Models\TblCcBccRequestNotifications;
26use App\Models\TblCcG3WEmailReminders;
27use App\Models\TblCompanyEmails;
28use App\Models\TblToAcceptanceNotifications;
29use App\Models\TblWorkflowApprover;
30use App\Models\TblLastFollowUpDate;
31use App\Models\TblFacilitySettings;
32use App\Models\TblTradeAlignmentSettings;
33use App\Models\TblFinalSummary;
34use Illuminate\Support\Facades\App;
35use Illuminate\Http\Request;
36use Illuminate\Support\Facades\DB;
37use Illuminate\Support\Facades\Storage;
38use Illuminate\Support\Facades\Validator;
39use Illuminate\Support\Facades\Cache;
40
41class Companies extends Controller
42{
43    public function __construct(){
44        $this->locale = @getallheaders()['Locale-ID'];
45        $this->userId = @getallheaders()['User-ID'];
46        $this->region = @getallheaders()['Region'];
47        
48        App::setLocale($this->locale);
49
50        $this->companyIds = array();
51
52        if($this->region != null && $this->region != "" && $this->region != "All"){
53            $this->region = urldecode($this->region);
54            
55            $query = "SELECT 
56                        b.company_id
57                    FROM 
58                        tbl_company_users a 
59                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
60                    WHERE 
61                        a.user_id = {$this->userId}
62                        AND b.region = '{$this->region}'";
63            
64            $this->companyIds = DB::select($query);
65
66            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
67        }else{
68            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
69        }
70        
71        $this->companyId = implode(',', $this->companyIds);
72    }
73
74    public function create_company(Request $request){
75
76        try {        
77
78            $data = $request->all();
79            $data['updated_at'] = date('Y-m-d H:i:s');
80            $logo = Storage::get('logo-light.png');
81            $base64 = base64_encode($logo);
82            $mimetype = 'image/png';
83            $blob = 'data:' . $mimetype . ';base64,' . $base64;
84            $data['logo'] = $blob;
85            $data['filename'] = 'logo-light.png';
86            $data['filesize'] = 6233;
87            $data['filetype'] = $mimetype;
88            $data['default_page'] = 'orders';
89            $userId = $data['user_id'];
90            unset($data['user_id']);
91
92            $result = array();
93            $newCompanyId = 0;
94
95            DB::beginTransaction();
96
97            if(isset($data['template_company_id'])){
98                $companyId = addslashes($data['template_company_id']);
99
100                $company = TblCompanies::where('company_id', $companyId)->first();
101
102                $data['is_send'] = $company->is_send;
103                $data['limit_send'] = $company->limit_send;
104                $data['is_send_follow_up'] = $company->is_send_follow_up;
105                $data['is_send_request'] = $company->is_send_request;
106                $data['is_send_g3w'] = $company->is_send_g3w;
107                $data['revenue_per_employee_per_day'] = $company->revenue_per_employee_per_day;
108                $data['minimum_margin'] = $company->minimum_margin;
109                $data['general_costs'] = $company->general_costs;
110                $data['hours_per_worker_per_day'] = $company->hours_per_worker_per_day;
111                $data['cost_of_hour'] = $company->cost_of_hour;
112                $data['hours_per_worker_per_day_percentage'] = $company->hours_per_worker_per_day_percentage;
113                $data['convert_to_job_amount_limit'] = $company->convert_to_job_amount_limit;
114                $data['minimum_order_size'] = $company->minimum_order_size;
115                $data['minimum_order_size_v2'] = $company->minimum_order_size_v2;
116                $data['last_follow_up_date'] = $company->last_follow_up_date;
117                $data['limit_reminder_emails'] = $company->limit_reminder_emails;
118                $data['workflow_budget_size'] = $company->workflow_budget_size;
119                $data['is_send_executive'] = $company->is_send_executive;
120                $data['customer_type_ids'] = $company->customer_type_ids;
121                $data['goal_for_the_year'] = $company->goal_for_the_year;
122                $data['logo'] = $company->logo;
123                $data['filetype'] = $company->filetype;
124                $data['filename'] = $company->filename;
125                $data['filesize'] = $company->filesize;
126
127                $result = TblCompanies::create($data);
128                $newCompanyId = $result->company_id;
129
130                $approvers = TblApprovers::where('company_id', $companyId)->get();
131
132                if(count($approvers) > 0){
133                    $newApprovers = [];
134                    foreach ($approvers as $item) {
135                        $newApprovers[] = [
136                            'company_id' => $newCompanyId,
137                            'user_id' => $item->user_id,
138                            'created_by' => $data['created_by']
139                        ];
140                    }
141                    
142                    TblApprovers::insert((array) $newApprovers);
143                }
144
145                $approversV2 = TblApproversV2::where('company_id', $companyId)->get();
146
147                if(count($approversV2) > 0){
148                    $newApproversV2 = [];
149                    foreach ($approversV2 as $item) {
150                        $newApproversV2[] = [
151                            'company_id' => $newCompanyId,
152                            'user_id' => $item->user_id,
153                            'created_by' => $data['created_by']
154                        ];
155                    }
156                    
157                    TblApproversV2::insert((array) $newApproversV2);
158                }
159
160                $blockedDomains = TblBlockedDomains::where('company_id', $companyId)->get();
161
162                if(count($blockedDomains) > 0){
163                    $newBlockedDomains = [];
164                    foreach ($blockedDomains as $item) {
165                        $newBlockedDomains[] = [
166                            'company_id' => $newCompanyId,
167                            'domain' => $item->domain,
168                            'created_by' => $data['created_by']
169                        ];
170                    }
171                    
172                    TblBlockedDomains::insert((array) $newBlockedDomains);
173                }
174
175                $ccAcceptanceNotifications = TblCcAcceptanceNotifications::where('company_id', $companyId)->get();
176
177                if(count($ccAcceptanceNotifications) > 0){
178                    $newCcAcceptanceNotifications = [];
179                    foreach ($ccAcceptanceNotifications as $item) {
180                        $newCcAcceptanceNotifications[] = [
181                            'company_id' => $newCompanyId,
182                            'email' => $item->email,
183                            'created_by' => $data['created_by']
184                        ];
185                    }
186                    
187                    TblCcAcceptanceNotifications::insert((array) $newCcAcceptanceNotifications);
188                }
189
190                $ccBcc = TblCcBcc::where('company_id', $companyId)->get();
191
192                if(count($ccBcc) > 0){
193                    $newCcBcc = [];
194                    foreach ($ccBcc as $item) {
195                        $newCcBcc[] = [
196                            'company_id' => $newCompanyId,
197                            'email' => $item->email,
198                            'created_by' => $data['created_by']
199                        ];
200                    }
201                    
202                    TblCcBcc::insert((array) $newCcBcc);
203                }
204
205                $ccBccNotifications = TblCcBccNotifications::where('company_id', $companyId)->get();
206
207                if(count($ccBccNotifications) > 0){
208                    $newCcBccNotifications = [];
209                    foreach ($ccBccNotifications as $item) {
210                        $newCcBccNotifications[] = [
211                            'company_id' => $newCompanyId,
212                            'email' => $item->email,
213                            'created_by' => $data['created_by']
214                        ];
215                    }
216                    
217                    TblCcBccNotifications::insert((array) $newCcBccNotifications);
218                }
219
220                $ccBccRequestNotifications = TblCcBccRequestNotifications::where('company_id', $companyId)->get();
221
222                if(count($ccBccRequestNotifications) > 0){
223                    $newCcBccRequestNotifications = [];
224                    foreach ($ccBccRequestNotifications as $item) {
225                        $newCcBccRequestNotifications[] = [
226                            'company_id' => $newCompanyId,
227                            'email' => $item->email,
228                            'created_by' => $data['created_by']
229                        ];
230                    }
231                    
232                    TblCcBccRequestNotifications::insert((array) $newCcBccRequestNotifications);
233                }
234
235                $ccG3WEmailReminders = TblCcG3WEmailReminders::where('company_id', $companyId)->get();
236
237                if(count($ccG3WEmailReminders) > 0){
238                    $newCcG3WEmailReminders = [];
239                    foreach ($ccG3WEmailReminders as $item) {
240                        $newCcG3WEmailReminders[] = [
241                            'company_id' => $newCompanyId,
242                            'email' => $item->email,
243                            'created_by' => $data['created_by']
244                        ];
245                    }
246                    
247                    TblCcG3WEmailReminders::insert((array) $newCcG3WEmailReminders);
248                }
249                
250                $companyEmails = TblCompanyEmails::where('company_id', $companyId)->get();
251
252                if(count($companyEmails) > 0){
253                    $newCompanyEmails = [];
254                    foreach ($companyEmails as $item) {
255                        $newCompanyEmails[] = [
256                            'response_id' => $item->response_id,
257                            'company_id' => $newCompanyId,
258                            'nickname' => $item->nickname,
259                            'from_email' => $item->from_email,
260                            'from_name' => $item->from_name,
261                            'reply_to' => $item->reply_to,
262                            'reply_to_name' => $item->reply_to_name,
263                            'address' => $item->address,
264                            'state' => $item->state,
265                            'city' => $item->city,
266                            'country' => $item->country,
267                            'zip' => $item->zip,
268                            'verified' => $item->verified,
269                            'locked' => $item->locked,
270                            'is_active' => $item->is_active,
271                            'created_by' => $data['created_by']
272                        ];
273                    }
274                    
275                    TblCompanyEmails::insert((array) $newCompanyEmails);
276                }
277
278                $companyUsers = TblCompanyUsers::where('company_id', $companyId)->get();
279
280                if(count($companyUsers) > 0){
281                    $newCompanyUsers = [];
282                    foreach ($companyUsers as $item) {
283                        $newCompanyUsers[] = [
284                            'user_id' => $item->user_id,
285                            'company_id' => $newCompanyId,
286                            'can_read' => $item->can_read,
287                            'can_write' => $item->can_write,
288                            'is_selected' => $item->is_selected,
289                            'created_by' => $data['created_by']
290                        ];
291                    }
292                    
293                    TblCompanyUsers::insert((array) $newCompanyUsers);
294                }
295
296                $emailConfiguration = TblEmailConfiguration::where('company_id', $companyId)->get();
297
298                if(count($emailConfiguration) > 0){
299                    $newEmailConfiguration = [];
300                    foreach ($emailConfiguration as $item) {
301                        $newEmailConfiguration[] = [
302                            'company_id' => $newCompanyId,
303                            'from_id' => $item->from_id,
304                            'name' => $item->name,
305                            'subject' => $item->subject,
306                            'html' => $item->html,
307                            'is_active' => $item->is_active,
308                            'type' => $item->type,
309                            'created_by' => $data['created_by'],
310                            'email_template_id_copied' => $item->id
311                        ];
312                    }
313                    
314                    TblEmailConfiguration::insert((array) $newEmailConfiguration);
315
316                    $query = "SELECT 
317                                a.id, 
318                                (
319                                    SELECT 
320                                        id 
321                                    FROM 
322                                        tbl_company_emails 
323                                    WHERE 
324                                        from_email = b.from_email 
325                                        AND company_id = {$newCompanyId}
326                                ) from_id 
327                                FROM 
328                                    tbl_email_configuration a 
329                                LEFT JOIN tbl_company_emails b 
330                                    ON a.from_id = b.id 
331                                WHERE 
332                                    a.company_id = {$newCompanyId}";
333
334                    $r = DB::select($query);
335
336                    foreach ($r as $item) {
337                        TblEmailConfiguration::where('id', $item->id)->update(array('from_id' => $item->from_id));
338                    }
339
340                    $query = "INSERT INTO tbl_email_files (
341                                    email_template_id, 
342                                    original_name, 
343                                    filename, 
344                                    uploaded_by, 
345                                    uploaded_at
346                                ) 
347                                SELECT 
348                                    b.id, 
349                                    a.original_name, 
350                                    a.filename, 
351                                    '{$data['created_by']}', 
352                                    NOW() 
353                                FROM 
354                                    tbl_email_files a 
355                                LEFT JOIN tbl_email_configuration b 
356                                    ON a.email_template_id = b.email_template_id_copied 
357                                WHERE 
358                                    b.company_id = {$newCompanyId}";
359
360                    DB::select($query);
361                }
362
363                $projectTypes = TblProjectTypes::where('company_id', $companyId)->get();
364
365                if(count($projectTypes) > 0){
366                    $newProjectTypes = [];
367                    foreach ($projectTypes as $item) {
368                        $newProjectTypes[] = [
369                            'company_id' => $newCompanyId,
370                            'project_id' => $item->project_id,
371                            'budget_type_id' => $item->budget_type_id,
372                            'customer_type_ids' => $item->customer_type_ids,
373                            'revenue_per_employee_per_day' => $item->revenue_per_employee_per_day,
374                            'minimum_margin' => $item->minimum_margin,
375                            'general_costs' => $item->general_costs,
376                            'minimum_order_size' => $item->minimum_order_size,
377                            'minimum_order_size_v2' => $item->minimum_order_size_v2,
378                            'created_by' => $data['created_by']
379                        ];
380                    }
381                    
382                    TblProjectTypes::insert((array) $newProjectTypes);
383                }
384
385                $lastFolloUpDates = TblLastFollowUpDate::where('company_id', $companyId)->get();
386
387                if(count($lastFolloUpDates) > 0){
388                    $newLastFollowUpDate = [];
389                    foreach ($lastFolloUpDates as $item) {
390                        $newLastFollowUpDate[] = [
391                            'company_id' => $newCompanyId,
392                            'row_id' => $item->row_id,
393                            'budget_type_id' => $item->budget_type_id,
394                            'last_follow_up_date' => $item->last_follow_up_date,
395                            'created_by' => $data['created_by']
396                        ];
397                    }
398                    
399                    TblLastFollowUpDate::insert((array) $newLastFollowUpDate);
400                }
401
402                $toAcceptanceNotifications = TblToAcceptanceNotifications::where('company_id', $companyId)->get();
403                
404                if(count($toAcceptanceNotifications) > 0){
405                    $newToAcceptanceNotifications = [];
406                    foreach ($toAcceptanceNotifications as $item) {
407                        $newToAcceptanceNotifications[] = [
408                            'company_id' => $newCompanyId,
409                            'email' => $item->email,
410                            'created_by' => $data['created_by']
411                        ];
412                    }
413                    
414                    TblToAcceptanceNotifications::insert((array) $newToAcceptanceNotifications);
415                }
416
417                $workflowApprover = TblWorkflowApprover::where('company_id', $companyId)->get();
418
419                if(count($workflowApprover) > 0){
420                    $newWorkflowApprover = [];
421                    foreach ($workflowApprover as $item) {
422                        $newWorkflowApprover[] = [
423                            'company_id' => $newCompanyId,
424                            'user_id' => $item->user_id,
425                            'created_by' => $data['created_by']
426                        ];
427                    }
428                    
429                    TblWorkflowApprover::insert((array) $newWorkflowApprover);
430                }
431
432                $workflowCustomerTypes = TblWorkflowCustomerTypes::where('company_id', $companyId)->get();
433
434                if(count($workflowCustomerTypes) > 0){
435                    $newWorkflowCustomerTypes = [];
436                    foreach ($workflowCustomerTypes as $item) {
437                        $newWorkflowCustomerTypes[] = [
438                            'company_id' => $newCompanyId,
439                            'customer_type_id' => $item->customer_type_id,
440                            'created_by' => $data['created_by']
441                        ];
442                    }
443                    
444                    TblWorkflowCustomerTypes::insert((array) $newWorkflowCustomerTypes);
445                }
446
447                $workflowProjectTypes = TblWorkflowProjectTypes::where('company_id', $companyId)->get();
448
449                if(count($workflowProjectTypes) > 0){
450                    $newWorkflowProjectTypes = [];
451                    foreach ($workflowProjectTypes as $item) {
452                        $newWorkflowProjectTypes[] = [
453                            'company_id' => $newCompanyId,
454                            'budget_type_id' => $item->budget_type_id,
455                            'created_by' => $data['created_by']
456                        ];
457                    }
458                    
459                    TblWorkflowProjectTypes::insert((array) $newWorkflowProjectTypes);
460                }
461
462                $tradeAlignmentFacility = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
463
464                if(count($tradeAlignmentFacility) > 0){
465                    $newTradeAlignmentFacility = [];
466                    foreach ($tradeAlignmentFacility as $item) {
467                        $newTradeAlignmentFacility[] = [
468                            'company_id' => $newCompanyId,
469                            'budget_type_id' => $item->budget_type_id,
470                            'minimum_budget_amount' => $item->minimum_budget_amount,
471                            'created_by' => $data['created_by']
472                        ];
473                    }
474                    
475                    TblWorkflowProjectTypes::insert((array) $newTradeAlignmentFacility);
476                }
477            }else{
478                $result = TblCompanies::create($data);
479                $newCompanyId = $result->id;
480
481                TblCompanyUsers::create(
482                    array(
483                        'company_id' => $newCompanyId,
484                        'user_id' => $userId,
485                        'can_read' => 1,
486                        'can_write' => 1,
487                        'created_by' => $data['created_by']
488                    )
489                );
490    
491                for ($i = 1; $i < 7; $i++) { 
492                    TblProjectTypes::create(
493                        array(
494                            'company_id' => $result->id,
495                            'project_id' => $i,
496                            'created_by' => $data['created_by']
497                        )
498                    );
499                }
500
501                for ($i = 1; $i < 3; $i++) { 
502                    TblLastFollowUpDate::create(
503                        array(
504                            'company_id' => $result->id,
505                            'row_id' => $i,
506                            'created_by' => $data['created_by']
507                        )
508                    );
509                }
510
511                for ($i = 1; $i < 7; $i++) { 
512                    TblTradeAlignmentSettings::create(
513                        array(
514                            'company_id' => $result->id,
515                            'minimum_budget_amount' => 0,
516                            'created_by' => $data['created_by']
517                        )
518                    );
519                }
520            }
521            
522            TblFinalSummary::create(
523                array(
524                    'company_id' => $newCompanyId,
525                    'created_by' => $data['created_by']
526                )
527            );
528
529            $preLoadedQuestions[1] = "¿Confirma que hemos ofrecido presupuesto de mantenimiento de PCI activo?";
530            $preLoadedQuestions[2] = "¿El pago inicial cubre el coste de materiales y mano de obra?";
531            $preLoadedQuestions[3] = "¿Has solicitado un análisis de riesgo a la administración de Grupo Fire para no correr riesgo de impagos?";
532            $preLoadedQuestions[4] = null;
533            $preLoadedQuestions[5] = null;
534
535            for ($i = 1; $i < 5; $i++) { 
536                TblWorkflowQuestions::create(
537                    array(
538                        'company_id' => $result->id,
539                        'question' => $preLoadedQuestions[$i],
540                        'created_by' => $data['created_by']
541                    )
542                );
543            }
544
545            DB::commit();
546
547            return response(['message' => 'OK', 'data' => $result]);
548
549        } catch (\Exception $e) {
550            /** @disregard P1014 */
551            $e->exceptionCode = 'CREATE_COMPANY_EXCEPTION'; 
552            report($e);
553            return response(['message' => 'KO', 'error' => $e->getMessage()]);
554        }
555    }
556
557    public function list_companies(){
558
559        try {
560
561            $query = "SELECT 
562                        company_id,
563                        name,
564                        fiscal_id,
565                        address,
566                        logo,
567                        filetype,
568                        DATE_FORMAT(created_at, '%b %d, %Y %l:%i%p') 'created_at',
569                        created_by,
570                        DATE_FORMAT(updated_at, '%b %d, %Y %l:%i%p') 'updated_at',
571                        updated_by,
572                        region,
573                        is_send_executive
574                    FROM tbl_companies
575                    ORDER BY region ASC";
576            
577            $result = DB::select($query);
578
579            return response(['message' => 'OK', 'data' => $result]);
580
581        } catch (\Exception $e) {
582            /** @disregard P1014 */
583            $e->exceptionCode = 'LIST_COMPANIES_EXCEPTION'; 
584            report($e);
585            return response(['message' => 'KO', 'error' => $e->getMessage()]);
586        }
587    }
588
589    public function get_company($companyId){
590
591        try {
592
593            $companyId = addslashes($companyId);
594
595            $query = "SELECT 
596                        company_id,
597                        name,
598                        fiscal_id,
599                        address,
600                        logo,
601                        filetype,
602                        filename,
603                        filesize,
604                        filetype,
605                        default_page,
606                        is_send,
607                        limit_send,
608                        is_send_follow_up,
609                        is_send_request,
610                        is_send_g3w,
611                        revenue_per_employee_per_day,
612                        minimum_margin,
613                        general_costs,
614                        hours_per_worker_per_day,
615                        cost_of_hour,
616                        hours_per_worker_per_day_percentage,
617                        convert_to_job_amount_limit,
618                        minimum_order_size,
619                        minimum_order_size_v2,
620                        last_follow_up_date,
621                        limit_reminder_emails,
622                        workflow_budget_size,
623                        is_send_executive,
624                        customer_type_ids,
625                        goal_for_the_year,
626                        process_limit,
627                        last_id,
628                        region,
629                        created_at,
630                        created_by,
631                        updated_at,
632                        updated_by,
633                        kpi_filters
634                    FROM tbl_companies
635                    WHERE company_id = {$companyId}
636                    ORDER BY created_at DESC";
637
638            $result = DB::select($query);
639
640            if($result[0]->customer_type_ids != null){
641                $result[0]->customer_type_ids = array_map('intval', explode(',', $result[0]->customer_type_ids));
642            }
643
644            return response(['message' => 'OK', 'data' => $result]);
645
646        } catch (\Exception $e) {
647            /** @disregard P1014 */
648            $e->exceptionCode = 'GET_COMPANY_EXCEPTION'; 
649            report($e);
650            return response(['message' => 'KO', 'error' => $e->getMessage()]);
651        }
652    }
653
654    public function get_company_users($companyId){
655
656        try {
657
658            $companyId = addslashes($companyId);
659
660            $where = "";
661            if($companyId != 0){
662                $where = " a.company_id = {$companyId} ";
663            }else{
664                $where = " a.company_id IN ({$this->companyId}";
665            }
666
667            $query = "SELECT
668                        a.id,
669                        a.user_id,
670                        a.company_id,
671                        b.name,
672                        b.email,    
673                        a.can_read,
674                        a.can_write
675                    FROM tbl_company_users a
676                    LEFT JOIN tbl_users b
677                        ON a.user_id = b.id
678                    WHERE {$where}
679                    GROUP BY a.user_id
680                    ORDER BY b.name ASC";
681
682            $result = DB::select($query);
683
684            return response(['message' => 'OK', 'data' => $result]);
685
686        } catch (\Exception $e) {
687            /** @disregard P1014 */
688            $e->exceptionCode = 'GET_COMPANY_USERS_EXCEPTION'; 
689            report($e);
690            return response(['message' => 'KO', 'error' => $e->getMessage()]);
691        }
692    }
693
694    public function get_user_companies($userId, $region = null){
695
696        try {
697
698            $userId = addslashes($userId);
699
700            $where = "";
701
702            if($region != null && $region != "All"){
703                $region = urldecode($region);
704                $where = " AND b.region = '{$region}";
705            }
706
707            $query = "SELECT 
708                        a.id,
709                        b.name, 
710                        b.logo, 
711                        b.filename,
712                        b.company_id,
713                        b.region,
714                        a.can_write,
715                        a.can_read
716                    FROM 
717                        tbl_company_users a 
718                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
719                    WHERE 
720                        a.user_id = {$userId}
721                    {$where}
722                    ORDER BY b.region ASC";
723
724            $result = DB::select($query);
725
726            if($result){
727                array_unshift(
728                    $result, 
729                    array(
730                        'id' => 0,
731                        'name' => 'All',
732                        'logo' => null,
733                        'company_id' => 0
734                    )
735                );
736            }
737
738            $query = "SELECT 
739                        DISTINCT
740                        b.region
741                    FROM 
742                        tbl_company_users a 
743                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
744                    WHERE 
745                        a.user_id = {$userId}
746                        AND b.region IS NOT NULL
747                    ORDER BY b.region ASC";
748
749            $regions = DB::select($query);
750
751            if($regions){
752                array_unshift(
753                    $regions, 
754                    array(
755                        'region' => 'All'
756                    )
757                );
758            }
759
760            $query = "SELECT updated_at FROM tbl_quotations ORDER BY updated_at DESC LIMIT 1";
761            $latedDate = DB::select($query);
762
763            return response([
764                'message' => 'OK', 
765                'data' => $result, 
766                'regions' => $regions, 
767                'latestUpdatedDate' => strtotime($latedDate[0]->updated_at) * 1000
768            ]);
769
770        } catch (\Exception $e) {
771            /** @disregard P1014 */
772            $e->exceptionCode = 'GET_USER_COMPANIES_EXCEPTION'; 
773            report($e);
774            return response(['message' => 'KO', 'error' => $e->getMessage()]);
775        }
776    }
777
778    public function update_company_users(Request $request){
779
780        try {
781
782            $data = $request->all();
783            $companyId = $data['company_id'];
784            $userId = $data['user_id'];
785
786            unset($data['company_id']);
787            unset($data['user_id']);
788
789            $result = array();
790
791            $result = TblCompanyUsers::where('company_id', $companyId)->where('user_id', $userId)->update($data);
792
793            return response(['message' => 'OK', 'data' => $result]);
794
795        } catch (\Exception $e) {
796            /** @disregard P1014 */
797            $e->exceptionCode = 'UPDATE_COMPANY_USERS_EXCEPTION'; 
798            report($e);
799            return response(['message' => 'KO', 'error' => $e->getMessage()]);
800        }
801
802    }
803
804    public function update_company_selected(Request $request){
805
806        try {
807
808            $data = $request->all();
809            $userId = $data['user_id'];
810            $id = $data['id'];
811
812            unset($data['user_id']);
813            unset($data['id']);
814
815            TblCompanyUsers::where('user_id', $userId)->update(array('is_selected' => 0));
816            $result = TblCompanyUsers::where('id', $id)->update(array('is_selected' => 1));
817
818            return response(['message' => 'OK', 'data' => $result]);
819
820        } catch (\Exception $e) {
821            /** @disregard P1014 */
822            $e->exceptionCode = 'UPDATE_COMPANY_SELECTED_EXCEPTION'; 
823            report($e);
824            return response(['message' => 'KO', 'error' => $e->getMessage()]);
825        }
826
827    }
828
829    public function delete_company_users(Request $request){
830
831        try {
832
833            $data = $request->all();
834
835            $id = addslashes($data['user_id']);
836
837            $user = TblUsers::where('id', $id)->first();
838
839            $count = TblQuotations::where('company_id', $data['company_id'])->where('commercial', $user->name)->count();
840            $countQ = TblOngoingJobs::where('company_id', $data['company_id'])->where('responsible_for_work', $user->name)->count();
841
842            if($count > 0 || $countQ > 0){
843                $urlOrder = env('URL') . "orders?commercial={$user->name}&company_id=0";
844                $urlJob = env('URL') . "ongoing-jobs?responsible_for_work={$user->name}&company_id=0";
845                $urlOrder = "<a href='{$urlOrder}' target='_blank'>{$count}</a>";
846                $urlJob = "<a href='{$urlJob}' target='_blank'>{$countQ}</a>";
847                return response(['message' => 'user_cannot_be_deleted', 'error' => __('language.user_cannot_be_deleted'), 'total_job' => $urlJob, 'total_order' => $urlOrder]);
848            }
849
850            $result = TblCompanyUsers::where('user_id', $id)->where('company_id', $data['company_id'])->delete();
851
852            return response(['message' => 'OK', 'data' => $result]);
853
854        } catch (\Exception $e) {
855            /** @disregard P1014 */
856            $e->exceptionCode = 'DELETE_COMPANY_USERS_EXCEPTION'; 
857            report($e);
858            return response(['message' => 'KO', 'error' => $e->getMessage()]);
859        }
860
861    }
862
863    public function update_company(Request $request, $companyId){
864
865        try {
866            
867            $data = $request->all();
868            $companyId = addslashes($companyId);
869
870            if(@$data['file'] == ""){
871                unset($data['file']);
872            }
873
874            if(isset($data['customer_type_ids'])){
875                $data['customer_type_ids'] = implode(',', $data['customer_type_ids']);
876            }
877
878            if(isset($data['last_id'])){
879                $data['before_last_id'] = $data['last_id'];
880            }
881            
882            $data['updated_at'] = date('Y-m-d H:i:s');            
883            
884            $result = TblCompanies::where('company_id', $companyId)->update($data);
885
886            return response(['message' => 'OK', 'data' => $result]);
887
888        } catch (\Exception $e) {
889            /** @disregard P1014 */
890            $e->exceptionCode = 'UPDATE_COMPANY_EXCEPTION'; 
891            report($e);
892            return response(['message' => 'KO', 'error' => $e->getMessage()]);
893        }
894    }
895
896    public function update_company_blocked(Request $request){
897
898        try {
899            
900            $data = $request->all();
901
902            TblCompanies::query()->update(array('is_send_executive' => null));
903            TblCompanies::whereIn('company_id', $data['company_ids'])->update(array('is_send_executive' => 1, 'updated_at' => date('Y-m-d H:i:s')));
904
905            return response(['message' => 'OK']);
906
907        } catch (\Exception $e) {
908            /** @disregard P1014 */
909            $e->exceptionCode = 'UPDATE_COMPANY_BLOCKED_EXCEPTION'; 
910            report($e);
911            return response(['message' => 'KO', 'error' => $e->getMessage()]);
912        }
913    }
914
915    public function upload_file(Request $request){
916
917        try {
918            
919            $data = $request->all();
920            $companyId = $data['company_id'];
921            
922            $data['updated_at'] = date('Y-m-d H:i:s');
923
924            if($request->file('file')){
925                $file = $request->file('file');
926
927                $mimetype = $file->getMimeType();
928                
929                if(strpos($mimetype, "image") === false){
930                    return response(['message' => 'invalid_file_type', 'error' => __('language.invalid_file_type')]);
931                }
932
933                $filename = $file->getClientOriginalName();
934                $filesize = $file->getSize();
935
936                if($filesize > 5000000){
937                    return response(['message' => 'limit_exceeded', 'error' => __('language.limit_exceeded')]);
938                }
939
940                $path = $file->getRealPath();
941
942                $logo = file_get_contents($path);
943                $base64 = base64_encode($logo);
944
945                $blob = 'data:' . $mimetype . ';base64,' . $base64;
946
947                $data['logo'] = $blob;
948                $data['filename'] = $filename;
949                $data['filesize'] = $filesize;
950                $data['filetype'] = $mimetype;
951
952                unset($data['file']);
953            }
954
955            $result = TblCompanies::where('company_id', $companyId)->update($data);
956
957            return response(['message' => 'OK', 'data' => $result]);
958
959        } catch (\Exception $e) {
960            /** @disregard P1014 */
961            $e->exceptionCode = 'UPLOAD_FILE_EXCEPTION'; 
962            report($e);
963            return response(['message' => 'KO', 'error' => $e->getMessage()]);
964        }
965    }
966
967    public function delete_company($companyId){
968
969        try {
970            
971            $companyId = addslashes($companyId);
972
973            $count = TblCompanyUsers::where('company_id', $companyId)->count();
974
975            if($count > 0){
976                return response(['message' => 'cannot_be_deleted', 'error' => __('language.cannot_be_deleted')]);
977            }
978
979            $result = TblCompanies::where('company_id', $companyId)->delete();
980            TblEmailConfiguration::where('company_id', $companyId)->delete();
981
982            $query = "DELETE FROM tbl_files WHERE quotation_id IN (SELECT id FROM tbl_quotations WHERE company_id = {$companyId})";
983            DB::select($query);
984
985            TblQuotations::where('company_id', $companyId)->delete();
986            TblProjectTypes::where('company_id', $companyId)->delete();
987
988            return response(['message' => 'OK', 'data' => $result]);
989
990        } catch (\Exception $e) {
991            /** @disregard P1014 */
992            $e->exceptionCode = 'DELETE_COMPANY_EXCEPTION'; 
993            report($e);
994            return response(['message' => 'KO', 'error' => $e->getMessage()]);
995        }
996    }
997
998    public function update_company_users_selected(Request $request){
999
1000        try {
1001
1002            $request->all();
1003            $data = $request->all();
1004            $companyId = $data['company_id'];
1005
1006            TblCompanyUsers::where('company_id', $companyId)->update(array('is_selected' => null));
1007            for ($i = 0; $i < count($data['user_ids']); $i++) { 
1008                TblCompanyUsers::where('company_id', $companyId)->where('user_id', $data['user_ids'][$i])->update(array('is_selected' => 1));
1009            }
1010
1011            return response(['message' => 'OK']);
1012
1013        } catch (\Exception $e) {
1014            /** @disregard P1014 */
1015            $e->exceptionCode = 'UPDATE_COMPANY_USERS_SELECTED_EXCEPTION'; 
1016            report($e);
1017            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1018        }
1019    }
1020
1021    public function create_company_users(Request $request){
1022
1023        try {
1024
1025            $request->all();
1026            $data = $request->all();
1027            $companyId = $data['company_id'];
1028
1029            if($data['user_ids']){
1030                $userIds = implode(",", $data['user_ids']);
1031
1032                $query = "DELETE FROM tbl_company_users WHERE user_id NOT IN ({$userIds}) AND company_id = {$companyId}";
1033                DB::select($query);
1034
1035                $companyUsers = array();
1036
1037                $query = "SELECT user_id FROM tbl_company_users WHERE company_id = {$companyId} AND user_id IN ({$userIds})";
1038                $result = DB::select($query);
1039
1040                $ids = array();
1041
1042                for ($i = 0; $i < count($result); $i++) { 
1043                    array_push($ids, $result[$i]->user_id);
1044                }
1045
1046                for ($i = 0; $i < count($data['user_ids']); $i++) { 
1047                    if(!in_array($data['user_ids'][$i], $ids)){
1048                        array_push(
1049                            $companyUsers,
1050                            array(
1051                                'user_id' => $data['user_ids'][$i],
1052                                'company_id' => $companyId,
1053                                'can_read' => 1,
1054                                'can_write' => 0,
1055                                'created_by' => $data['created_by']
1056                            )
1057                        );
1058                    }
1059                }
1060                
1061                TblCompanyUsers::insert($companyUsers);
1062            }else{
1063                TblCompanyUsers::where('company_id', $companyId)->delete();
1064            }
1065
1066            return response(['message' => 'OK']);
1067
1068        } catch (\Exception $e) {
1069            /** @disregard P1014 */
1070            $e->exceptionCode = 'CREATE_COMPANY_USERS_EXCEPTION'; 
1071            report($e);
1072            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1073        }
1074    }
1075
1076    function get_cc_bcc($id){
1077
1078        try {
1079            
1080            $companyId = addslashes($id);
1081
1082            $result = TblCcBcc::where('company_id', $companyId)->get();
1083
1084            return response(['message' => 'OK', 'data' => $result]);
1085
1086        } catch (\Exception $e) {
1087            /** @disregard P1014 */
1088            $e->exceptionCode = 'GET_CC_BCC_EXCEPTION'; 
1089            report($e);
1090            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1091        }
1092    }
1093
1094    function delete_cc_bcc($id){
1095
1096        try {
1097            
1098            $id = addslashes($id);
1099
1100            TblCcBcc::where('id', $id)->delete();
1101
1102            return response(['message' => 'OK']);
1103
1104        } catch (\Exception $e) {
1105            /** @disregard P1014 */
1106            $e->exceptionCode = 'DELETE_CC_BCC_EXCEPTION'; 
1107            report($e);
1108            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1109        }
1110    }
1111
1112    function update_cc_bcc(Request $request, $id){
1113
1114        try {
1115
1116            $data = $request->all();
1117            $id = addslashes($id);
1118
1119            $x = $this->isEmailValid($data['email']);
1120
1121            if($x){
1122                $result = TblCcBcc::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1123
1124                if($result > 0){
1125                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1126                }else{
1127                    $data['updated_at'] = date('Y-m-d H:i:s');
1128                    TblCcBcc::where('id', $id)->update($data);
1129                }
1130            }else{
1131                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1132            }
1133
1134            return response(['message' => 'OK']);
1135
1136        } catch (\Exception $e) {
1137            /** @disregard P1014 */
1138            $e->exceptionCode = 'UPDATE_CC_BCC_EXCEPTION'; 
1139            report($e);
1140            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1141        }
1142    }
1143
1144    function create_cc_bcc(Request $request){
1145
1146        try {
1147            
1148            $data = $request->all();
1149
1150            $x = $this->isEmailValid($data['email']);
1151
1152            if($x){
1153                $result = TblCcBcc::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1154
1155                if($result > 0){
1156                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1157                }else{
1158                    TblCcBcc::create($data);
1159                }
1160            }else{
1161                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1162            }
1163            
1164            return response(['message' => 'OK']);
1165
1166        } catch (\Exception $e) {
1167            /** @disregard P1014 */
1168            $e->exceptionCode = 'CREATE_CC_BCC_EXCEPTION'; 
1169            report($e);
1170            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1171        }
1172    }
1173
1174    function isEmailValid($email) {
1175        // Regular expression pattern for email validation
1176        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
1177        
1178        // Check if the email matches the pattern
1179        if (preg_match($pattern, $email)) {
1180            return true; // Valid email
1181        } else {
1182            return false; // Invalid email
1183        }
1184    }
1185
1186    function get_blocked_domains($id){
1187
1188        try {
1189            
1190            $companyId = addslashes($id);
1191
1192            $result = array();
1193
1194            if($companyId != 0){
1195                $result = TblBlockedDomains::where('company_id', $companyId)->get();
1196            }else{
1197                $result = TblBlockedDomains::whereIn('company_id', $this->companyIds)->get();
1198            }
1199
1200            return response(['message' => 'OK', 'data' => $result]);
1201
1202        } catch (\Exception $e) {
1203            /** @disregard P1014 */
1204            $e->exceptionCode = 'GET_BLOCKED_DOMAINS_EXCEPTION'; 
1205            report($e);
1206            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1207        }
1208    }
1209
1210    function delete_blocked_domain($id){
1211
1212        try {
1213            
1214            $id = addslashes($id);
1215
1216            TblBlockedDomains::where('id', $id)->delete();
1217
1218            Cache::flush();
1219            return response(['message' => 'OK']);
1220
1221        } catch (\Exception $e) {
1222            /** @disregard P1014 */
1223            $e->exceptionCode = 'DELETE_BLOCKED_DOMAIN_EXCEPTION'; 
1224            report($e);
1225            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1226        }
1227    }
1228
1229    function update_blocked_domain(Request $request, $id){
1230
1231        try {
1232
1233            $data = $request->all();
1234            $id = addslashes($id);
1235
1236            $result = TblBlockedDomains::where('company_id', $data['company_id'])->where('domain', strtolower($data['domain']))->count();
1237
1238            if($result > 0){
1239                return response(['message' => 'KO', 'error' => __('language.domain_exists')]);
1240            }else{
1241                $data['updated_at'] = date('Y-m-d H:i:s');
1242                TblBlockedDomains::where('id', $id)->update($data);
1243            }
1244
1245            Cache::flush();
1246            return response(['message' => 'OK']);
1247
1248        } catch (\Exception $e) {
1249            /** @disregard P1014 */
1250            $e->exceptionCode = 'UPDATE_BLOCKED_DOMAIN_EXCEPTION'; 
1251            report($e);
1252            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1253        }
1254    }
1255
1256    function create_blocked_domain(Request $request){
1257
1258        try {
1259            
1260            $data = $request->all();
1261
1262            $result = TblBlockedDomains::where('company_id', $data['company_id'])->where('domain', strtolower($data['domain']))->count();
1263
1264            if($result > 0){
1265                return response(['message' => 'KO', 'error' => __('language.domain_exists')]);
1266            }else{
1267                TblBlockedDomains::create($data);
1268            }
1269
1270            Cache::flush();
1271            return response(['message' => 'OK']);
1272
1273        } catch (\Exception $e) {
1274            /** @disregard P1014 */
1275            $e->exceptionCode = 'CREATE_BLOCKED_DOMAIN_EXCEPTION'; 
1276            report($e);
1277            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1278        }
1279    }
1280
1281    function list_project_types($companyId){
1282
1283        try {
1284            
1285            $companyId = addslashes($companyId);
1286
1287            $result = TblProjectTypes::where('company_id', $companyId)->orderBy('project_id', 'ASC')->get();
1288
1289            $data = array();
1290
1291            for ($i = 0; $i < count($result); $i++) { 
1292                $data[$result[$i]->project_id]['project_id'] = $result[$i]->project_id;
1293                if($result[$i]->budget_type_id != null){
1294                    $data[$result[$i]->project_id]['budget_types'][] = $result[$i]->budget_type_id;
1295                }
1296                if($result[$i]->customer_type_ids != null){
1297                    $data[$result[$i]->project_id]['customer_types'] = array_map('intval', explode(',', $result[$i]->customer_type_ids));
1298                }
1299                $data[$result[$i]->project_id]['benchmarks'] = array(
1300                    'revenue_per_employee_per_day' => $result[$i]->revenue_per_employee_per_day,
1301                    'minimum_margin' => $result[$i]->minimum_margin,
1302                    'general_costs' => $result[$i]->general_costs,
1303                    'minimum_order_size' => $result[$i]->minimum_order_size,
1304                    'minimum_order_size_v2' => $result[$i]->minimum_order_size_v2,
1305                );
1306            }
1307
1308            return response(['message' => 'OK', 'data' => array_values($data)]);
1309
1310        } catch (\Exception $e) {
1311            /** @disregard P1014 */
1312            $e->exceptionCode = 'LIST_PROJECT_TYPES_EXCEPTION'; 
1313            report($e);
1314            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1315        }
1316
1317    }
1318
1319    function get_project_types($companyId){
1320
1321        try {
1322            
1323            $companyId = addslashes($companyId);
1324
1325            $result = TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', '!=', null)->get();
1326
1327            $query = "
1328                SELECT a.approver_id, u.name AS approver, 'v1' as type
1329                FROM tbl_approvers a
1330                LEFT JOIN tbl_users u ON a.user_id = u.id
1331                WHERE a.company_id = {$companyId}
1332
1333                UNION ALL
1334
1335                SELECT a.approver_id, u.name AS approver, 'v2' as type
1336                FROM tbl_approvers_v2 a
1337                LEFT JOIN tbl_users u ON a.user_id = u.id
1338                WHERE a.company_id = {$companyId}
1339            ";
1340
1341            $approvers = DB::select($query);
1342
1343            $ids = [];
1344            $names = [];
1345
1346            foreach ($approvers as $item) {
1347                $ids[] = $item->approver_id;
1348                $names[] = $item->approver;
1349            }
1350
1351            return response([
1352                'message' => 'OK', 
1353                'data' => $result,     
1354                'approversData' => $approvers,
1355                'approvers' => $ids, 
1356                'approverNames' => $names
1357            ]);
1358
1359        } catch (\Exception $e) {
1360            /** @disregard P1014 */
1361            $e->exceptionCode = 'GET_PROJECT_TYPES_EXCEPTION'; 
1362            report($e);
1363            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1364        }
1365    }
1366
1367    function update_project_types(Request $request){
1368
1369        try {
1370            
1371            $data = $request->all();
1372            $companyId = addslashes($data['company_id']);
1373            $projectId = addslashes($data['project_id']);
1374            unset($data['company_id']);
1375            unset($data['project_id']);
1376
1377            $previousData = TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->first();
1378
1379            $lastBudgetTypeId = end($data['budget_type_id']);
1380            $project = TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', $lastBudgetTypeId)->first();
1381
1382            TblProjectTypes::where('company_id', $companyId)->whereIn('budget_type_id', $data['budget_type_id'])->delete();
1383            TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->delete();
1384
1385            foreach ($data['budget_type_id'] as $budgetTypeId) {
1386                TblProjectTypes::create(
1387                    array(
1388                        'company_id' => $companyId,
1389                        'project_id' => $projectId,
1390                        'customer_type_ids' => $previousData->customer_type_ids,
1391                        'budget_type_id' => $budgetTypeId,
1392                        'revenue_per_employee_per_day' => $previousData->revenue_per_employee_per_day,
1393                        'minimum_margin' => $previousData->minimum_margin,
1394                        'general_costs' => $previousData->general_costs,
1395                        'minimum_order_size' => $previousData->minimum_order_size,
1396                        'minimum_order_size_v2' => $previousData->minimum_order_size_v2,
1397                        'created_by' => $data['created_by']
1398                    )
1399                );
1400            }
1401
1402            if($project != null){
1403                if($project->budget_type_id != null){
1404                    TblProjectTypes::create(
1405                        array(
1406                            'company_id' => $companyId,
1407                            'project_id' => $project->project_id,
1408                            'budget_type_id' => null,
1409                            'customer_type_ids' => $project->customer_type_ids,
1410                            'revenue_per_employee_per_day' => $project->revenue_per_employee_per_day,
1411                            'minimum_margin' => $project->minimum_margin,
1412                            'general_costs' => $project->general_costs,
1413                            'minimum_order_size' => $project->minimum_order_size,
1414                            'minimum_order_size_v2' => $project->minimum_order_size_v2,
1415                            'created_by' => $data['created_by']
1416                        )
1417                    );
1418                }
1419            }
1420
1421            return $this->list_project_types($companyId);
1422
1423        } catch (\Exception $e) {
1424            /** @disregard P1014 */
1425            $e->exceptionCode = 'CREATE_PROJECT_TYPES_EXCEPTION'; 
1426            report($e);
1427            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1428        }
1429
1430    }
1431
1432    function update_project_types_benchmarks(Request $request){
1433
1434        try {
1435            
1436            $data = $request->all();
1437            $companyId = addslashes($data['company_id']);
1438            $projectId = addslashes($data['project_id']);
1439
1440            unset($data['company_id']);
1441            unset($data['project_id']);
1442
1443            if(isset($data['customer_type_ids'])){
1444                $data['customer_type_ids'] = implode(',', $data['customer_type_ids']);
1445            }
1446
1447            TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->update($data);
1448
1449            return $this->list_project_types($companyId);
1450
1451        } catch (\Exception $e) {
1452            /** @disregard P1014 */
1453            $e->exceptionCode = 'UPDATE_PROJECT_TYPES_BENCHMARKS_EXCEPTION'; 
1454            report($e);
1455            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1456        }
1457
1458    }
1459
1460    function delete_project_types(Request $request){
1461
1462        try {
1463            
1464            $data = $request->all();
1465            $companyId = addslashes($data['company_id']);
1466            $projectId = addslashes($data['project_id']);
1467            unset($data['company_id']);
1468            unset($data['project_id']);
1469
1470            $count = TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->count();
1471
1472            if($count > 1){
1473                TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', $data['budget_type_id'])->delete();
1474            }else{
1475                TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->update(array('budget_type_id' => null));
1476            }
1477
1478            return $this->list_project_types($companyId);
1479
1480        } catch (\Exception $e) {
1481            /** @disregard P1014 */
1482            $e->exceptionCode = 'DELETE_PROJECT_TYPES_EXCEPTION'; 
1483            report($e);
1484            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1485        }
1486
1487    }
1488
1489    function list_workflow_project_types($companyId){
1490
1491        try {
1492            
1493            $companyId = addslashes($companyId);
1494
1495            $result = TblWorkflowProjectTypes::where('company_id', $companyId)->get();
1496
1497            return response(['message' => 'OK', 'data' => $result]);
1498
1499        } catch (\Exception $e) {
1500            /** @disregard P1014 */
1501            $e->exceptionCode = 'LIST_WORKFLOW_PROJECT_TYPES_EXCEPTION'; 
1502            report($e);
1503            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1504        }
1505
1506    }
1507
1508    function update_workflow_project_types(Request $request){
1509
1510        try {
1511            
1512            $data = $request->all();
1513
1514            TblWorkflowProjectTypes::where('company_id', $data['company_id'])->delete();
1515            
1516            for ($i = 0; $i < count($data['budget_type_id']); $i++) { 
1517                TblWorkflowProjectTypes::create(
1518                    array(
1519                        'company_id' => $data['company_id'],
1520                        'budget_type_id' => $data['budget_type_id'][$i],
1521                        'created_by' => $data['created_by']
1522                    )
1523                );
1524            }
1525
1526            return $this->list_workflow_project_types($data['company_id']);
1527
1528        } catch (\Exception $e) {
1529            /** @disregard P1014 */
1530            $e->exceptionCode = 'UPDATE_WORKFLOW_PROJECT_TYPES_EXCEPTION'; 
1531            report($e);
1532            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1533        }
1534
1535    }
1536
1537    function delete_workflow_project_types(Request $request){
1538
1539        try {
1540
1541            $data = $request->all();
1542            
1543            $companyId = addslashes($data['company_id']);
1544            $budgetTypeId = addslashes($data['budget_type_id']);
1545
1546            TblWorkflowProjectTypes::where('budget_type_id', $budgetTypeId)->where('company_id', $companyId)->delete();
1547
1548            return $this->list_workflow_project_types($companyId);
1549
1550        } catch (\Exception $e) {
1551            /** @disregard P1014 */
1552            $e->exceptionCode = 'DELETE_WORKFLOW_PROJECT_TYPES_EXCEPTION'; 
1553            report($e);
1554            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1555        }
1556
1557    }
1558
1559    function list_workflow_customer_types($companyId){
1560
1561        try {
1562            
1563            $companyId = addslashes($companyId);
1564
1565            $result = TblWorkflowCustomerTypes::where('company_id', $companyId)->get();
1566
1567            return response(['message' => 'OK', 'data' => $result]);
1568
1569        } catch (\Exception $e) {
1570            /** @disregard P1014 */
1571            $e->exceptionCode = 'LIST_WORKFLOW_CUSTOMER_TYPES_EXCEPTION'; 
1572            report($e);
1573            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1574        }
1575
1576    }
1577
1578    function update_workflow_customer_types(Request $request){
1579
1580        try {
1581            
1582            $data = $request->all();
1583
1584            TblWorkflowCustomerTypes::where('company_id', $data['company_id'])->delete();
1585            
1586            for ($i = 0; $i < count($data['customer_type_id']); $i++) { 
1587                TblWorkflowCustomerTypes::create(
1588                    array(
1589                        'company_id' => $data['company_id'],
1590                        'customer_type_id' => $data['customer_type_id'][$i],
1591                        'created_by' => $data['created_by']
1592                    )
1593                );
1594            }
1595
1596            return $this->list_workflow_project_types($data['company_id']);
1597
1598        } catch (\Exception $e) {
1599            /** @disregard P1014 */
1600            $e->exceptionCode = 'UPDATE_WORKFLOW_CUSTOMER_TYPES_EXCEPTION'; 
1601            report($e);
1602            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1603        }
1604
1605    }
1606
1607    function delete_workflow_customer_types(Request $request){
1608
1609        try {
1610
1611            $data = $request->all();
1612            
1613            $companyId = addslashes($data['company_id']);
1614            $customerTypeId = addslashes($data['customer_type_id']);
1615
1616            TblWorkflowCustomerTypes::where('customer_type_id', $customerTypeId)->where('company_id', $companyId)->delete();
1617
1618            return $this->list_workflow_customer_types($companyId);
1619
1620        } catch (\Exception $e) {
1621            /** @disregard P1014 */
1622            $e->exceptionCode = 'DELETE_WORKFLOW_CUSTOMER_TYPES_EXCEPTION'; 
1623            report($e);
1624            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1625        }
1626
1627    }
1628
1629    function list_workflow_questions($companyId){
1630
1631        try {
1632
1633            $companyId = addslashes($companyId);
1634
1635            $result = TblWorkflowQuestions::where('company_id', $companyId)->get();
1636
1637            return response(['message' => 'OK', 'data' => $result]);
1638
1639        } catch (\Exception $e) {
1640            /** @disregard P1014 */
1641            $e->exceptionCode = 'LIST_WORKFLOW_QUESTIONS_EXCEPTION'; 
1642            report($e);
1643            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1644        }
1645
1646    }
1647
1648    function update_workflow_questions(Request $request, $questionId){
1649
1650        try {
1651            
1652            $data = $request->all();
1653            $questionId = addslashes($questionId);
1654            $companyId = addslashes($data['company_id']);
1655            unset($data['company_id']);
1656
1657            $data['updated_at'] = date('Y-m-d H:i:s');
1658            TblWorkflowQuestions::where('question_id', $questionId)->update($data);
1659
1660            return $this->list_workflow_questions($companyId);
1661
1662        } catch (\Exception $e) {   
1663            /** @disregard P1014 */
1664            $e->exceptionCode = 'UPDATE_WORKFLOW_QUESTIONS_EXCEPTION'; 
1665            report($e);
1666            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1667        }
1668
1669    }
1670
1671    function get_company_executive(){
1672
1673        try {
1674            
1675            $result = TblCompanies::where('is_send_executive', 1)->get();
1676
1677            return response(['message' => 'OK', 'data' => $result]);
1678
1679        } catch (\Exception $e) {   
1680            /** @disregard P1014 */
1681            $e->exceptionCode = 'GET_COMPANY_EXECUTIVE_EXCEPTION'; 
1682            report($e);
1683            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1684        }
1685
1686    }
1687
1688    function get_all_details($companyId){
1689
1690        try {
1691
1692            $companyId = addslashes($companyId);
1693
1694            $getCompany = $this->get_company($companyId);
1695            $listWorkflowQuestions = $this->list_workflow_questions($companyId);
1696            $listWorkflowCustomerTypes = $this->list_workflow_customer_types($companyId);
1697            $listWorkflowProjectTypes = $this->list_workflow_project_types($companyId);
1698            $getProjectTypes = $this->get_project_types($companyId);
1699            $getCompanyUsers = $this->get_company_users($companyId);
1700            $getBlockedDomains = TblBlockedDomains::where('company_id', $companyId)->get();
1701
1702            return response([
1703                'message' => 'OK', 
1704                'getCompany' => $getCompany->original['data'],
1705                'approvers' => $getProjectTypes->original['approvers'],
1706                'approverNames' => $getProjectTypes->original['approverNames'],
1707                'listWorkflowQuestions' => $listWorkflowQuestions->original['data'],
1708                'listWorkflowCustomerTypes' => $listWorkflowCustomerTypes->original['data'],
1709                'listWorkflowProjectTypes' => $listWorkflowProjectTypes->original['data'],
1710                'getProjectTypes' => $getProjectTypes->original['data'],
1711                'getBlockedDomains' => $getBlockedDomains,
1712                'getCompanyUsers' => $getCompanyUsers->original['data'],
1713            ]);
1714
1715        } catch (\Exception $e) {   
1716            /** @disregard P1014 */
1717            $e->exceptionCode = 'GET_ALL_DETAILS_EXCEPTION'; 
1718            report($e);
1719            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1720        }
1721    }
1722
1723    function list_all_companies(){
1724
1725        try {
1726            
1727            $result = TblCompanies::whereIn('company_id', $this->companyIds)->get();
1728
1729            return response([
1730                'message' => 'OK', 
1731                'data' => $result
1732            ]);
1733
1734        } catch (\Exception $e) {   
1735            /** @disregard P1014 */
1736            $e->exceptionCode = 'LIST_ALL_COMPANIES_EXCEPTION'; 
1737            report($e);
1738            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1739        }
1740
1741    }
1742
1743    function update_company_permission(Request $request, $userId){
1744
1745        try {
1746            
1747            $data = $request->all();
1748            $userId = addslashes($userId);
1749
1750            if(isset($data['read_only'])){
1751                if($data['read_only'] == false){
1752                    TblCompanyUsers::where('user_id', $userId)->update(
1753                        array(
1754                            'can_read' => 1,
1755                            'can_write' => 0,
1756                            'updated_at' => date('Y-m-d H:i:s'),
1757                            'updated_by' => $data['updated_by']
1758                        )
1759                    );
1760                }else{
1761                    TblCompanyUsers::where('user_id', $userId)->update(
1762                        array(
1763                            'can_read' => 1,
1764                            'can_write' => 1,
1765                            'updated_at' => date('Y-m-d H:i:s'),
1766                            'updated_by' => $data['updated_by']
1767                        )
1768                    );
1769                }
1770            }
1771
1772            return response([
1773                'message' => 'OK'
1774            ]);
1775
1776        } catch (\Exception $e) {   
1777            /** @disregard P1014 */
1778            $e->exceptionCode = 'UPDATE_COMPANY_PERMISSION_EXCEPTION'; 
1779            report($e);
1780            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1781        }
1782
1783    }
1784
1785    function list_facility_settings(){
1786
1787        try {
1788            
1789            $result = TblFacilitySettings::get();
1790
1791            for ($i = 0; $i < count($result); $i++) {       
1792                if($result[$i]->budget_type_id != null){
1793                    $result[$i]->budget_type_id = array_map('intval', explode(',', $result[$i]->budget_type_id));    
1794                }                
1795            }
1796
1797            return response([
1798                'message' => 'OK',
1799                'data' => $result
1800            ]);
1801
1802        } catch (\Exception $e) {   
1803            /** @disregard P1014 */
1804            $e->exceptionCode = 'LIST_FACILITY_SETTINGS_EXCEPTION'; 
1805            report($e);
1806            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1807        }
1808
1809    }
1810
1811    function update_facility_settings(Request $request, $id)
1812    {
1813        try {
1814
1815            $data = $request->all();
1816            $id = addslashes($id); 
1817            $data['updated_at'] = date('Y-m-d H:i:s');
1818
1819            if (isset($data['budget_type_id']) && is_array($data['budget_type_id'])) {
1820                $incomingIds = $data['budget_type_id'];
1821
1822                $rows = TblFacilitySettings::all();
1823
1824                foreach ($rows as $row) {
1825                    $currentIds = $row->budget_type_id ? explode(',', $row->budget_type_id) : [];
1826
1827                    $newIds = array_diff($currentIds, $incomingIds);
1828
1829                    if (!empty($newIds)) {
1830                        TblFacilitySettings::where('id', $row->id)->update([
1831                            'budget_type_id' => implode(',', $newIds),
1832                            'updated_at' => date('Y-m-d H:i:s')
1833                        ]);
1834                    } else {
1835                        TblFacilitySettings::where('id', $row->id)->update([
1836                            'budget_type_id' => '',
1837                            'updated_at' => date('Y-m-d H:i:s')
1838                        ]);
1839                    }
1840                }
1841
1842                $data['budget_type_id'] = implode(',', $incomingIds);
1843
1844                $exists = TblFacilitySettings::where('id', $id)->exists();
1845                if ($exists) {
1846                    TblFacilitySettings::where('id', $id)->update($data);
1847                } else {
1848                    TblFacilitySettings::create(array_merge($data, ['id' => $id]));
1849                }
1850            }elseif(isset($data['minimum_budget_amount'])){
1851                TblFacilitySettings::where('id', $id)->update($data);
1852            }
1853
1854            $result = $this->list_facility_settings();
1855
1856            return response([
1857                'message' => 'OK',
1858                'data' => $result->original['data']
1859            ]);
1860
1861        } catch (\Exception $e) {   
1862            /** @disregard P1014 */
1863            $e->exceptionCode = 'UPDATE_FACILITY_SETTINGS_EXCEPTION'; 
1864            report($e);
1865            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1866        }
1867    }
1868
1869    function list_trade_alignment_settings($companyId){
1870
1871        try {
1872            
1873            $companyId = addslashes($companyId);
1874            $result = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
1875
1876            for ($i = 0; $i < count($result); $i++) {       
1877                if($result[$i]->budget_type_id != null){
1878                    $result[$i]->budget_type_id = array_map('intval', explode(',', $result[$i]->budget_type_id));    
1879                }                
1880            }
1881
1882            return response([
1883                'message' => 'OK',
1884                'data' => $result
1885            ]);
1886
1887        } catch (\Exception $e) {   
1888            /** @disregard P1014 */
1889            $e->exceptionCode = 'LIST_TRADE_ALIGNMENT_SETTINGS_EXCEPTION'; 
1890            report($e);
1891            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1892        }
1893
1894    }
1895
1896    function update_trade_alignment_settings(Request $request, $id)
1897    {
1898        try {
1899
1900            $data = $request->all();
1901            $id = addslashes($id); 
1902            $data['updated_at'] = date('Y-m-d H:i:s');
1903            $companyId = addslashes($data['company_id']);
1904
1905            if (isset($data['budget_type_id']) && is_array($data['budget_type_id'])) {
1906                $incomingIds = $data['budget_type_id'];
1907
1908                $rows = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
1909
1910                foreach ($rows as $row) {
1911                    $currentIds = $row->budget_type_id ? explode(',', $row->budget_type_id) : [];
1912
1913                    $newIds = array_diff($currentIds, $incomingIds);
1914
1915                    if (!empty($newIds)) {
1916                        TblTradeAlignmentSettings::where('id', $row->id)->update([
1917                            'budget_type_id' => implode(',', $newIds),
1918                            'updated_at' => date('Y-m-d H:i:s')
1919                        ]);
1920                    } else {
1921                        TblTradeAlignmentSettings::where('id', $row->id)->update([
1922                            'budget_type_id' => '',
1923                            'updated_at' => date('Y-m-d H:i:s')
1924                        ]);
1925                    }
1926                }
1927
1928                $data['budget_type_id'] = implode(',', $incomingIds);
1929
1930                $exists = TblTradeAlignmentSettings::where('id', $id)->exists();
1931                if ($exists) {
1932                    TblTradeAlignmentSettings::where('id', $id)->update($data);
1933                } else {
1934                    TblTradeAlignmentSettings::create(array_merge($data, ['id' => $id]));
1935                }
1936            }elseif(isset($data['minimum_budget_amount'])){
1937                TblTradeAlignmentSettings::where('id', $id)->update($data);
1938            }
1939
1940            $result = $this->list_trade_alignment_settings($companyId);
1941
1942            return response([
1943                'message' => 'OK',
1944                'data' => $result->original['data']
1945            ]);
1946
1947        } catch (\Exception $e) {   
1948            /** @disregard P1014 */
1949            $e->exceptionCode = 'UPDATE_TRADE_ALIGNMENT_SETTINGS_EXCEPTION'; 
1950            report($e);
1951            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1952        }
1953    }
1954
1955}