Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 926
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 / 926
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 / 325
0.00% covered (danger)
0.00%
0 / 1
1980
 list_companies
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_company
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 get_company_users
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 get_user_companies
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
42
 update_company_users
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 update_company_selected
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 delete_company_users
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 update_company
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 update_company_blocked
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 upload_file
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
 delete_company
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 update_company_users_selected
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 create_company_users
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
42
 get_cc_bcc
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc
0.00% covered (danger)
0.00%
0 / 11
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 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 delete_blocked_domain
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 update_blocked_domain
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 create_blocked_domain
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 list_project_types
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 get_project_types
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
12
 update_project_types
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
30
 update_project_types_benchmarks
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 delete_project_types
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 list_workflow_project_types
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_project_types
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 delete_workflow_project_types
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 list_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 delete_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 list_workflow_questions
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_questions
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 get_company_executive
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_all_details
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
6
 list_all_companies
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_company_permission
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
20
 list_facility_settings
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 update_facility_settings
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
90
 list_trade_alignment_settings
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 update_trade_alignment_settings
0.00% covered (danger)
0.00%
0 / 33
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            return response(['message' => 'KO', 'error' => $e->getMessage()]);
551        }
552    }
553
554    public function list_companies(){
555
556        try {
557
558            $query = "SELECT 
559                        company_id,
560                        name,
561                        fiscal_id,
562                        address,
563                        logo,
564                        filetype,
565                        DATE_FORMAT(created_at, '%b %d, %Y %l:%i%p') 'created_at',
566                        created_by,
567                        DATE_FORMAT(updated_at, '%b %d, %Y %l:%i%p') 'updated_at',
568                        updated_by,
569                        region,
570                        is_send_executive
571                    FROM tbl_companies
572                    ORDER BY region ASC";
573            
574            $result = DB::select($query);
575
576            return response(['message' => 'OK', 'data' => $result]);
577
578        } catch (\Exception $e) {
579            return response(['message' => 'KO', 'error' => $e->getMessage()]);
580        }
581    }
582
583    public function get_company($companyId){
584
585        try {
586
587            $companyId = addslashes($companyId);
588
589            $query = "SELECT 
590                        company_id,
591                        name,
592                        fiscal_id,
593                        address,
594                        logo,
595                        filetype,
596                        filename,
597                        filesize,
598                        filetype,
599                        default_page,
600                        is_send,
601                        limit_send,
602                        is_send_follow_up,
603                        is_send_request,
604                        is_send_g3w,
605                        revenue_per_employee_per_day,
606                        minimum_margin,
607                        general_costs,
608                        hours_per_worker_per_day,
609                        cost_of_hour,
610                        hours_per_worker_per_day_percentage,
611                        convert_to_job_amount_limit,
612                        minimum_order_size,
613                        minimum_order_size_v2,
614                        last_follow_up_date,
615                        limit_reminder_emails,
616                        workflow_budget_size,
617                        is_send_executive,
618                        customer_type_ids,
619                        goal_for_the_year,
620                        process_limit,
621                        last_id,
622                        region,
623                        created_at,
624                        created_by,
625                        updated_at,
626                        updated_by,
627                        kpi_filters
628                    FROM tbl_companies
629                    WHERE company_id = {$companyId}
630                    ORDER BY created_at DESC";
631
632            $result = DB::select($query);
633
634            if($result[0]->customer_type_ids != null){
635                $result[0]->customer_type_ids = array_map('intval', explode(',', $result[0]->customer_type_ids));
636            }
637
638            return response(['message' => 'OK', 'data' => $result]);
639
640        } catch (\Exception $e) {
641            return response(['message' => 'KO', 'error' => $e->getMessage()]);
642        }
643    }
644
645    public function get_company_users($companyId){
646
647        try {
648
649            $companyId = addslashes($companyId);
650
651            $where = "";
652            if($companyId != 0){
653                $where = " a.company_id = {$companyId} ";
654            }else{
655                $where = " a.company_id IN ({$this->companyId}";
656            }
657
658            $query = "SELECT
659                        a.id,
660                        a.user_id,
661                        a.company_id,
662                        b.name,
663                        b.email,    
664                        a.can_read,
665                        a.can_write
666                    FROM tbl_company_users a
667                    LEFT JOIN tbl_users b
668                        ON a.user_id = b.id
669                    WHERE {$where}
670                    GROUP BY a.user_id
671                    ORDER BY b.name ASC";
672
673            $result = DB::select($query);
674
675            return response(['message' => 'OK', 'data' => $result]);
676
677        } catch (\Exception $e) {
678            return response(['message' => 'KO', 'error' => $e->getMessage()]);
679        }
680    }
681
682    public function get_user_companies($userId, $region = null){
683
684        try {
685
686            $userId = addslashes($userId);
687
688            $where = "";
689
690            if($region != null && $region != "All"){
691                $region = urldecode($region);
692                $where = " AND b.region = '{$region}";
693            }
694
695            $query = "SELECT 
696                        a.id,
697                        b.name, 
698                        b.logo, 
699                        b.filename,
700                        b.company_id,
701                        b.region,
702                        a.can_write,
703                        a.can_read
704                    FROM 
705                        tbl_company_users a 
706                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
707                    WHERE 
708                        a.user_id = {$userId}
709                    {$where}
710                    ORDER BY b.region ASC";
711
712            $result = DB::select($query);
713
714            if($result){
715                array_unshift(
716                    $result, 
717                    array(
718                        'id' => 0,
719                        'name' => 'All',
720                        'logo' => null,
721                        'company_id' => 0
722                    )
723                );
724            }
725
726            $query = "SELECT 
727                        DISTINCT
728                        b.region
729                    FROM 
730                        tbl_company_users a 
731                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
732                    WHERE 
733                        a.user_id = {$userId}
734                        AND b.region IS NOT NULL
735                    ORDER BY b.region ASC";
736
737            $regions = DB::select($query);
738
739            if($regions){
740                array_unshift(
741                    $regions, 
742                    array(
743                        'region' => 'All'
744                    )
745                );
746            }
747
748            $query = "SELECT updated_at FROM tbl_quotations ORDER BY updated_at DESC LIMIT 1";
749            $latedDate = DB::select($query);
750
751            return response([
752                'message' => 'OK', 
753                'data' => $result, 
754                'regions' => $regions, 
755                'latestUpdatedDate' => strtotime($latedDate[0]->updated_at) * 1000
756            ]);
757
758        } catch (\Exception $e) {
759            return response(['message' => 'KO', 'error' => $e->getMessage()]);
760        }
761    }
762
763    public function update_company_users(Request $request){
764
765        try {
766
767            $data = $request->all();
768            $companyId = $data['company_id'];
769            $userId = $data['user_id'];
770
771            unset($data['company_id']);
772            unset($data['user_id']);
773
774            $result = array();
775
776            $result = TblCompanyUsers::where('company_id', $companyId)->where('user_id', $userId)->update($data);
777
778            return response(['message' => 'OK', 'data' => $result]);
779
780        } catch (\Exception $e) {
781            return response(['message' => 'KO', 'error' => $e->getMessage()]);
782        }
783
784    }
785
786    public function update_company_selected(Request $request){
787
788        try {
789
790            $data = $request->all();
791            $userId = $data['user_id'];
792            $id = $data['id'];
793
794            unset($data['user_id']);
795            unset($data['id']);
796
797            TblCompanyUsers::where('user_id', $userId)->update(array('is_selected' => 0));
798            $result = TblCompanyUsers::where('id', $id)->update(array('is_selected' => 1));
799
800            return response(['message' => 'OK', 'data' => $result]);
801
802        } catch (\Exception $e) {
803            return response(['message' => 'KO', 'error' => $e->getMessage()]);
804        }
805
806    }
807
808    public function delete_company_users(Request $request){
809
810        try {
811
812            $data = $request->all();
813
814            $id = addslashes($data['user_id']);
815
816            $user = TblUsers::where('id', $id)->first();
817
818            $count = TblQuotations::where('company_id', $data['company_id'])->where('commercial', $user->name)->count();
819            $countQ = TblOngoingJobs::where('company_id', $data['company_id'])->where('responsible_for_work', $user->name)->count();
820
821            if($count > 0 || $countQ > 0){
822                $urlOrder = env('URL') . "orders?commercial={$user->name}&company_id=0";
823                $urlJob = env('URL') . "ongoing-jobs?responsible_for_work={$user->name}&company_id=0";
824                $urlOrder = "<a href='{$urlOrder}' target='_blank'>{$count}</a>";
825                $urlJob = "<a href='{$urlJob}' target='_blank'>{$countQ}</a>";
826                return response(['message' => 'user_cannot_be_deleted', 'error' => __('language.user_cannot_be_deleted'), 'total_job' => $urlJob, 'total_order' => $urlOrder]);
827            }
828
829            $result = TblCompanyUsers::where('user_id', $id)->where('company_id', $data['company_id'])->delete();
830
831            return response(['message' => 'OK', 'data' => $result]);
832
833        } catch (\Exception $e) {
834            return response(['message' => 'KO', 'error' => $e->getMessage()]);
835        }
836
837    }
838
839    public function update_company(Request $request, $companyId){
840
841        try {
842            
843            $data = $request->all();
844            $companyId = addslashes($companyId);
845
846            if(@$data['file'] == ""){
847                unset($data['file']);
848            }
849
850            if(isset($data['customer_type_ids'])){
851                $data['customer_type_ids'] = implode(',', $data['customer_type_ids']);
852            }
853
854            if(isset($data['last_id'])){
855                $data['before_last_id'] = $data['last_id'];
856            }
857            
858            $data['updated_at'] = date('Y-m-d H:i:s');            
859            
860            $result = TblCompanies::where('company_id', $companyId)->update($data);
861
862            return response(['message' => 'OK', 'data' => $result]);
863
864        } catch (\Exception $e) {
865            return response(['message' => 'KO', 'error' => $e->getMessage()]);
866        }
867    }
868
869    public function update_company_blocked(Request $request){
870
871        try {
872            
873            $data = $request->all();
874
875            TblCompanies::query()->update(array('is_send_executive' => null));
876            TblCompanies::whereIn('company_id', $data['company_ids'])->update(array('is_send_executive' => 1, 'updated_at' => date('Y-m-d H:i:s')));
877
878            return response(['message' => 'OK']);
879
880        } catch (\Exception $e) {
881            return response(['message' => 'KO', 'error' => $e->getMessage()]);
882        }
883    }
884
885    public function upload_file(Request $request){
886
887        try {
888            
889            $data = $request->all();
890            $companyId = $data['company_id'];
891            
892            $data['updated_at'] = date('Y-m-d H:i:s');
893
894            if($request->file('file')){
895                $file = $request->file('file');
896
897                $mimetype = $file->getMimeType();
898                
899                if(strpos($mimetype, "image") === false){
900                    return response(['message' => 'invalid_file_type', 'error' => __('language.invalid_file_type')]);
901                }
902
903                $filename = $file->getClientOriginalName();
904                $filesize = $file->getSize();
905
906                if($filesize > 5000000){
907                    return response(['message' => 'limit_exceeded', 'error' => __('language.limit_exceeded')]);
908                }
909
910                $path = $file->getRealPath();
911
912                $logo = file_get_contents($path);
913                $base64 = base64_encode($logo);
914
915                $blob = 'data:' . $mimetype . ';base64,' . $base64;
916
917                $data['logo'] = $blob;
918                $data['filename'] = $filename;
919                $data['filesize'] = $filesize;
920                $data['filetype'] = $mimetype;
921
922                unset($data['file']);
923            }
924
925            $result = TblCompanies::where('company_id', $companyId)->update($data);
926
927            return response(['message' => 'OK', 'data' => $result]);
928
929        } catch (\Exception $e) {
930            return response(['message' => 'KO', 'error' => $e->getMessage()]);
931        }
932    }
933
934    public function delete_company($companyId){
935
936        try {
937            
938            $companyId = addslashes($companyId);
939
940            $count = TblCompanyUsers::where('company_id', $companyId)->count();
941
942            if($count > 0){
943                return response(['message' => 'cannot_be_deleted', 'error' => __('language.cannot_be_deleted')]);
944            }
945
946            $result = TblCompanies::where('company_id', $companyId)->delete();
947            TblEmailConfiguration::where('company_id', $companyId)->delete();
948
949            $query = "DELETE FROM tbl_files WHERE quotation_id IN (SELECT id FROM tbl_quotations WHERE company_id = {$companyId})";
950            DB::select($query);
951
952            TblQuotations::where('company_id', $companyId)->delete();
953            TblProjectTypes::where('company_id', $companyId)->delete();
954
955            return response(['message' => 'OK', 'data' => $result]);
956
957        } catch (\Exception $e) {
958            return response(['message' => 'KO', 'error' => $e->getMessage()]);
959        }
960    }
961
962    public function update_company_users_selected(Request $request){
963
964        try {
965
966            $request->all();
967            $data = $request->all();
968            $companyId = $data['company_id'];
969
970            TblCompanyUsers::where('company_id', $companyId)->update(array('is_selected' => null));
971            for ($i = 0; $i < count($data['user_ids']); $i++) { 
972                TblCompanyUsers::where('company_id', $companyId)->where('user_id', $data['user_ids'][$i])->update(array('is_selected' => 1));
973            }
974
975            return response(['message' => 'OK']);
976
977        } catch (\Exception $e) {
978            return response(['message' => 'KO', 'error' => $e->getMessage()]);
979        }
980    }
981
982    public function create_company_users(Request $request){
983
984        try {
985
986            $request->all();
987            $data = $request->all();
988            $companyId = $data['company_id'];
989
990            if($data['user_ids']){
991                $userIds = implode(",", $data['user_ids']);
992
993                $query = "DELETE FROM tbl_company_users WHERE user_id NOT IN ({$userIds}) AND company_id = {$companyId}";
994                DB::select($query);
995
996                $companyUsers = array();
997
998                $query = "SELECT user_id FROM tbl_company_users WHERE company_id = {$companyId} AND user_id IN ({$userIds})";
999                $result = DB::select($query);
1000
1001                $ids = array();
1002
1003                for ($i = 0; $i < count($result); $i++) { 
1004                    array_push($ids, $result[$i]->user_id);
1005                }
1006
1007                for ($i = 0; $i < count($data['user_ids']); $i++) { 
1008                    if(!in_array($data['user_ids'][$i], $ids)){
1009                        array_push(
1010                            $companyUsers,
1011                            array(
1012                                'user_id' => $data['user_ids'][$i],
1013                                'company_id' => $companyId,
1014                                'can_read' => 1,
1015                                'can_write' => 0,
1016                                'created_by' => $data['created_by']
1017                            )
1018                        );
1019                    }
1020                }
1021                
1022                TblCompanyUsers::insert($companyUsers);
1023            }else{
1024                TblCompanyUsers::where('company_id', $companyId)->delete();
1025            }
1026
1027            return response(['message' => 'OK']);
1028
1029        } catch (\Exception $e) {
1030            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1031        }
1032    }
1033
1034    function get_cc_bcc($id){
1035
1036        try {
1037            
1038            $companyId = addslashes($id);
1039
1040            $result = TblCcBcc::where('company_id', $companyId)->get();
1041
1042            return response(['message' => 'OK', 'data' => $result]);
1043
1044        } catch (\Exception $e) {
1045            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1046        }
1047    }
1048
1049    function delete_cc_bcc($id){
1050
1051        try {
1052            
1053            $id = addslashes($id);
1054
1055            TblCcBcc::where('id', $id)->delete();
1056
1057            return response(['message' => 'OK']);
1058
1059        } catch (\Exception $e) {
1060            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1061        }
1062    }
1063
1064    function update_cc_bcc(Request $request, $id){
1065
1066        try {
1067
1068            $data = $request->all();
1069            $id = addslashes($id);
1070
1071            $x = $this->isEmailValid($data['email']);
1072
1073            if($x){
1074                $result = TblCcBcc::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1075
1076                if($result > 0){
1077                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1078                }else{
1079                    $data['updated_at'] = date('Y-m-d H:i:s');
1080                    TblCcBcc::where('id', $id)->update($data);
1081                }
1082            }else{
1083                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1084            }
1085
1086            return response(['message' => 'OK']);
1087
1088        } catch (\Exception $e) {
1089            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1090        }
1091    }
1092
1093    function create_cc_bcc(Request $request){
1094
1095        try {
1096            
1097            $data = $request->all();
1098
1099            $x = $this->isEmailValid($data['email']);
1100
1101            if($x){
1102                $result = TblCcBcc::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1103
1104                if($result > 0){
1105                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1106                }else{
1107                    TblCcBcc::create($data);
1108                }
1109            }else{
1110                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1111            }
1112            
1113            return response(['message' => 'OK']);
1114
1115        } catch (\Exception $e) {
1116            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1117        }
1118    }
1119
1120    function isEmailValid($email) {
1121        // Regular expression pattern for email validation
1122        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
1123        
1124        // Check if the email matches the pattern
1125        if (preg_match($pattern, $email)) {
1126            return true; // Valid email
1127        } else {
1128            return false; // Invalid email
1129        }
1130    }
1131
1132    function get_blocked_domains($id){
1133
1134        try {
1135            
1136            $companyId = addslashes($id);
1137
1138            $result = array();
1139
1140            if($companyId != 0){
1141                $result = TblBlockedDomains::where('company_id', $companyId)->get();
1142            }else{
1143                $result = TblBlockedDomains::whereIn('company_id', $this->companyIds)->get();
1144            }
1145
1146            return response(['message' => 'OK', 'data' => $result]);
1147
1148        } catch (\Exception $e) {
1149            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1150        }
1151    }
1152
1153    function delete_blocked_domain($id){
1154
1155        try {
1156            
1157            $id = addslashes($id);
1158
1159            TblBlockedDomains::where('id', $id)->delete();
1160
1161            Cache::flush();
1162            return response(['message' => 'OK']);
1163
1164        } catch (\Exception $e) {
1165            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1166        }
1167    }
1168
1169    function update_blocked_domain(Request $request, $id){
1170
1171        try {
1172
1173            $data = $request->all();
1174            $id = addslashes($id);
1175
1176            $result = TblBlockedDomains::where('company_id', $data['company_id'])->where('domain', strtolower($data['domain']))->count();
1177
1178            if($result > 0){
1179                return response(['message' => 'KO', 'error' => __('language.domain_exists')]);
1180            }else{
1181                $data['updated_at'] = date('Y-m-d H:i:s');
1182                TblBlockedDomains::where('id', $id)->update($data);
1183            }
1184
1185            Cache::flush();
1186            return response(['message' => 'OK']);
1187
1188        } catch (\Exception $e) {
1189            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1190        }
1191    }
1192
1193    function create_blocked_domain(Request $request){
1194
1195        try {
1196            
1197            $data = $request->all();
1198
1199            $result = TblBlockedDomains::where('company_id', $data['company_id'])->where('domain', strtolower($data['domain']))->count();
1200
1201            if($result > 0){
1202                return response(['message' => 'KO', 'error' => __('language.domain_exists')]);
1203            }else{
1204                TblBlockedDomains::create($data);
1205            }
1206
1207            Cache::flush();
1208            return response(['message' => 'OK']);
1209
1210        } catch (\Exception $e) {
1211            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1212        }
1213    }
1214
1215    function list_project_types($companyId){
1216
1217        try {
1218            
1219            $companyId = addslashes($companyId);
1220
1221            $result = TblProjectTypes::where('company_id', $companyId)->orderBy('project_id', 'ASC')->get();
1222
1223            $data = array();
1224
1225            for ($i = 0; $i < count($result); $i++) { 
1226                $data[$result[$i]->project_id]['project_id'] = $result[$i]->project_id;
1227                if($result[$i]->budget_type_id != null){
1228                    $data[$result[$i]->project_id]['budget_types'][] = $result[$i]->budget_type_id;
1229                }
1230                if($result[$i]->customer_type_ids != null){
1231                    $data[$result[$i]->project_id]['customer_types'] = array_map('intval', explode(',', $result[$i]->customer_type_ids));
1232                }
1233                $data[$result[$i]->project_id]['benchmarks'] = array(
1234                    'revenue_per_employee_per_day' => $result[$i]->revenue_per_employee_per_day,
1235                    'minimum_margin' => $result[$i]->minimum_margin,
1236                    'general_costs' => $result[$i]->general_costs,
1237                    'minimum_order_size' => $result[$i]->minimum_order_size,
1238                    'minimum_order_size_v2' => $result[$i]->minimum_order_size_v2,
1239                );
1240            }
1241
1242            return response(['message' => 'OK', 'data' => array_values($data)]);
1243
1244        } catch (\Exception $e) {
1245            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1246        }
1247
1248    }
1249
1250    function get_project_types($companyId){
1251
1252        try {
1253            
1254            $companyId = addslashes($companyId);
1255
1256            $result = TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', '!=', null)->get();
1257
1258            $query = "
1259                SELECT a.approver_id, u.name AS approver, 'v1' as type
1260                FROM tbl_approvers a
1261                LEFT JOIN tbl_users u ON a.user_id = u.id
1262                WHERE a.company_id = {$companyId}
1263
1264                UNION ALL
1265
1266                SELECT a.approver_id, u.name AS approver, 'v2' as type
1267                FROM tbl_approvers_v2 a
1268                LEFT JOIN tbl_users u ON a.user_id = u.id
1269                WHERE a.company_id = {$companyId}
1270            ";
1271
1272            $approvers = DB::select($query);
1273
1274            $ids = [];
1275            $names = [];
1276
1277            foreach ($approvers as $item) {
1278                $ids[] = $item->approver_id;
1279                $names[] = $item->approver;
1280            }
1281
1282            return response([
1283                'message' => 'OK', 
1284                'data' => $result,     
1285                'approversData' => $approvers,
1286                'approvers' => $ids, 
1287                'approverNames' => $names
1288            ]);
1289
1290        } catch (\Exception $e) {
1291            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1292        }
1293    }
1294
1295    function update_project_types(Request $request){
1296
1297        try {
1298            
1299            $data = $request->all();
1300            $companyId = addslashes($data['company_id']);
1301            $projectId = addslashes($data['project_id']);
1302            unset($data['company_id']);
1303            unset($data['project_id']);
1304
1305            $previousData = TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->first();
1306
1307            $lastBudgetTypeId = end($data['budget_type_id']);
1308            $project = TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', $lastBudgetTypeId)->first();
1309
1310            TblProjectTypes::where('company_id', $companyId)->whereIn('budget_type_id', $data['budget_type_id'])->delete();
1311            TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->delete();
1312
1313            foreach ($data['budget_type_id'] as $budgetTypeId) {
1314                TblProjectTypes::create(
1315                    array(
1316                        'company_id' => $companyId,
1317                        'project_id' => $projectId,
1318                        'customer_type_ids' => $previousData->customer_type_ids,
1319                        'budget_type_id' => $budgetTypeId,
1320                        'revenue_per_employee_per_day' => $previousData->revenue_per_employee_per_day,
1321                        'minimum_margin' => $previousData->minimum_margin,
1322                        'general_costs' => $previousData->general_costs,
1323                        'minimum_order_size' => $previousData->minimum_order_size,
1324                        'minimum_order_size_v2' => $previousData->minimum_order_size_v2,
1325                        'created_by' => $data['created_by']
1326                    )
1327                );
1328            }
1329
1330            if($project != null){
1331                if($project->budget_type_id != null){
1332                    TblProjectTypes::create(
1333                        array(
1334                            'company_id' => $companyId,
1335                            'project_id' => $project->project_id,
1336                            'budget_type_id' => null,
1337                            'customer_type_ids' => $project->customer_type_ids,
1338                            'revenue_per_employee_per_day' => $project->revenue_per_employee_per_day,
1339                            'minimum_margin' => $project->minimum_margin,
1340                            'general_costs' => $project->general_costs,
1341                            'minimum_order_size' => $project->minimum_order_size,
1342                            'minimum_order_size_v2' => $project->minimum_order_size_v2,
1343                            'created_by' => $data['created_by']
1344                        )
1345                    );
1346                }
1347            }
1348
1349            return $this->list_project_types($companyId);
1350
1351        } catch (\Exception $e) {
1352            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1353        }
1354
1355    }
1356
1357    function update_project_types_benchmarks(Request $request){
1358
1359        try {
1360            
1361            $data = $request->all();
1362            $companyId = addslashes($data['company_id']);
1363            $projectId = addslashes($data['project_id']);
1364
1365            unset($data['company_id']);
1366            unset($data['project_id']);
1367
1368            if(isset($data['customer_type_ids'])){
1369                $data['customer_type_ids'] = implode(',', $data['customer_type_ids']);
1370            }
1371
1372            TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->update($data);
1373
1374            return $this->list_project_types($companyId);
1375
1376        } catch (\Exception $e) {
1377            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1378        }
1379
1380    }
1381
1382    function delete_project_types(Request $request){
1383
1384        try {
1385            
1386            $data = $request->all();
1387            $companyId = addslashes($data['company_id']);
1388            $projectId = addslashes($data['project_id']);
1389            unset($data['company_id']);
1390            unset($data['project_id']);
1391
1392            $count = TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->count();
1393
1394            if($count > 1){
1395                TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', $data['budget_type_id'])->delete();
1396            }else{
1397                TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->update(array('budget_type_id' => null));
1398            }
1399
1400            return $this->list_project_types($companyId);
1401
1402        } catch (\Exception $e) {
1403            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1404        }
1405
1406    }
1407
1408    function list_workflow_project_types($companyId){
1409
1410        try {
1411            
1412            $companyId = addslashes($companyId);
1413
1414            $result = TblWorkflowProjectTypes::where('company_id', $companyId)->get();
1415
1416            return response(['message' => 'OK', 'data' => $result]);
1417
1418        } catch (\Exception $e) {
1419            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1420        }
1421
1422    }
1423
1424    function update_workflow_project_types(Request $request){
1425
1426        try {
1427            
1428            $data = $request->all();
1429
1430            TblWorkflowProjectTypes::where('company_id', $data['company_id'])->delete();
1431            
1432            for ($i = 0; $i < count($data['budget_type_id']); $i++) { 
1433                TblWorkflowProjectTypes::create(
1434                    array(
1435                        'company_id' => $data['company_id'],
1436                        'budget_type_id' => $data['budget_type_id'][$i],
1437                        'created_by' => $data['created_by']
1438                    )
1439                );
1440            }
1441
1442            return $this->list_workflow_project_types($data['company_id']);
1443
1444        } catch (\Exception $e) {
1445            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1446        }
1447
1448    }
1449
1450    function delete_workflow_project_types(Request $request){
1451
1452        try {
1453
1454            $data = $request->all();
1455            
1456            $companyId = addslashes($data['company_id']);
1457            $budgetTypeId = addslashes($data['budget_type_id']);
1458
1459            TblWorkflowProjectTypes::where('budget_type_id', $budgetTypeId)->where('company_id', $companyId)->delete();
1460
1461            return $this->list_workflow_project_types($companyId);
1462
1463        } catch (\Exception $e) {
1464            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1465        }
1466
1467    }
1468
1469    function list_workflow_customer_types($companyId){
1470
1471        try {
1472            
1473            $companyId = addslashes($companyId);
1474
1475            $result = TblWorkflowCustomerTypes::where('company_id', $companyId)->get();
1476
1477            return response(['message' => 'OK', 'data' => $result]);
1478
1479        } catch (\Exception $e) {
1480            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1481        }
1482
1483    }
1484
1485    function update_workflow_customer_types(Request $request){
1486
1487        try {
1488            
1489            $data = $request->all();
1490
1491            TblWorkflowCustomerTypes::where('company_id', $data['company_id'])->delete();
1492            
1493            for ($i = 0; $i < count($data['customer_type_id']); $i++) { 
1494                TblWorkflowCustomerTypes::create(
1495                    array(
1496                        'company_id' => $data['company_id'],
1497                        'customer_type_id' => $data['customer_type_id'][$i],
1498                        'created_by' => $data['created_by']
1499                    )
1500                );
1501            }
1502
1503            return $this->list_workflow_project_types($data['company_id']);
1504
1505        } catch (\Exception $e) {
1506            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1507        }
1508
1509    }
1510
1511    function delete_workflow_customer_types(Request $request){
1512
1513        try {
1514
1515            $data = $request->all();
1516            
1517            $companyId = addslashes($data['company_id']);
1518            $customerTypeId = addslashes($data['customer_type_id']);
1519
1520            TblWorkflowCustomerTypes::where('customer_type_id', $customerTypeId)->where('company_id', $companyId)->delete();
1521
1522            return $this->list_workflow_customer_types($companyId);
1523
1524        } catch (\Exception $e) {
1525            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1526        }
1527
1528    }
1529
1530    function list_workflow_questions($companyId){
1531
1532        try {
1533
1534            $companyId = addslashes($companyId);
1535
1536            $result = TblWorkflowQuestions::where('company_id', $companyId)->get();
1537
1538            return response(['message' => 'OK', 'data' => $result]);
1539
1540        } catch (\Exception $e) {
1541            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1542        }
1543
1544    }
1545
1546    function update_workflow_questions(Request $request, $questionId){
1547
1548        try {
1549            
1550            $data = $request->all();
1551            $questionId = addslashes($questionId);
1552            $companyId = addslashes($data['company_id']);
1553            unset($data['company_id']);
1554
1555            $data['updated_at'] = date('Y-m-d H:i:s');
1556            TblWorkflowQuestions::where('question_id', $questionId)->update($data);
1557
1558            return $this->list_workflow_questions($companyId);
1559
1560        } catch (\Exception $e) {
1561            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1562        }
1563
1564    }
1565
1566    function get_company_executive(){
1567
1568        try {
1569            
1570            $result = TblCompanies::where('is_send_executive', 1)->get();
1571
1572            return response(['message' => 'OK', 'data' => $result]);
1573
1574        } catch (\Exception $e) {
1575            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1576        }
1577
1578    }
1579
1580    function get_all_details($companyId){
1581
1582        try {
1583
1584            $companyId = addslashes($companyId);
1585
1586            $getCompany = $this->get_company($companyId);
1587            $listWorkflowQuestions = $this->list_workflow_questions($companyId);
1588            $listWorkflowCustomerTypes = $this->list_workflow_customer_types($companyId);
1589            $listWorkflowProjectTypes = $this->list_workflow_project_types($companyId);
1590            $getProjectTypes = $this->get_project_types($companyId);
1591            $getCompanyUsers = $this->get_company_users($companyId);
1592            $getBlockedDomains = TblBlockedDomains::where('company_id', $companyId)->get();
1593
1594            return response([
1595                'message' => 'OK', 
1596                'getCompany' => $getCompany->original['data'],
1597                'approvers' => $getProjectTypes->original['approvers'],
1598                'approverNames' => $getProjectTypes->original['approverNames'],
1599                'listWorkflowQuestions' => $listWorkflowQuestions->original['data'],
1600                'listWorkflowCustomerTypes' => $listWorkflowCustomerTypes->original['data'],
1601                'listWorkflowProjectTypes' => $listWorkflowProjectTypes->original['data'],
1602                'getProjectTypes' => $getProjectTypes->original['data'],
1603                'getBlockedDomains' => $getBlockedDomains,
1604                'getCompanyUsers' => $getCompanyUsers->original['data'],
1605            ]);
1606
1607        } catch (\Exception $e) {
1608            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1609        }
1610    }
1611
1612    function list_all_companies(){
1613
1614        try {
1615            
1616            $result = TblCompanies::whereIn('company_id', $this->companyIds)->get();
1617
1618            return response([
1619                'message' => 'OK', 
1620                'data' => $result
1621            ]);
1622
1623        } catch (\Exception $e) {
1624            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1625        }
1626
1627    }
1628
1629    function update_company_permission(Request $request, $userId){
1630
1631        try {
1632            
1633            $data = $request->all();
1634            $userId = addslashes($userId);
1635
1636            if(isset($data['read_only'])){
1637                if($data['read_only'] == false){
1638                    TblCompanyUsers::where('user_id', $userId)->update(
1639                        array(
1640                            'can_read' => 1,
1641                            'can_write' => 0,
1642                            'updated_at' => date('Y-m-d H:i:s'),
1643                            'updated_by' => $data['updated_by']
1644                        )
1645                    );
1646                }else{
1647                    TblCompanyUsers::where('user_id', $userId)->update(
1648                        array(
1649                            'can_read' => 1,
1650                            'can_write' => 1,
1651                            'updated_at' => date('Y-m-d H:i:s'),
1652                            'updated_by' => $data['updated_by']
1653                        )
1654                    );
1655                }
1656            }
1657
1658            return response([
1659                'message' => 'OK'
1660            ]);
1661
1662        } catch (\Exception $e) {
1663            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1664        }
1665
1666    }
1667
1668    function list_facility_settings(){
1669
1670        try {
1671            
1672            $result = TblFacilitySettings::get();
1673
1674            for ($i = 0; $i < count($result); $i++) {       
1675                if($result[$i]->budget_type_id != null){
1676                    $result[$i]->budget_type_id = array_map('intval', explode(',', $result[$i]->budget_type_id));    
1677                }                
1678            }
1679
1680            return response([
1681                'message' => 'OK',
1682                'data' => $result
1683            ]);
1684
1685        } catch (\Exception $e) {
1686            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1687        }
1688
1689    }
1690
1691    function update_facility_settings(Request $request, $id)
1692    {
1693        try {
1694
1695            $data = $request->all();
1696            $id = addslashes($id); 
1697            $data['updated_at'] = date('Y-m-d H:i:s');
1698
1699            if (isset($data['budget_type_id']) && is_array($data['budget_type_id'])) {
1700                $incomingIds = $data['budget_type_id'];
1701
1702                $rows = TblFacilitySettings::all();
1703
1704                foreach ($rows as $row) {
1705                    $currentIds = $row->budget_type_id ? explode(',', $row->budget_type_id) : [];
1706
1707                    $newIds = array_diff($currentIds, $incomingIds);
1708
1709                    if (!empty($newIds)) {
1710                        TblFacilitySettings::where('id', $row->id)->update([
1711                            'budget_type_id' => implode(',', $newIds),
1712                            'updated_at' => date('Y-m-d H:i:s')
1713                        ]);
1714                    } else {
1715                        TblFacilitySettings::where('id', $row->id)->update([
1716                            'budget_type_id' => '',
1717                            'updated_at' => date('Y-m-d H:i:s')
1718                        ]);
1719                    }
1720                }
1721
1722                $data['budget_type_id'] = implode(',', $incomingIds);
1723
1724                $exists = TblFacilitySettings::where('id', $id)->exists();
1725                if ($exists) {
1726                    TblFacilitySettings::where('id', $id)->update($data);
1727                } else {
1728                    TblFacilitySettings::create(array_merge($data, ['id' => $id]));
1729                }
1730            }elseif(isset($data['minimum_budget_amount'])){
1731                TblFacilitySettings::where('id', $id)->update($data);
1732            }
1733
1734            $result = $this->list_facility_settings();
1735
1736            return response([
1737                'message' => 'OK',
1738                'data' => $result->original['data']
1739            ]);
1740
1741        } catch (\Exception $e) {
1742            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1743        }
1744    }
1745
1746    function list_trade_alignment_settings($companyId){
1747
1748        try {
1749            
1750            $companyId = addslashes($companyId);
1751            $result = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
1752
1753            for ($i = 0; $i < count($result); $i++) {       
1754                if($result[$i]->budget_type_id != null){
1755                    $result[$i]->budget_type_id = array_map('intval', explode(',', $result[$i]->budget_type_id));    
1756                }                
1757            }
1758
1759            return response([
1760                'message' => 'OK',
1761                'data' => $result
1762            ]);
1763
1764        } catch (\Exception $e) {
1765            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1766        }
1767
1768    }
1769
1770    function update_trade_alignment_settings(Request $request, $id)
1771    {
1772        try {
1773
1774            $data = $request->all();
1775            $id = addslashes($id); 
1776            $data['updated_at'] = date('Y-m-d H:i:s');
1777            $companyId = addslashes($data['company_id']);
1778
1779            if (isset($data['budget_type_id']) && is_array($data['budget_type_id'])) {
1780                $incomingIds = $data['budget_type_id'];
1781
1782                $rows = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
1783
1784                foreach ($rows as $row) {
1785                    $currentIds = $row->budget_type_id ? explode(',', $row->budget_type_id) : [];
1786
1787                    $newIds = array_diff($currentIds, $incomingIds);
1788
1789                    if (!empty($newIds)) {
1790                        TblTradeAlignmentSettings::where('id', $row->id)->update([
1791                            'budget_type_id' => implode(',', $newIds),
1792                            'updated_at' => date('Y-m-d H:i:s')
1793                        ]);
1794                    } else {
1795                        TblTradeAlignmentSettings::where('id', $row->id)->update([
1796                            'budget_type_id' => '',
1797                            'updated_at' => date('Y-m-d H:i:s')
1798                        ]);
1799                    }
1800                }
1801
1802                $data['budget_type_id'] = implode(',', $incomingIds);
1803
1804                $exists = TblTradeAlignmentSettings::where('id', $id)->exists();
1805                if ($exists) {
1806                    TblTradeAlignmentSettings::where('id', $id)->update($data);
1807                } else {
1808                    TblTradeAlignmentSettings::create(array_merge($data, ['id' => $id]));
1809                }
1810            }elseif(isset($data['minimum_budget_amount'])){
1811                TblTradeAlignmentSettings::where('id', $id)->update($data);
1812            }
1813
1814            $result = $this->list_trade_alignment_settings($companyId);
1815
1816            return response([
1817                'message' => 'OK',
1818                'data' => $result->original['data']
1819            ]);
1820
1821        } catch (\Exception $e) {
1822            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1823        }
1824    }
1825
1826}