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