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