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