Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
20.67% covered (danger)
20.67%
1628 / 7876
10.49% covered (danger)
10.49%
15 / 143
CRAP
0.00% covered (danger)
0.00%
0 / 1
Quotations
20.67% covered (danger)
20.67%
1628 / 7876
10.49% covered (danger)
10.49%
15 / 143
2418502.49
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 create_quotation
55.34% covered (warning)
55.34%
57 / 103
0.00% covered (danger)
0.00%
0 / 1
65.11
 currency
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 send_approval_notification
0.00% covered (danger)
0.00%
0 / 136
0.00% covered (danger)
0.00%
0 / 1
1332
 send_approval_margin_notification
0.00% covered (danger)
0.00%
0 / 115
0.00% covered (danger)
0.00%
0 / 1
342
 isApproverAuthorizedFor
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 approverActingType
97.14% covered (success)
97.14%
34 / 35
0.00% covered (danger)
0.00%
0 / 1
19
 pendingApprovalDimensions
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
16
 recordApprovalDecision
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 clearApprovalIfDecided
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
16.04
 approve_quotation
89.80% covered (warning)
89.80%
44 / 49
0.00% covered (danger)
0.00%
0 / 1
16.27
 buildTitanEmailCard
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 send_approved_notification
0.00% covered (danger)
0.00%
0 / 82
0.00% covered (danger)
0.00%
0 / 1
342
 reject_quotation
93.33% covered (success)
93.33%
42 / 45
0.00% covered (danger)
0.00%
0 / 1
16.08
 preview_approval
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 confirm_approval_request
0.00% covered (danger)
0.00%
0 / 58
0.00% covered (danger)
0.00%
0 / 1
210
 resolveApprovers
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 notifyApproversBudgetChanged
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 notifyApproversNoLongerRequired
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pushApproverNotifications
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 approvalDimsFromType
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 intOrNull
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 floatOrNull
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
12
 invalidAmountResponse
46.15% covered (danger)
46.15%
6 / 13
0.00% covered (danger)
0.00%
0 / 1
29.89
 measuredFloatOrNull
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 evaluateApprovalForBudget
7.14% covered (danger)
7.14%
3 / 42
0.00% covered (danger)
0.00%
0 / 1
195.15
 sendApprovalEmailV2
23.61% covered (danger)
23.61%
17 / 72
0.00% covered (danger)
0.00%
0 / 1
145.82
 buildApprovalConditionsNota
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
156
 list_my_pending_approvals
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
506
 send_rejected_notification
0.00% covered (danger)
0.00%
0 / 83
0.00% covered (danger)
0.00%
0 / 1
342
 update_quotation
23.53% covered (danger)
23.53%
160 / 680
0.00% covered (danger)
0.00%
0 / 1
22661.75
 compareArrays
60.00% covered (warning)
60.00%
9 / 15
0.00% covered (danger)
0.00%
0 / 1
8.30
 isEmpty
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
20
 convertValue
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
23.81
 callDeleteQuotation
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 get_quotation
74.29% covered (warning)
74.29%
26 / 35
0.00% covered (danger)
0.00%
0 / 1
17.33
 get_quotation_log
52.17% covered (warning)
52.17%
12 / 23
0.00% covered (danger)
0.00%
0 / 1
3.98
 send_notification
0.00% covered (danger)
0.00%
0 / 68
0.00% covered (danger)
0.00%
0 / 1
72
 delete_quotation
43.18% covered (danger)
43.18%
19 / 44
0.00% covered (danger)
0.00%
0 / 1
23.86
 archiveQuotations
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
30
 getBlacklistEmails
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 pendingFollowUpSql
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 validate_email
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
6
 isBlacklistedEmail
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
5.05
 isInvalidEmail
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
6.29
 normalizeSendChannel
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 list_quotations
24.76% covered (danger)
24.76%
103 / 416
0.00% covered (danger)
0.00%
0 / 1
8976.39
 list_orders_table
56.52% covered (warning)
56.52%
117 / 207
0.00% covered (danger)
0.00%
0 / 1
203.12
 build_orders_table_filters
45.00% covered (danger)
45.00%
45 / 100
0.00% covered (danger)
0.00%
0 / 1
366.10
 orders_yes_no_clause
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 text_filter_clause
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
132
 get_dates
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 list_quotation_analytics_by_source
85.25% covered (warning)
85.25%
104 / 122
0.00% covered (danger)
0.00%
0 / 1
52.80
 list_quotation_analytics_send_budgets
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
342
 list_quotation_analytics_track_budgets
87.60% covered (warning)
87.60%
106 / 121
0.00% covered (danger)
0.00%
0 / 1
44.20
 list_quotation_analytics_types_budgets
84.55% covered (warning)
84.55%
104 / 123
0.00% covered (danger)
0.00%
0 / 1
42.05
 download_quotations
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
6
 download_quotations_csv
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 bulk_upload
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
30
 list_bulk_upload
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 delete_number
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 get_number
86.84% covered (warning)
86.84%
33 / 38
0.00% covered (danger)
0.00%
0 / 1
11.28
 get_years
87.88% covered (warning)
87.88%
29 / 33
0.00% covered (danger)
0.00%
0 / 1
3.02
 human_filesize
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 get_files
0.00% covered (danger)
0.00%
0 / 136
0.00% covered (danger)
0.00%
0 / 1
1980
 download_file
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
90
 delete_file
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
56
 upload_coverage_contract
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
30
 upload_signed_coverage_contract
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
30
 sopBlockingRequirements
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
72
 matchesBudgetSetting
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 resolveEmailBody
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 isRowPendingApproval
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 budgetRequiresUnresolvedApproval
14.29% covered (danger)
14.29%
3 / 21
0.00% covered (danger)
0.00%
0 / 1
48.30
 send_approval_gate
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 warnMissingEmailTemplate
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 send_email_to_client
0.00% covered (danger)
0.00%
0 / 425
0.00% covered (danger)
0.00%
0 / 1
14280
 mark_manual_follow_up
0.00% covered (danger)
0.00%
0 / 55
0.00% covered (danger)
0.00%
0 / 1
90
 send_email_follow_ups
0.00% covered (danger)
0.00%
0 / 552
0.00% covered (danger)
0.00%
0 / 1
15750
 create_sender_identity
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
56
 get_sender_identity
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 get_all_sender_identity
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 delete_sender_identity
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 create_template
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
72
 get_email_files
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 download_email_template_file
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 delete_email_template_file
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 update_email_template_order
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 update_email_template
26.19% covered (danger)
26.19%
11 / 42
0.00% covered (danger)
0.00%
0 / 1
41.57
 delete_template
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 delete_email_template_user_override
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 get_email_template
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 update_sender_identity
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
20
 resend_verification
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 list_quotation_analytics_by_performance
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
30
 list_orders_update_logs
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 list_g3w_orders_update_logs
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 list_g3w_orders_failed
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
30
 list_cofrai_orders_update_logs
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 list_cofrai_orders_failed
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
30
 update_budget_status_rejected_manual
50.00% covered (danger)
50.00%
4 / 8
0.00% covered (danger)
0.00%
0 / 1
4.12
 update_budget_status_rejected
74.55% covered (warning)
74.55%
41 / 55
0.00% covered (danger)
0.00%
0 / 1
11.65
 bulk_update_quotation
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
110
 move_budget_and_job
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
56
 list_quotation_analytics_by_types_of_budgets_created_per_week
0.00% covered (danger)
0.00%
0 / 197
0.00% covered (danger)
0.00%
0 / 1
4290
 preview_file
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 get_past_added_quotation
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
30
 send_acceptance_notification
0.00% covered (danger)
0.00%
0 / 84
0.00% covered (danger)
0.00%
0 / 1
210
 get_total_quotations_by_budget_status
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
90
 sendgrid_webhook_receiver
86.54% covered (warning)
86.54%
45 / 52
0.00% covered (danger)
0.00%
0 / 1
16.62
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 list_email_status
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
30
 list_quotation_analytics_commercial
0.00% covered (danger)
0.00%
0 / 186
0.00% covered (danger)
0.00%
0 / 1
3540
 clear_open_data
84.00% covered (warning)
84.00%
21 / 25
0.00% covered (danger)
0.00%
0 / 1
5.10
 list_quotation_analytics_order_size
0.00% covered (danger)
0.00%
0 / 194
0.00% covered (danger)
0.00%
0 / 1
4830
 send_email_template_preview
0.00% covered (danger)
0.00%
0 / 110
0.00% covered (danger)
0.00%
0 / 1
342
 list_quotation_analytics_by_types_of_budgets_company_per_week
0.00% covered (danger)
0.00%
0 / 194
0.00% covered (danger)
0.00%
0 / 1
4290
 request_permission_commercial
0.00% covered (danger)
0.00%
0 / 73
0.00% covered (danger)
0.00%
0 / 1
90
 confirm_update_commercial
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 calculateEmailRequestSize
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
56
 list_quotation_analytics_commercial_productivity
0.00% covered (danger)
0.00%
0 / 264
0.00% covered (danger)
0.00%
0 / 1
5700
 applyCommercialRollupObjectives
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 loadCommercialDefaultGoals
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
342
 rewriteRollupNode
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
240
 overwriteObjectiveColumns
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
132
 list_quotations_deleted
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 delete_sengrid
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
20
 download_productivity_commercial
0.00% covered (danger)
0.00%
0 / 378
0.00% covered (danger)
0.00%
0 / 1
2450
 update_commercial_numbers
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 list_quotation_analytics_by_service_type
87.90% covered (warning)
87.90%
138 / 157
0.00% covered (danger)
0.00%
0 / 1
41.70
 getIdsFromInternalQuoteIds
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 checkQuotationExistByInternalQuoteId
83.33% covered (warning)
83.33%
15 / 18
0.00% covered (danger)
0.00%
0 / 1
5.12
 addUpdateLog
82.14% covered (warning)
82.14%
69 / 84
0.00% covered (danger)
0.00%
0 / 1
56.53
 setSolicitudDuplicity
86.96% covered (warning)
86.96%
20 / 23
0.00% covered (danger)
0.00%
0 / 1
6.08
 getQuoteIdOfDuplicityById
71.43% covered (warning)
71.43%
10 / 14
0.00% covered (danger)
0.00%
0 / 1
5.58
 findQuotationForReplacement
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
42
 resolveReplaceableQuote
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 linkReplacedQuote
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
20
 excludeReplacedQuotesSql
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 getQuoteReplacementLinks
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
42
 download_s3_files
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
72
 getQuotationStatusByInternalId
41.18% covered (danger)
41.18%
21 / 51
0.00% covered (danger)
0.00%
0 / 1
30.35
 findQuotationByInternalId
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Exceptions\AppException;
6use App\Jobs\CheckQuotationDuplicate;
7use App\Jobs\Email\SendApprovalEmail;
8use App\Jobs\Email\SendApprovedEmail;
9use App\Jobs\Email\SendRejectedEmail;
10use App\Models\Client;
11use App\Models\ReplacedQuote;
12use App\Models\StructureData;
13use App\Models\TblBlockedDomains;
14use App\Models\TblBudgetStatus;
15use App\Models\TblBudgetTypeGroups;
16use App\Models\TblBudgetTypes;
17use App\Models\TblBulkUpload;
18use App\Models\TblBusinessGoals;
19use App\Models\TblCcAcceptanceNotifications;
20use App\Models\TblCcBcc;
21use App\Models\TblCofraiOrdersUpdateLogs;
22use App\Models\TblCompanies;
23use App\Models\TblCompanyEmails;
24use App\Models\TblCoverageContractSettings;
25use App\Models\TblCustomerTypes;
26use App\Models\TblEmailConfiguration;
27use App\Models\TblEmailFiles;
28use App\Models\TblEmailTemplateUserOverride;
29use App\Models\TblFiles;
30use App\Models\TblFollowUpLogs;
31use App\Models\TblG3WOrdersUpdateLogs;
32use App\Models\TblLastFollowUpDate;
33use App\Models\TblMaintenancePotentialSettings;
34use App\Models\TblNotifications;
35use App\Models\TblOngoingJobs;
36use App\Models\TblOrdersUpdateLogs;
37use App\Models\TblProjectTypes;
38use App\Models\TblQuotations;
39use App\Models\TblQuotationSends;
40use App\Models\TblQuotationsLog;
41use App\Models\TblSegments;
42use App\Models\TblSendgridWebhook;
43use App\Models\TblSourceCodigos;
44use App\Models\TblSources;
45use App\Models\TblToAcceptanceNotifications;
46use App\Models\TblUsers;
47use App\Models\TblVisitTypeGroups;
48use App\Models\TblWorkflowQuestions;
49use App\Services\ApprovalStateResolver;
50use App\Services\ApprovalThresholdEngine;
51use App\Services\PresupuestosService;
52use App\Services\QuotationSendRecorder;
53use App\Services\ResultCache;
54use App\Services\SendgridDispatcher;
55use App\Services\SendgridLogger;
56use App\Services\UserCompanies;
57use App\Services\WhatsAppService;
58use App\Services\ZeusBridge;
59use Illuminate\Contracts\Routing\ResponseFactory;
60use Illuminate\Http\Request;
61use Illuminate\Http\Response as HttpResponse;
62use Illuminate\Support\Carbon;
63use Illuminate\Support\Facades\App;
64use Illuminate\Support\Facades\Cache;
65use Illuminate\Support\Facades\DB;
66use Illuminate\Support\Facades\File;
67use Illuminate\Support\Facades\Log;
68use Illuminate\Support\Facades\Response;
69use Illuminate\Support\Facades\Schema;
70use Illuminate\Support\Facades\Storage;
71use PhpOffice\PhpSpreadsheet\IOFactory;
72use PhpOffice\PhpSpreadsheet\Spreadsheet;
73use PhpOffice\PhpSpreadsheet\Style\Alignment;
74use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
75use SendGrid\Mail\Attachment;
76use SendGrid\Mail\Mail;
77use ZipArchive;
78
79class Quotations extends Controller
80{
81    /**
82     * tbl_budget_status ids whose name is "Rechazado*": 4 = Rechazado,
83     * 7 = Rechazado - automaticamente, 18 = Rechazado - IA,
84     * 20 = Rechazado-duplicado. A rejected budget is dead, so nothing about it
85     * can still be awaiting approval.
86     */
87    private const REJECTED_STATUS_IDS = '4,7,18,20';
88
89    /** tbl_budget_status 20 = "Rechazado-duplicado" - where a replaced quote lands. */
90    private const STATUS_REJECTED_DUPLICATE = 20;
91
92    /**
93     * What "pending approval" means in SQL (alias `a` = tbl_quotations).
94     *
95     * `for_approval` alone is not enough: it is only the pending flag, and rows
96     * decided before `reject_quotation` learned to clear it — plus the legacy
97     * rows where `for_approval = 2` meant "decided" rather than today's
98     * "finance-only pending" — keep it set forever. Filtering on the flag alone
99     * put rejected budgets in the "Requiere aprobación = Sí" results.
100     *
101     * A recorded rejection in EITHER slot ends the circuit (SOP §15: an
102     * Operations rejection never advances to Finance), so either slot being
103     * filled means the budget is decided, whatever the flag still says. The
104     * one-off backfill lives in
105     * 2026_07_28_000001_clear_stale_pending_approval_flags; this guard is what
106     * stops a future stranding from reappearing as pending.
107     */
108    private const PENDING_APPROVAL_SQL = '(a.for_approval IN (1,2,3)'
109        .' AND a.rejected_by IS NULL AND a.rejected_by_v2 IS NULL'
110        .' AND (a.budget_status_id IS NULL OR a.budget_status_id NOT IN ('.self::REJECTED_STATUS_IDS.')))';
111
112    /**
113     * Pending and waiting on the TECHNICAL approver now: type 1 or 3 (both),
114     * technical slot not decided yet. Same rule as approverActingType() and
115     * the approver's own queue (list_my_pending_approvals).
116     *
117     * The "Tipo de aprobación = Técnica" filter used to match approval_type = 1
118     * only. A quote rejected and re-saved often comes back as 3 (the edit also
119     * crosses the financial threshold), and vanished from the technical
120     * approver's filter while still needing him (Fran Alvarez, Madrid, 10/2026).
121     */
122    private const PENDING_TECHNICAL_SQL = '('.self::PENDING_APPROVAL_SQL
123        .' AND COALESCE(a.approval_type, a.for_approval) IN (1,3)'
124        ." AND NULLIF(a.approved_by, '') IS NULL)";
125
126    /**
127     * Pending and waiting on the FINANCIAL approver now: type 2, or type 3
128     * once the technical approval is given (dual is sequential, Operations
129     * then Finance: before that Finance cannot act on it).
130     */
131    private const PENDING_FINANCIAL_SQL = '('.self::PENDING_APPROVAL_SQL
132        ." AND NULLIF(a.approved_by_v2, '') IS NULL"
133        .' AND (COALESCE(a.approval_type, a.for_approval) = 2'
134        ." OR (COALESCE(a.approval_type, a.for_approval) = 3 AND NULLIF(a.approved_by, '') IS NOT NULL)))";
135
136    /** Exact negation of PENDING_APPROVAL_SQL — everything not awaiting a decision. */
137    private const NOT_PENDING_APPROVAL_SQL = '(a.for_approval NOT IN (1,2,3) OR a.for_approval IS NULL'
138        .' OR a.rejected_by IS NOT NULL OR a.rejected_by_v2 IS NOT NULL'
139        .' OR a.budget_status_id IN ('.self::REJECTED_STATUS_IDS.'))';
140
141    private $locale;
142
143    private $userId;
144
145    private $region;
146
147    private $companyIds;
148
149    private readonly string $companyId;
150
151    /** addUpdateLog(): user id → display name, so a multi-field save looks the user up once. */
152    private array $logUserNames = [];
153
154    public function __construct()
155    {
156        $this->locale = request()->header('Locale-Id');
157        $this->userId = request()->header('User-Id');
158        $this->region = request()->header('Region');
159
160        App::setLocale($this->locale);
161
162        $this->companyIds = [];
163
164        if ($this->region != null && $this->region != '' && $this->region != 'All') {
165            $this->region = urldecode((string) $this->region);
166
167            $query = 'SELECT
168                        b.company_id
169                    FROM
170                        tbl_company_users a
171                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
172                    WHERE
173                        a.user_id = ?
174                        AND b.region = ?';
175
176            $this->companyIds = DB::select($query, [intval($this->userId), $this->region]);
177
178            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
179        } else {
180            // FIRE-1146: prefer the middleware-resolved attribute; fall back to a fresh fetch only on unattached paths.
181            $this->companyIds = request()->attributes->get('user_company_ids', UserCompanies::forUser((int) $this->userId));
182        }
183
184        $this->companyId = implode(',', $this->companyIds);
185    }
186
187    public function create_quotation(Request $request): ResponseFactory|HttpResponse
188    {
189
190        try {
191
192            // Titan → Zeus bridge. Madrid is the first region to move to Zeus,
193            // so a Madrid write from an external consumer (Fluency Labs,
194            // Víctor's AI, the chatbot, the landing pages) is replayed to Zeus
195            // exactly as the third party sent it. In `mirror` mode — the trial
196            // default — we then carry on and save in Titan as always, and the
197            // caller gets Titan's usual response. Everything else falls through
198            // untouched. See config/zeus.php.
199            // Reject a non-numeric amount before the Zeus bridge, so a payload
200            // Titan refuses is never mirrored to Zeus either.
201            if ($invalid = $this->invalidAmountResponse($request->all())) {
202                return $invalid;
203            }
204
205            $zeus = app(ZeusBridge::class);
206            $forward = $zeus->createQuotation($request);
207
208            if ($zeus->shouldReturnZeusResponse($forward)) {
209                return $forward->toTitanResponse();
210            }
211
212            $data = $request->all();
213            $data['updated_at'] = date('Y-m-d H:i:s');
214
215            // A blank amount arrives as the literal "null" from the orders form.
216            // update_quotation already maps it to PHP null; create didn't, so
217            // the string itself was stored.
218            if (($data['amount'] ?? null) === 'null') {
219                $data['amount'] = null;
220            }
221
222            // "Replace quotation": the Quote # the commercial pasted on the add
223            // form. Held aside because it is not a tbl_quotations column - the
224            // link lives in replaced_quotes and is written after the new row
225            // exists, since it needs the new id.
226            $replacedQuoteId = trim((string) ($data['replaced_quote_id'] ?? ''));
227
228            // FIRE-1753: CLM (22) was merged into Madrid (18) by FIRE-1476 /
229            // commit 20cb916b (2026-08-05). An external "IA" integration is
230            // still POSTing company_id = 22 (created_by = 'IA', ~1 row every
231            // 10 days), which is where the trickle Ricardo saw as of 2026-08-25
232            // is coming from. The sync path is already clean since the whitelist
233            // in PresupuestosService::resolveCompanyForRegion — this rewrite is
234            // the belt-and-braces at the manual/API entry point.
235            if (! empty($data['company_id']) && (int) $data['company_id'] === 22) {
236                Log::channel('g3w')->warning(sprintf(
237                    'FIRE-1753: rewriting company_id 22 → 18 on create_quotation. created_by=%s, quote_id=%s',
238                    $data['created_by'] ?? '?',
239                    $data['quote_id'] ?? '?',
240                ));
241                $data['company_id'] = 18;
242            }
243
244            // FIRE-1260 — if the client picked a código, verify it belongs
245            // to the source they also picked. Optional field: NULL/empty is
246            // valid and skips the check.
247            if (! empty($data['codigo_id'])) {
248                $belongs = TblSourceCodigos::where('id', $data['codigo_id'])
249                    ->where('source_id', $data['source_id'] ?? null)
250                    ->exists();
251                if (! $belongs) {
252                    return response([
253                        'message' => 'KO',
254                        'error' => 'El código no pertenece a la fuente seleccionada',
255                    ], 422);
256                }
257            }
258
259            if (isset($data['request_date']) && isset($data['issue_date'])) {
260                $requestDate = strtotime($data['request_date']);
261                $issueDate = strtotime($data['issue_date']);
262                $dateDiff = $issueDate - $requestDate;
263                $data['duration'] = round($dateDiff / (60 * 60 * 24));
264            }
265
266            $r = new Request([
267                'created_by' => $data['created_by'],
268            ]);
269
270            $result = $this->get_number($r, @$data['company_id']);
271            $id = $result->original['id'];
272
273            $files = $request->file('files');
274            if ($files) {
275                $uploadedFiles = [];
276
277                foreach ($files as $file) {
278                    $filename = time().'_'.$file->getClientOriginalName();
279                    $fileSize = $file->getSize();
280                    // $fileContent = file_get_contents($file->getRealPath());
281                    // $fileHash = hash('sha256', $fileContent);
282
283                    $s3path = Storage::disk('s3')->putFileAs(
284                        'uploads',
285                        $file,
286                        $filename,
287                        [
288                            'ContentType' => $file->getMimeType(),
289                        ]
290                    );
291
292                    TblFiles::create(
293                        [
294                            'quotation_id' => $id,
295                            'original_name' => $file->getClientOriginalName(),
296                            'filename' => $filename,
297                            'uploaded_by' => $data['updated_by'],
298                            // 'file' => $fileContent,
299                            'file_size' => $file->getSize(),
300                            // 'file_hash' => $fileHash,
301                            'mime_type' => $file->getMimeType(),
302                            'uploaded_at' => now(),
303                        ]
304                    );
305
306                    // $this->addUpdateLog($id, $data['updated_by'], "upload_attachment", null, $filename, 4);
307                }
308            }
309
310            $query = 'SELECT COUNT(*) as count FROM tbl_files WHERE quotation_id = ?';
311            $fileCount = DB::select($query, [$id])[0]->count;
312
313            $data['has_attachment'] = $fileCount > 0 ? 1 : 0;
314
315            $data = array_diff_key($data, array_flip(['files', '_token', 'otros_campos_no_necesarios', 'replaced_quote_id']));
316
317            $data['for_add'] = 0;
318
319            // FIRE-1377: normalise the send channel and enforce the amount rule.
320            $data['send_channel'] = $this->normalizeSendChannel($data['send_channel'] ?? null, $data['amount'] ?? null);
321
322            // FIRE-864 / FIRE-1377: if email is invalid (blacklisted, malformed,
323            // or empty) and status is sendable, set to 22 (Correo erroneo).
324            // This ONLY applies when the budget is sent by email — correo
325            // ordinario and WhatsApp budgets never require a valid email and
326            // must never be routed to the "emails with error" bucket.
327            if ($data['send_channel'] === 'email'
328                && isset($data['email']) && $this->isInvalidEmail($data['email'])
329                && isset($data['budget_status_id']) && in_array($data['budget_status_id'], [1, 2, 11, 17])) {
330                $data['budget_status_id'] = 22;
331            }
332
333            TblQuotations::where('id', $id)->update($data);
334
335            $result = TblQuotations::where('id', $id)->first();
336
337            // Retire the quote this one replaces: status 20 + audit log + the
338            // replaced_quotes link. Re-validated inside, and deliberately
339            // non-fatal - a new quote that already saved must not be lost
340            // because the replacement target went stale while the form was open.
341            if ($replacedQuoteId !== '' && $result) {
342                $this->linkReplacedQuote(
343                    $result,
344                    $replacedQuoteId,
345                    (int) ($result->company_id ?? 0),
346                    $data['updated_by'] ?? ($data['created_by'] ?? null)
347                );
348            }
349
350            // FIRE-1199: removed the `if ($result->budget_status_id == 6)` gate —
351            // we now track duplicities on every quotation regardless of status,
352            // not only on Solicitud. The Lambda still decides what's a duplicate;
353            // we just send it more candidates. UI for non-Solicitud is info-only
354            // (no Rechazar/Ignorar buttons — see orders.component.html).
355            $data = [
356                'id' => $result->id ?? null,
357                'client' => $result->client ?? null,
358                'email' => $result->email ?? null,
359                'phone_number' => $result->phone_number ?? null,
360                'last_follow_up_comment' => $result->last_follow_up_comment ?? null,
361                'quote_id' => $result->quote_id ?? null,
362                'request_date' => date('Y-m-d'),
363                'updated_by' => 'IA',
364                'user_id' => $result->getAttribute('user_id') ?? null,
365                'commercial' => $result->commercial ?? null,
366                'budget_status_id' => $result->budget_status_id ?? null,
367                'internal_quote_id' => $result->internal_quote_id ?? null,
368            ];
369
370            // FIRE-1147: dispatch the Lambda duplicate-checker async.
371            // The original inline curl call blocked the HTTP response for
372            // 3-5 s but its return value was already discarded — no
373            // downstream code reads $response or $httpCode — so moving
374            // this to a job is a pure latency win with no behaviour change.
375            CheckQuotationDuplicate::dispatch($data)->onQueue('default');
376
377            $logCategory = $result->budget_status_id == 6 ? 0 : 2;
378            $this->addUpdateLog($result->id, $result->getAttribute('user_id'), 'create_quotation', null, null, $logCategory);
379            // FIRE-1145: was Cache::flush() — scoped to the domains create_quotation actually affects.
380            ResultCache::forgetDomain(['quotations', 'users']);
381
382            return response(['message' => 'OK', 'data' => $result]);
383
384        } catch (\Exception $e) {
385            report(AppException::fromException($e, 'CREATE_QUOTATION_EXCEPTION'));
386
387            return response(['message' => 'KO', 'error' => $e->getMessage()]);
388        }
389
390    }
391
392    public function currency($amount, $withEuro = '')
393    {
394
395        if ($withEuro != null) {
396            $withEuro = ' €';
397        }
398
399        return number_format($amount, 2, ',', '.').$withEuro;
400    }
401
402    public function send_approval_notification($amount, $budgetTypeId, $customerTypeId, $minimumOrderSize, string $quoteId, $id, $companyName, $createdBy, $userId, $action, $commercialEmail, $companyId, $endpoint, $isQuestion, $questionIdsNo, $n, $locale = null, bool $isReapproval = false, $previousAmount = null): void
403    {
404        // FIRE-1930: honour the per-region kill switch for approval
405        // emails. Assumed semantics (default read of Berta's ticket,
406        // pending explicit confirmation): the switch suppresses BOTH
407        // the initial request AND the reminders — approvers in a paused
408        // region simply don't get notified during the pause. When the
409        // switch is flipped back on, the reminder cron picks them up on
410        // its next run (initial requests are only sent from user actions
411        // and are NOT retroactively re-fired).
412        if (! SendgridDispatcher::isAllowed(
413            SendgridDispatcher::BUCKET_APPROVAL,
414            (int) $companyId,
415        )) {
416            return;
417        }
418
419        if (! is_null($locale)) {
420            $this->locale = $locale;
421        }
422
423        if ($action != 1) {
424            if ($this->locale == 'es') {
425                $action = 'actualizado';
426            } else {
427                $action = 'updated';
428            }
429
430        } else {
431            if ($this->locale == 'es') {
432                $action = 'creado';
433            } else {
434                $action = 'created';
435            }
436        }
437
438        $fendpoint = '';
439
440        if ($endpoint == 'orders') {
441            if ($this->locale == 'es') {
442                $fendpoint = 'presupuesto';
443            } else {
444                $fendpoint = 'budget';
445            }
446
447        } else {
448            if ($this->locale == 'es') {
449                $fendpoint = 'trabajo';
450            } else {
451                $fendpoint = 'job';
452            }
453        }
454
455        $user = TblUsers::where('id', $userId)->first();
456
457        $query = "SELECT
458                    a.approver_id,
459                    a.user_id,
460                    b.name,
461                    b.email
462                FROM
463                    tbl_approvers a
464                    INNER JOIN tbl_users b ON a.user_id = b.id
465                WHERE a.company_id = {$companyId}
466                ";
467
468        if ($n == 3) {
469            $query = "SELECT
470                        a.approver_id,
471                        a.user_id,
472                        u.name,
473                        u.email
474                    FROM tbl_approvers a
475                    INNER JOIN tbl_users u ON a.user_id = u.id
476                    WHERE a.company_id = {$companyId}
477
478                    UNION ALL
479
480                    SELECT
481                        c.approver_id,
482                        c.user_id,
483                        u2.name,
484                        u2.email
485                    FROM tbl_approvers_v2 c
486                    INNER JOIN tbl_users u2 ON c.user_id = u2.id
487                    WHERE c.company_id = {$companyId}";
488        }
489
490        $approvers = DB::select($query);
491
492        if (count($approvers) > 0) {
493            $amount = $this->currency($amount, 1);
494            $minimumOrderSize = $this->currency($minimumOrderSize, 1);
495
496            $budgetType = TblBudgetTypes::where('budget_type_id', $budgetTypeId)->first();
497            $clientType = TblCustomerTypes::where('customer_type_id', $customerTypeId)->first();
498
499            $imgpath = file_get_contents(public_path('fireservicetitan.png'));
500            $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
501
502            $subject = __('language.send_approval_notification.subject');
503            $subject = str_replace('{{type}}', $budgetType->name, $subject);
504            $subject = str_replace('{{amount}}', $amount, $subject);
505            $subject = str_replace('{{endpoint}}', ucfirst($fendpoint), $subject);
506
507            // E2 (SOP §10): re-approval of a budget that was already approved.
508            $reapprovalPrefix = $this->locale == 'es' ? 'Re-aprobación · ' : 'Re-approval · ';
509            if ($isReapproval) {
510                $subject = $reapprovalPrefix.$subject;
511            }
512            $previousAmountFmt = $previousAmount !== null ? $this->currency($previousAmount, 1) : null;
513
514            $url = config('app.frontend_url')."{$endpoint}/{$id}?company_id={$companyId}";
515            $href = "<a href='{$url}'>{$quoteId}</a>";
516            $cc = false;
517            foreach ($approvers as $item) {
518
519                $toEmail = $item->email;
520
521                $body = __('language.send_approval_notification.body_hello');
522                $body = str_replace('{{approver}}', $item->name, $body);
523
524                $body .= __('language.send_approval_notification.body_message');
525                $body = str_replace('{{endpoint}}', $fendpoint, $body);
526                $body = str_replace('{{creator}}', $createdBy, $body);
527                $body = str_replace('{{action}}', $action, $body);
528                $body = str_replace('{{company}}', $companyName, $body);
529                $body = str_replace('{{type}}', $budgetType->name, $body);
530                $body = str_replace('{{amount}}', $amount, $body);
531                $body = str_replace('{{quote_id}}', $href, $body);
532
533                if ($isQuestion == 1) {
534                    $body .= __('language.send_approval_notification.note_question');
535                } else {
536                    $body .= __('language.send_approval_notification.note');
537                }
538
539                $body = str_replace('{{company}}', $companyName, $body);
540                $body = str_replace('{{client_type}}', $clientType->name, $body);
541                $body = str_replace('{{project_type}}', $budgetType->name, $body);
542                $body = str_replace('{{amount}}', $minimumOrderSize, $body);
543
544                // E2 (SOP §10): call out that this is a re-approval, with the
545                // previous → new amount when known.
546                if ($isReapproval) {
547                    if ($this->locale == 'es') {
548                        $body .= '<p><b>Re-aprobación:</b> este presupuesto ya había sido aprobado y se ha modificado'
549                            .($previousAmountFmt !== null ? ", el importe pasó de {$previousAmountFmt} a {$amount}" : '')
550                            .'. Requiere una nueva aprobación.</p>';
551                    } else {
552                        $body .= '<p><b>Re-approval:</b> this budget was already approved and has changed'
553                            .($previousAmountFmt !== null ? ", the amount went from {$previousAmountFmt} to {$amount}" : '')
554                            .'. A new approval is required.</p>';
555                    }
556                }
557
558                if ($isQuestion == 1) {
559                    if ($questionIdsNo) {
560                        $questions = TblWorkflowQuestions::whereIn('question_id', $questionIdsNo)->where('company_id', $companyId)->get();
561
562                        if ($questions->isNotEmpty()) {
563                            $ul = '<ul>';
564                            $li = '';
565                            foreach ($questions as $item) {
566                                $li .= "<li>{$item->question}</li>";
567                            }
568                            $ul .= $li.'</ul><br><br>';
569                            $body .= $ul;
570                        }
571                    }
572                }
573
574                $content = $body;
575
576                $body .= '<p>Fire Service Titan</p>';
577                $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
578
579                $html = '<!DOCTYPE html>';
580                $html .= '<html>';
581                $html .= '<head>';
582                $html .= '<meta charset="UTF-8">';
583                $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
584                $html .= '</head>';
585                $html .= '<body>';
586                $html .= $body;
587                $html .= '</body>';
588                $html .= '</html>';
589
590                if ($toEmail != null) {
591                    // $user is the commercial/creator. It can be null when the
592                    // quote came from G3W with a commercial name that doesn't
593                    // map to any tbl_users row. Notification still goes out to
594                    // the technical approver; the BCC to the commercial is
595                    // simply skipped when we don't know who they are.
596                    $userEmail = $user?->email;
597
598                    // FIRE-1229: STG redirects all approval emails to the
599                    // logged-in operator (matches `approve_quotation:572` /
600                    // `reject_quotation:1221` pattern) so the person testing
601                    // sees the result in their inbox. Pre-fix this branch
602                    // redirected to the commercial's email (`$userEmail`),
603                    // which meant a different person received the test email
604                    // depending on the budget's commercial. Falls back to the
605                    // commercial only when there's no authenticated request
606                    // user (e.g. cron-triggered syncs).
607                    if (config('services.sendgrid.staging')) {
608                        $loggedInUserEmail = request()->user()?->email;
609                        if ($loggedInUserEmail) {
610                            $toEmail = $loggedInUserEmail;
611                            $item->user_id = $userId;
612                        } elseif ($userEmail) {
613                            $toEmail = $userEmail;
614                            $item->user_id = $userId;
615                        }
616                    }
617
618                    // BCC list — only attached once (to the first approver),
619                    // not duplicated across multiple approvers.
620                    $bcc = [];
621                    if ($cc == false) {
622                        $cc = true;
623                        if ($userEmail && $userEmail != $toEmail) {
624                            $bcc[] = $userEmail;
625                            if ($userEmail != $commercialEmail && $commercialEmail != null) {
626                                $bcc[] = $commercialEmail;
627                            }
628                        } elseif (! $userEmail && $commercialEmail != null && $commercialEmail != $toEmail) {
629                            // No commercial user in FST but G3W gave us a raw
630                            // email — include it so the (unknown-to-FST) seller
631                            // at least sees the approval request.
632                            $bcc[] = $commercialEmail;
633                        }
634                    }
635
636                    // FIRE-1147: synchronous side effects FIRST (audit log +
637                    // in-app notification), then dispatch the email send.
638                    // Pre-fix these were inside the 202-branch — if SendGrid
639                    // 5xx'd the in-app notification was lost.
640                    $this->addUpdateLog($id, $userId, 'send_approval_notification', null, null, 5);
641
642                    TblNotifications::create(
643                        [
644                            'user_id' => $item->user_id,
645                            'content' => $content,
646                            'is_open' => 1,
647                            'created_by' => 'System',
648                            'link' => $url,
649                        ]
650                    );
651
652                    SendApprovalEmail::dispatch(
653                        toEmail: (string) $toEmail,
654                        subject: $subject,
655                        html: $html,
656                        bcc: $bcc,
657                        quoteId: $quoteId,
658                        companyId: (int) $companyId,
659                    )->onQueue('email');
660                }
661
662            }
663        }
664    }
665
666    public function send_approval_margin_notification($amount, $budgetTypeId, $customerTypeId, $minimumMargin, string $quoteId, $id, $companyName, $createdBy, $userId, $action, $commercialEmail, $invoiceMargin, $companyId, $endpoint): void
667    {
668        // FIRE-1930: same kill switch as send_approval_notification —
669        // margin-related approval requests are part of bucket 2.
670        if (! SendgridDispatcher::isAllowed(
671            SendgridDispatcher::BUCKET_APPROVAL,
672            (int) $companyId,
673        )) {
674            return;
675        }
676
677        if ($action != 1) {
678            if ($this->locale == 'es') {
679                $action = 'actualizado';
680            } else {
681                $action = 'updated';
682            }
683
684        } else {
685            if ($this->locale == 'es') {
686                $action = 'creado';
687            } else {
688                $action = 'created';
689            }
690        }
691
692        $fendpoint = '';
693
694        if ($endpoint == 'orders') {
695            if ($this->locale == 'es') {
696                $fendpoint = 'presupuesto';
697            } else {
698                $fendpoint = 'budget';
699            }
700
701        } else {
702            if ($this->locale == 'es') {
703                $fendpoint = 'trabajo';
704            } else {
705                $fendpoint = 'job';
706            }
707        }
708
709        $invoiceMargin = number_format($invoiceMargin, 2);
710        $minimumMargin = number_format($minimumMargin, 2);
711
712        $user = TblUsers::where('id', $userId)->first();
713
714        $query = "SELECT
715                    a.approver_id,
716                    a.user_id,
717                    b.name,
718                    b.email
719                FROM
720                    tbl_approvers a
721                    INNER JOIN tbl_users b ON a.user_id = b.id
722                WHERE a.company_id = {$companyId}
723                ";
724
725        $approvers = DB::select($query);
726
727        if (count($approvers) > 0) {
728
729            $amount = $this->currency($amount, 1);
730
731            $budgetType = TblBudgetTypes::where('budget_type_id', $budgetTypeId)->first();
732            $clientType = TblCustomerTypes::where('customer_type_id', $customerTypeId)->first();
733
734            $imgpath = file_get_contents(public_path('fireservicetitan.png'));
735            $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
736
737            $subject = __('language.send_approval_margin_notification.subject');
738            $subject = str_replace('{{type}}', $budgetType->name, $subject);
739            $subject = str_replace('{{amount}}', $amount, $subject);
740            $subject = str_replace('{{margin}}', $invoiceMargin, $subject);
741            $subject = str_replace('{{endpoint}}', ucfirst($fendpoint), $subject);
742
743            $url = config('app.frontend_url')."{$endpoint}/{$id}?company_id={$companyId}";
744            $href = "<a href='{$url}'>{$quoteId}</a>";
745            $cc = false;
746            foreach ($approvers as $item) {
747
748                $toEmail = $item->email;
749
750                $body = __('language.send_approval_margin_notification.body_hello');
751                $body = str_replace('{{approver}}', $item->name, $body);
752
753                $body .= __('language.send_approval_margin_notification.body_message');
754                $body = str_replace('{{endpoint}}', $fendpoint, $body);
755                $body = str_replace('{{creator}}', $createdBy, $body);
756                $body = str_replace('{{action}}', $action, $body);
757                $body = str_replace('{{company}}', $companyName, $body);
758                $body = str_replace('{{type}}', $budgetType->name, $body);
759                $body = str_replace('{{amount}}', $amount, $body);
760                $body = str_replace('{{quote_id}}', $href, $body);
761                $body = str_replace('{{margin}}', $invoiceMargin, $body);
762
763                $body .= __('language.send_approval_margin_notification.note');
764                $body = str_replace('{{company}}', $companyName, $body);
765                $body = str_replace('{{client_type}}', $clientType->name, $body);
766                $body = str_replace('{{project_type}}', $budgetType->name, $body);
767                $body = str_replace('{{margin}}', $minimumMargin, $body);
768
769                $content = $body;
770
771                $body .= '<p>Fire Service Titan</p>';
772                $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
773
774                $html = '<!DOCTYPE html>';
775                $html .= '<html>';
776                $html .= '<head>';
777                $html .= '<meta charset="UTF-8">';
778                $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
779                $html .= '</head>';
780                $html .= '<body>';
781                $html .= $body;
782                $html .= '</body>';
783                $html .= '</html>';
784
785                if ($toEmail != null) {
786                    $email = new Mail;
787
788                    if (config('services.sendgrid.staging')) {
789                        $toEmail = $user->email;
790                        $item->user_id = $userId;
791                    }
792
793                    if ($cc == false) {
794                        $cc = true;
795
796                        if ($user->email != $toEmail) {
797                            if ($user->email != $commercialEmail && $commercialEmail != null) {
798                                $email->addBcc($user->email);
799                                $email->addBcc($commercialEmail);
800                            } else {
801                                $email->addBcc($user->email);
802                            }
803                        }
804                    }
805
806                    $email->setFrom('fire@fire.es', 'Fire Service Titan');
807                    $email->setSubject($subject);
808                    $email->addTo($toEmail);
809                    $email->addContent('text/html', $html);
810
811                    $email->addAttachment(
812                        $imgpath,
813                        'image/png',
814                        'fireservicetitan.png',
815                        'inline',
816                        'fireservicetitan'
817                    );
818
819                    $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
820
821                    try {
822                        $response = $sendgrid->send($email);
823                        SendgridLogger::log($email, $response);
824                    } catch (\Throwable $sendException) {
825                        SendgridLogger::logException($email, $sendException);
826                        throw $sendException;
827                    }
828
829                    if ($response->statusCode() == 202) {
830                        Log::channel('email_log')->info('ID:'.$quoteId.' : '.$toEmail.' - MARGIN APPROVAL EMAIL NOTIFICATION SENT');
831
832                        $this->addUpdateLog($quoteId, $userId, 'send_approval_margin_notification', null, null, 5);
833
834                        TblNotifications::create(
835                            [
836                                'user_id' => $item->user_id,
837                                'content' => $content,
838                                'is_open' => 1,
839                                'created_by' => 'System',
840                                'link' => $url,
841                            ]
842                        );
843                    } else {
844                        $error = true;
845                        Log::channel('email_log')->error('ID:'.$quoteId.' : '.$toEmail.' - '.$response->body());
846                    }
847                }
848
849            }
850        }
851    }
852
853    /**
854     * Authorize the logged-in user to approve/reject the given quotation.
855     *
856     * Only an approver of the type the order currently NEEDS, whose slot is
857     * still open, may act:
858     *   - technical (v1, tbl_approvers): type 1 or 3, v1 slot empty
859     *   - financial (v2, tbl_approvers_v2): type 2 (immediately), or type 3
860     *     after the technical slot has approved, v2 slot empty
861     *   (type = approval_type, authoritative; for_approval is only the flag)
862     *
863     * Frontend gating (orders.component) mirrors this, but the UI is
864     * bypassable: without this check a non-approver / wrong-type approver
865     * could hit the endpoint and clear `for_approval` (see the single-level
866     * branch in approve_quotation / reject_quotation) with no approver recorded.
867     */
868    private function isApproverAuthorizedFor($result): bool
869    {
870        return $this->approverActingType($result) !== null;
871    }
872
873    /**
874     * Which approver slot the logged-in user would act on for this order:
875     * 'technical' (tbl_approvers, v1 slot) or 'financial' (tbl_approvers_v2, v2
876     * slot), or null if the user is not an eligible approver with an open slot.
877     * A user present in BOTH tables acts on the technical slot first — mirroring
878     * send_approved/rejected_notification, which treats 'both' as technical.
879     */
880    private function approverActingType($result): ?string
881    {
882        if ($result === null) {
883            return null;
884        }
885
886        $companyId = (int) $result->company_id;
887        $userId = (int) $this->userId;
888
889        $isTechnical = DB::table('tbl_approvers')
890            ->where('company_id', $companyId)
891            ->where('user_id', $userId)
892            ->exists();
893
894        $isFinancial = DB::table('tbl_approvers_v2')
895            ->where('company_id', $companyId)
896            ->where('user_id', $userId)
897            ->exists();
898
899        // The order's required approver type comes from approval_type
900        // (1 = technical, 2 = financial, 3 = both) — the authoritative column,
901        // always written correctly. for_approval is only the "still pending"
902        // flag (non-null while a decision is outstanding). Keying openness off
903        // approval_type also unblocks historical rows saved with a mislabelled
904        // for_approval (financial-only orders were stored as for_approval = 1).
905        // Fall back to for_approval for very old rows with no approval_type.
906        $type = $result->approval_type !== null
907            ? (int) $result->approval_type
908            : (int) $result->for_approval;
909        $pending = $result->for_approval !== null;
910
911        $technicalOpen = $pending
912            && ($type === 1 || $type === 3)
913            && $result->approved_by === null
914            && $result->rejected_by === null;
915
916        // Financial slot opens immediately for a financial-only order, or — in a
917        // dual (both) flow — only AFTER Operations (technical) has approved and
918        // not rejected (sequential Operations → Finance).
919        $financialOpen = $pending && (
920            ($type === 2
921                && $result->approved_by_v2 === null
922                && $result->rejected_by_v2 === null)
923            || ($type === 3
924                && $result->approved_by !== null
925                && $result->rejected_by === null
926                && $result->approved_by_v2 === null
927                && $result->rejected_by_v2 === null)
928        );
929
930        if ($isTechnical && $technicalOpen) {
931            return 'technical';
932        }
933
934        if ($isFinancial && $financialOpen) {
935            return 'financial';
936        }
937
938        return null;
939    }
940
941    /**
942     * FIRE-1572: subtract the approvals that still stand from a fresh engine
943     * requirement, leaving only the dimension(s) that must actually be
944     * (re-)approved.
945     *
946     * The engine is stateless — it re-derives "requires financial" from
947     * `amount >= financial threshold` every time it runs — so on a budget that
948     * was already approved, editing an unrelated figure used to re-request both
949     * levels. An approval only becomes stale when one of ITS OWN inputs moves:
950     *   financial ← amount
951     *   technical ← amount, invoice margin, revenue/employee/day, the
952     *               margin-tracking flag, the questionnaire
953     * A budget/customer type change re-selects the matrix row, so it
954     * invalidates both.
955     *
956     * The margin/revenue inputs only count while the engine's revenue gate is
957     * open ($financialMinimumsApply — see ApprovalThresholdEngine). Below the
958     * row's `min_amount_for_margin_check` those figures cannot change the
959     * requirement, so editing the margin on a small budget that is pending for
960     * another reason (questionnaire) must not re-request the technical approval.
961     *
962     * Shared by the save (update_quotation), the preview the amount field calls
963     * (preview_approval) and therefore the red "requires approval" warning, so
964     * all three agree on what would be asked of whom.
965     *
966     * @param  array<string, mixed>  $d  Post-edit values
967     * @param  object|null  $row  Current DB row, null for a brand-new budget
968     * @param  bool  $financialMinimumsApply  engine revenue gate state; true keeps
969     *                                        the pre-gate behaviour for callers
970     *                                        that have no engine result
971     * @return array{tech: bool, fin: bool}
972     */
973    private function pendingApprovalDimensions(array $d, $row, bool $reqTech, bool $reqFin, bool $questionInputsChanged = false, bool $financialMinimumsApply = true): array
974    {
975        if ($row === null) {
976            return ['tech' => $reqTech, 'fin' => $reqFin];
977        }
978
979        $changed = fn (string $field) => array_key_exists($field, $d) && $row->{$field} != $d[$field];
980
981        $rowKeyChanged = $changed('budget_type_id') || $changed('customer_type_id');
982        $finInputsChanged = $rowKeyChanged || $changed('amount');
983        $marginInputsChanged = $financialMinimumsApply && (
984            $changed('invoice_margin')
985            || $changed('budget_margin_enabled')
986            || $changed('revenue_per_date_per_worked')
987        );
988        $techInputsChanged = $finInputsChanged
989            || $marginInputsChanged
990            || $questionInputsChanged;
991
992        // Already granted + its own inputs untouched ⇒ still valid, not re-asked.
993        $techStillApproved = $reqTech && $row->approved_by !== null && ! $techInputsChanged;
994        $finStillApproved = $reqFin && $row->approved_by_v2 !== null && ! $finInputsChanged;
995
996        return [
997            'tech' => $reqTech && ! $techStillApproved,
998            'fin' => $reqFin && ! $finStillApproved,
999        ];
1000    }
1001
1002    /**
1003     * Record an approve/reject decision on the slot the user is ACTING on.
1004     *
1005     * The slot must follow `approverActingType()` (which authorized the click),
1006     * never the approver's table membership: a user who sits in both
1007     * `tbl_approvers` and `tbl_approvers_v2` was previously always written to
1008     * the technical slot, so on a dual budget the financial slot never filled
1009     * and the circuit could never complete ("approved but still pending").
1010     *
1011     * Owned by the controller, not by the notification methods — the decision
1012     * is authoritative state and must land even when no email can be sent
1013     * (e.g. G3W rows whose created_by/commercial match no tbl_users row).
1014     */
1015    private function recordApprovalDecision($id, ?string $actingType, bool $approved): void
1016    {
1017        $name = TblUsers::where('id', $this->userId)->value('name') ?? 'System';
1018        $now = date('Y-m-d H:i:s');
1019
1020        // Unknown acting type (legacy/edge): fall back to the technical slot,
1021        // the historical default — better a recorded decision than none.
1022        $financial = $actingType === 'financial';
1023
1024        $column = $approved
1025            ? ($financial ? ['approved_at_v2' => $now, 'approved_by_v2' => $name] : ['approved_at' => $now, 'approved_by' => $name])
1026            : ($financial ? ['rejected_at_v2' => $now, 'rejected_by_v2' => $name] : ['rejected_at' => $now, 'rejected_by' => $name]);
1027
1028        TblQuotations::where('id', $id)->update($column);
1029    }
1030
1031    /**
1032     * A recorded decision means the budget is NOT pending any more.
1033     *
1034     * Clears `for_approval` + `approval_type` as soon as the circuit is
1035     * satisfied, matched per dimension against the required type:
1036     *   - any rejection ends it immediately (SOP §15)
1037     *   - technical (1) needs the V1 slot, financial (2) needs V2, dual (3) both
1038     *   - unclassified (no type at all) accepts either slot
1039     *
1040     * Per-dimension matching matters since FIRE-1572: an edit re-requests only
1041     * the dimension whose inputs changed and deliberately KEEPS the other
1042     * dimension's approval, so a type-1 pending row can legitimately carry an
1043     * older V2 approval. Counting that as satisfaction would cancel a technical
1044     * approval that nobody has given.
1045     *
1046     * The post-decision state is computed from the PRE-decision row plus the
1047     * decision just recorded, deliberately NOT by re-reading the row: a stale
1048     * read-back would silently skip the clear, which is the "approved but still
1049     * pending" stranding this exists to prevent.
1050     *
1051     * Returns true when the budget was cleared, false when it is legitimately
1052     * still pending (dual circuit waiting on its second approver).
1053     */
1054    private function clearApprovalIfDecided($id, $preRow, ?string $actingType, bool $approved): bool
1055    {
1056        $financial = $actingType === 'financial';
1057
1058        $approvedTech = $preRow->approved_by !== null || ($approved && ! $financial);
1059        $approvedFin = $preRow->approved_by_v2 !== null || ($approved && $financial);
1060        // Any rejection — the one just recorded or an earlier one — is final.
1061        $rejected = ! $approved
1062            || $preRow->rejected_by !== null
1063            || $preRow->rejected_by_v2 !== null;
1064
1065        $type = $preRow->approval_type !== null
1066            ? (int) $preRow->approval_type
1067            : (int) $preRow->for_approval;
1068
1069        $decided = $rejected || match ($type) {
1070            1 => $approvedTech,
1071            2 => $approvedFin,
1072            3 => $approvedTech && $approvedFin,
1073            // No usable type recorded — any approval closes it.
1074            default => $approvedTech || $approvedFin,
1075        };
1076
1077        if (! $decided) {
1078            return false;
1079        }
1080
1081        TblQuotations::where('id', $id)->update(['for_approval' => null, 'approval_type' => null]);
1082
1083        return true;
1084    }
1085
1086    public function approve_quotation($id): ResponseFactory|HttpResponse
1087    {
1088
1089        try {
1090
1091            $id = addslashes((string) $id);
1092
1093            $result = TblQuotations::where('id', $id)->first();
1094            $company = TblCompanies::where('company_id', $result->company_id)->first();
1095            $budgetType = TblBudgetTypes::where('budget_type_id', $result->budget_type_id)->first();
1096
1097            // FIRE-1092: G3W-imported quotes commonly have budget_type_id=NULL
1098            // (mapping not yet resolved), so the TblBudgetTypes lookup returns
1099            // null and the downstream `$budgetType->name` crashes. Same risk
1100            // on $company if the company was renamed/deleted. Fall back to a
1101            // safe placeholder for the notification body; it's purely
1102            // informational and the approval still proceeds.
1103            $companyName = $company?->name ?? '—';
1104            $budgetTypeName = $budgetType?->name ?? '—';
1105            $companyIdForNotification = $company?->company_id ?? $result->company_id;
1106
1107            // Only the approver type the order needs (with an open slot) may act.
1108            if (! $this->isApproverAuthorizedFor($result)) {
1109                return response(['message' => 'KO', 'error' => __('language.approval_not_authorized')]);
1110            }
1111
1112            // Which slot this user is acting on (technical v1 / financial v2),
1113            // read from the PRE-decision row.
1114            $actingType = $this->approverActingType($result);
1115
1116            // Record the decision FIRST and unconditionally: it is authoritative
1117            // state, so it must not depend on an email/in-app write succeeding
1118            // (the FIRE-324 stranding class) nor on the creator/commercial
1119            // resolving to a tbl_users row (common on G3W-imported quotes).
1120            $this->recordApprovalDecision($id, $actingType, true);
1121
1122            // Dual-level approval email timing: tell the creator/commercial the
1123            // budget is "approved" only when THIS action completes the circuit.
1124            // approval_type is the authoritative required-type column
1125            // (for_approval is just the pending flag and was historically
1126            // mislabelled), and $result is the pre-decision row, so a dual
1127            // budget is final here only if the other slot was already filled.
1128            $requiredType = $result->approval_type !== null
1129                ? (int) $result->approval_type
1130                : (int) $result->for_approval;
1131            $priorApproved = ($result->approved_by !== null ? 1 : 0)
1132                + ($result->approved_by_v2 !== null ? 1 : 0);
1133            $isFinalApproval = $requiredType !== 3 || $priorApproved >= 1;
1134
1135            // Best-effort notifications, isolated so a failure here can never
1136            // block the state transition below.
1137            try {
1138                if ($result->created_by != $result->commercial) {
1139                    $creatorAndCommercial = [$result->created_by, $result->commercial];
1140                    foreach ($creatorAndCommercial as $name) {
1141                        $user = TblUsers::where('name', $name)->first();
1142                        if ($user) {
1143                            $this->send_approved_notification($user->id, $user->name, $user->email, $companyName, $budgetTypeName, $result->amount, $id, $result->quote_id, $companyIdForNotification, 'orders', $isFinalApproval, $actingType);
1144                        }
1145                    }
1146                } else {
1147                    $user = TblUsers::where('name', $result->created_by)->first();
1148                    if ($user) {
1149                        $this->send_approved_notification($user->id, $user->name, $user->email, $companyName, $budgetTypeName, $result->amount, $id, $result->quote_id, $companyIdForNotification, 'orders', $isFinalApproval, $actingType);
1150                    }
1151                }
1152            } catch (\Throwable $e) {
1153                report(AppException::fromException($e, 'APPROVE_QUOTATION_NOTIFY_EXCEPTION'));
1154            }
1155
1156            // Decision recorded → drop the pending flags unless a dual circuit
1157            // is genuinely still waiting on its second approver.
1158            if (! $this->clearApprovalIfDecided($id, $result, $actingType, true)) {
1159                // Still pending: this was the technical (Operations) approval of a
1160                // dual circuit, so Finance's slot has just opened → notify Finance
1161                // now. This is the ONLY point Finance receives the request; the
1162                // initial confirm only ever emailed Operations. (Sequential
1163                // Operations → Finance.)
1164                if ($actingType !== 'financial') {
1165                    // Best-effort, like every other notification here: the
1166                    // approval is already recorded, so a SendGrid/eval failure
1167                    // must not turn a successful approval into a KO response.
1168                    try {
1169                        $evalFin = $this->evaluateApprovalForBudget($result->getAttributes(), $company);
1170                        $conditionsFin = ($evalFin['matched'] ?? false) ? [
1171                            'technical' => $evalFin['technicalThreshold'],
1172                            'financial' => $evalFin['financialThreshold'],
1173                            'minMargin' => $evalFin['minInvoiceMargin'],
1174                            'minRevenue' => $evalFin['minRevenuePerEmployeeDay'],
1175                            'generalCosts' => $evalFin['generalCosts'],
1176                        ] : null;
1177                        $this->sendApprovalEmailV2($result, $company, ['financial'], false, $result->importe_avisado, $conditionsFin);
1178                        $this->addUpdateLog($id, $this->userId, 'send_approval_notification', null, null, 5);
1179                    } catch (\Throwable $e) {
1180                        report(AppException::fromException($e, 'APPROVE_QUOTATION_FINANCE_NOTIFY_EXCEPTION'));
1181                    }
1182                }
1183            }
1184
1185            // FIRE-1092: log the APPROVER (the user clicking the button) as
1186            // the actor — that's the only id guaranteed to exist for this
1187            // request. Pre-fix the code wrote `$user->id`, but `$user` was
1188            // the creator/commercial Eloquent lookup that returns null when
1189            // `created_by`/`commercial` doesn't match any `tbl_users.name`
1190            // (very common on G3W-imported rows where `created_by = 'Zala'`
1191            // or `'System'`). Result: every approve attempt on those quotes
1192            // threw "Attempt to read property 'id' on null".
1193            $this->addUpdateLog($id, $this->userId, 'approve_quotation', null, null, 5);
1194
1195            // FIRE-1145: was Cache::flush() — approval affects list_quotations + commercial counters.
1196            ResultCache::forgetDomain(['quotations', 'users']);
1197
1198            // Return the post-action `for_approval` so the frontend can tell
1199            // single-level "fully approved" from dual-level "still waiting on
1200            // the other approver" and show the right toast.
1201            $postState = TblQuotations::where('id', $id)->first();
1202
1203            return response(['message' => 'OK', 'for_approval' => $postState?->for_approval]);
1204
1205        } catch (\Exception $e) {
1206            report(AppException::fromException($e, 'APPROVE_QUOTATION_EXCEPTION'));
1207
1208            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1209        }
1210
1211    }
1212
1213    /**
1214     * Shared Titan email shell (SOP §10 look) — Outlook-classic compatible:
1215     * table layout, inline styles, no flexbox; a bgcolor status tag, an optional
1216     * bgcolor CTA button, and the logo as a cid inline image. Used by the
1217     * approved / rejected notifications so they match the redesigned E1/E2.
1218     */
1219    private function buildTitanEmailCard(string $tagText, string $tagColor, string $tagBg, string $heading, string $bodyHtml, ?string $url = null, ?string $ctaLabel = null): string
1220    {
1221        $cta = ($url && $ctaLabel)
1222            ? '<table role="presentation" cellpadding="0" cellspacing="0" style="margin:4px 0 6px;"><tr>'
1223                ."<td bgcolor=\"#556ee6\" style=\"padding:10px 18px;\"><a href=\"{$url}\" style=\"color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:bold;text-decoration:none;\">{$ctaLabel}</a></td>"
1224                .'</tr></table>'
1225            : '';
1226
1227        $card = '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f5f7;"><tr><td align="center" style="padding:20px;">'
1228            .'<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="width:480px;max-width:480px;background:#ffffff;border:1px solid #e5e7eb;">'
1229            .'<tr><td style="padding:20px;font-family:Arial,Helvetica,sans-serif;color:#1f2937;font-size:14px;">'
1230            ."<div style=\"font-size:16px;font-weight:bold;margin:0 0 10px;\">{$heading}</div>"
1231            .'<table role="presentation" cellpadding="0" cellspacing="0"><tr>'
1232            ."<td bgcolor=\"{$tagBg}\" style=\"padding:3px 9px;font-size:11px;font-weight:bold;color:{$tagColor};font-family:Arial,Helvetica,sans-serif;\">{$tagText}</td>"
1233            .'</tr></table>'
1234            ."<div style=\"margin:14px 0 12px;line-height:1.5;\">{$bodyHtml}</div>"
1235            .$cta
1236            .'<img src="cid:fireservicetitan" alt="Fire Service Titan" width="150" style="display:block;height:auto;border:0;outline:none;text-decoration:none;margin-top:14px;" />'
1237            .'</td></tr></table>'
1238            .'</td></tr></table>';
1239
1240        return '<!DOCTYPE html><html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body style="margin:0;padding:0;background:#f4f5f7;">'.$card.'</body></html>';
1241    }
1242
1243    /**
1244     * @param  string|null  $actingType  When non-null ('technical'/'financial') the
1245     *                                   caller already recorded the approval slot
1246     *                                   (see recordApprovalDecision) and this method
1247     *                                   must not write it again. Null keeps the
1248     *                                   legacy self-recording behaviour used by the
1249     *                                   OngoingJobs callers.
1250     */
1251    public function send_approved_notification($userId, $username, $email, $companyName, $budgetType, $amount, $id, string $quoteId, $companyId, $endpoint, bool $isFinal = true, ?string $actingType = null): void
1252    {
1253
1254        $fendpoint = '';
1255
1256        if ($endpoint == 'orders') {
1257            if ($this->locale == 'es') {
1258                $fendpoint = 'presupuesto';
1259            } else {
1260                $fendpoint = 'budget';
1261            }
1262
1263        } else {
1264            if ($this->locale == 'es') {
1265                $fendpoint = 'trabajo';
1266            } else {
1267                $fendpoint = 'job';
1268            }
1269        }
1270
1271        $query = "SELECT
1272                    u.id AS user_id,
1273                    u.name,
1274                    u.email,
1275                    u.sender_email,
1276                    CASE
1277                        WHEN a.user_id IS NOT NULL AND c.user_id IS NOT NULL THEN 'both'
1278                        WHEN a.user_id IS NOT NULL THEN 'approvers'
1279                        WHEN c.user_id IS NOT NULL THEN 'approvers_v2'
1280                        ELSE 'none'
1281                    END AS exists_in
1282                FROM tbl_users u
1283                LEFT JOIN tbl_approvers a
1284                    ON u.id = a.user_id AND a.company_id = {$companyId}
1285                LEFT JOIN tbl_approvers_v2 c
1286                    ON u.id = c.user_id AND c.company_id = {$companyId}
1287                WHERE u.id = {$this->userId}";
1288
1289        $user = DB::select($query);
1290
1291        $user = $user[0] ?? null;
1292
1293        // FIRE-1092: if the logged-in user isn't in tbl_users for any reason,
1294        // bail before downstream `$user->exists_in` / `$user->name` reads
1295        // null-deref. The caller (`approve_quotation`) doesn't care about
1296        // the return value, so silently skipping is acceptable; the audit
1297        // log entry in the caller still records the action.
1298        if ($user === null) {
1299            Log::channel('email_log')->warning("send_approved_notification: logged-in user {$this->userId} not found in tbl_users; skipping notification for quote {$quoteId}.");
1300
1301            return;
1302        }
1303
1304        $toEmail = $email;
1305
1306        $amount = $this->currency($amount, 1);
1307
1308        $imgpath = file_get_contents(public_path('fireservicetitan.png'));
1309        $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
1310
1311        $url = config('app.frontend_url')."{$endpoint}/{$id}?company_id={$companyId}";
1312        $href = "<a href='{$url}'>{$quoteId}</a>";
1313
1314        $body = __('language.send_approved_notification.body_hello');
1315        $body = str_replace('{{creator}}', $username, $body);
1316
1317        $body .= __('language.send_approved_notification.body_message');
1318        $body = str_replace('{{approver}}', $user->name, $body);
1319        $body = str_replace('{{company}}', $companyName, $body);
1320        $body = str_replace('{{type}}', $budgetType, $body);
1321        $body = str_replace('{{amount}}', $amount, $body);
1322        $body = str_replace('{{quote_id}}', $href, $body);
1323        $body = str_replace('{{endpoint}}', $fendpoint, $body);
1324
1325        $content = $body;
1326
1327        // SOP §10 redesigned shell (was the old plain body + inline logo).
1328        $html = $this->buildTitanEmailCard(
1329            $this->locale == 'es' ? 'Aprobado' : 'Approved',
1330            '#199a72',
1331            '#e4f7f0',
1332            $this->locale == 'es' ? 'Presupuesto aprobado' : 'Budget approved',
1333            $content,
1334            $url,
1335            ($this->locale == 'es' ? 'Ver ' : 'Open ').$fendpoint,
1336        );
1337
1338        $subject = __('language.send_approved_notification.subject');
1339        $subject = str_replace('{{quote_id}}', $quoteId, $subject);
1340        $subject = str_replace('{{endpoint}}', ucfirst($fendpoint), $subject);
1341
1342        // FIRE-1092: record the approval action FIRST, independently of
1343        // whether the notification email succeeds.
1344        //
1345        // For orders the caller (approve_quotation) now owns this write and
1346        // passes $actingType — the slot it authorized. Deriving the slot from
1347        // `exists_in` here was wrong for a user in BOTH approver tables: 'both'
1348        // always wrote the technical slot, so on a dual budget the financial
1349        // slot never filled, the circuit never completed, and the quote sat
1350        // "approved but still pending" forever.
1351        if ($endpoint == 'orders') {
1352            if ($actingType === null) {
1353                if ($user->exists_in == 'approvers' || $user->exists_in == 'both') {
1354                    TblQuotations::where('id', $id)->update([
1355                        'approved_at' => date('Y-m-d H:i:s'),
1356                        'approved_by' => $user->name,
1357                    ]);
1358                } elseif ($user->exists_in == 'approvers_v2') {
1359                    TblQuotations::where('id', $id)->update([
1360                        'approved_at_v2' => date('Y-m-d H:i:s'),
1361                        'approved_by_v2' => $user->name,
1362                    ]);
1363                }
1364            }
1365        } else {
1366            TblOngoingJobs::where('id', $id)->update([
1367                'approved_at' => date('Y-m-d H:i:s'),
1368                'approved_by' => $user->name,
1369            ]);
1370        }
1371
1372        // Dual-level approval email timing: the approval record above is written
1373        // on EVERY approval action (so the "who approved" state is always
1374        // correct), but the creator/commercial must only be told the budget is
1375        // "approved" once BOTH levels have approved. When this is the first of
1376        // two required approvals (for_approval == 3), $isFinal is false and we
1377        // stop here — no premature in-app notification and no email. The second
1378        // (completing) approver's action sends it. Single-level approvals pass
1379        // $isFinal = true, so their behaviour is unchanged.
1380        if (! $isFinal) {
1381            return;
1382        }
1383
1384        TblNotifications::create([
1385            'user_id' => $userId,
1386            'content' => $content,
1387            'is_open' => 1,
1388            'created_by' => 'System',
1389            'link' => $url,
1390        ]);
1391
1392        $this->addUpdateLog($id, $userId, 'send_approved_notification', null, null, 5);
1393
1394        // FIRE-1147: dispatch the email send to the queue. The approval
1395        // record + in-app notification at L893-928 already landed
1396        // synchronously, so even if SendGrid is down the action is recorded.
1397        // The duplicate side-effect block that previously fired on 202 is
1398        // deleted — it re-wrote rows we already wrote above.
1399        if ($toEmail != null) {
1400            if (config('services.sendgrid.staging')) {
1401                // Staging: route to the fixed test inbox (SENDGRID_TO_EMAIL) so the
1402                // tester receives it regardless of which user they've switched to.
1403                // Previously this used the User-Id-header user ($user) — the ACTING
1404                // APPROVER — so on a financial approval (after switching user) the
1405                // "approved" email went to the approver's placeholder address
1406                // instead of the tester. Falls back to the authenticated user, then
1407                // $user, when no test inbox is configured.
1408                $toEmail = config('services.sendgrid.to_email')
1409                    ?: request()->user()?->email ?: $user->email;
1410            }
1411
1412            SendApprovedEmail::dispatch(
1413                toEmail: (string) $toEmail,
1414                subject: $subject,
1415                html: $html,
1416                quoteId: $quoteId,
1417                companyId: (int) $companyId,
1418            )->onQueue('email');
1419        }
1420
1421    }
1422
1423    public function reject_quotation(Request $request, $id): ResponseFactory|HttpResponse
1424    {
1425
1426        try {
1427
1428            $id = addslashes((string) $id);
1429
1430            // The rejecter writes a free-text reason that is forwarded to the
1431            // sales rep (creator/commercial) in the rejection notification.
1432            $reason = trim((string) $request->input('reason', ''));
1433
1434            $result = TblQuotations::where('id', $id)->first();
1435            $company = TblCompanies::where('company_id', $result->company_id)->first();
1436            $budgetType = TblBudgetTypes::where('budget_type_id', $result->budget_type_id)->first();
1437
1438            // FIRE-1092: same null guards as approve_quotation. budget_type_id
1439            // is often NULL on G3W-imported quotes; pre-fix the call to
1440            // send_rejected_notification crashed with "name on null".
1441            $companyName = $company?->name ?? '—';
1442            $budgetTypeName = $budgetType?->name ?? '—';
1443            $companyIdForNotification = $company?->company_id ?? $result->company_id;
1444
1445            // Only the approver type the order needs (with an open slot) may act.
1446            if (! $this->isApproverAuthorizedFor($result)) {
1447                return response(['message' => 'KO', 'error' => __('language.approval_not_authorized')]);
1448            }
1449
1450            // Which approver type is acting (technical/financial), captured from the
1451            // pre-action row — used to label the comment and, below, to drop the
1452            // other approver's now-stale approval.
1453            $actingType = $this->approverActingType($result);
1454
1455            // Prefix the rejection comment with the approver type that rejected. The
1456            // same augmented text is e-mailed to the commercial and stored in the log.
1457            $roleLine = $actingType === 'technical'
1458                ? __('language.reject_by_technical')
1459                : ($actingType === 'financial' ? __('language.reject_by_finance') : '');
1460            $commentReason = $reason;
1461            if ($roleLine !== '') {
1462                $commentReason = $reason !== '' ? $roleLine."\n".$reason : $roleLine;
1463            }
1464
1465            // Also record the rejection on the order's running comment
1466            // (last_follow_up_comment) so it's visible on the order itself —
1467            // same convention as the other actions that append a dated line.
1468            $rejecterName = TblUsers::where('id', $this->userId)->value('name') ?? 'System';
1469            $commentLine = ($roleLine !== '' ? $roleLine : 'Rechazado')
1470                .' el '.date('Y-m-d H:i:s').' por el usuario '.$rejecterName
1471                .($reason !== '' ? '. '.__('language.send_rejected_notification.reason').' '.$reason : '');
1472            $existingComment = (string) ($result->last_follow_up_comment ?? '');
1473            TblQuotations::where('id', $id)->update([
1474                'last_follow_up_comment' => $existingComment !== '' ? $existingComment."\n".$commentLine : $commentLine,
1475            ]);
1476
1477            // Record the rejection FIRST and unconditionally — same rationale as
1478            // approve_quotation: authoritative state must not ride on an email.
1479            $this->recordApprovalDecision($id, $actingType, false);
1480
1481            // Best-effort notifications, isolated so a failure here can never
1482            // block the state transition below.
1483            try {
1484                if ($result->created_by != $result->commercial) {
1485                    $creatorAndCommercial = [$result->created_by, $result->commercial];
1486                    foreach ($creatorAndCommercial as $name) {
1487                        $user = TblUsers::where('name', $name)->first();
1488                        if ($user) {
1489                            $this->send_rejected_notification($user->id, $user->name, $user->email, $companyName, $budgetTypeName, $result->amount, $id, $result->quote_id, $companyIdForNotification, 'orders', $commentReason, $actingType);
1490                        }
1491                    }
1492                } else {
1493                    $user = TblUsers::where('name', $result->created_by)->first();
1494                    if ($user) {
1495                        $this->send_rejected_notification($user->id, $user->name, $user->email, $companyName, $budgetTypeName, $result->amount, $id, $result->quote_id, $companyIdForNotification, 'orders', $commentReason, $actingType);
1496                    }
1497                }
1498            } catch (\Throwable $e) {
1499                report(AppException::fromException($e, 'REJECT_QUOTATION_NOTIFY_EXCEPTION'));
1500            }
1501
1502            // Sequential (Operations → Finance): a rejection by EITHER Operations
1503            // (technical) or Finance (financial) ends the circuit immediately →
1504            // No aprobado. In particular, an Operations rejection must NEVER
1505            // advance the quote to Finance. The rejected_by/rejected_by_v2 slot
1506            // recorded above drives the "No aprobado" state once the pending
1507            // flags are cleared. (SOP §15.)
1508            $this->clearApprovalIfDecided($id, $result, $actingType, false);
1509
1510            // FIRE-1092: log the REJECTER (the logged-in user) as the actor,
1511            // not the creator/commercial — see the matching comment in
1512            // approve_quotation. `$user` can be null when `created_by` or
1513            // `commercial` don't match a `tbl_users.name`.
1514            // Record the rejection reason as the log's new value so it stays
1515            // traceable in the quotation change log.
1516            $this->addUpdateLog($id, $this->userId, 'reject_quotation', null, $commentReason !== '' ? $commentReason : null, 5);
1517
1518            // FIRE-1145: was Cache::flush() — rejection affects list_quotations + commercial counters.
1519            ResultCache::forgetDomain(['quotations', 'users']);
1520
1521            // Mirror approve_quotation: return post-action `for_approval` so
1522            // the frontend can distinguish "fully decided" from "still
1523            // waiting on the other approver" when showing the success toast.
1524            $postState = TblQuotations::where('id', $id)->first();
1525
1526            return response(['message' => 'OK', 'for_approval' => $postState?->for_approval]);
1527
1528        } catch (\Exception $e) {
1529            report(AppException::fromException($e, 'REJECT_QUOTATION_EXCEPTION'));
1530
1531            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1532        }
1533
1534    }
1535
1536    /**
1537     * Approval circuit v2 (SOP §5) — confirmation gate, part 1: PREVIEW.
1538     *
1539     * Given a budget's draft numbers, returns whether it would require approval
1540     * (technical / financial), the bridged `approvalType`, and the approver(s)
1541     * it would go to. The frontend calls this when the comercial hits "listo
1542     * para enviar" to decide whether to show the confirmation modal and what to
1543     * display. Read-only: it never writes or sends anything.
1544     */
1545    public function preview_approval(Request $request): ResponseFactory|HttpResponse
1546    {
1547        $data = $request->all();
1548        $companyId = (int) ($data['company_id'] ?? 0);
1549        $company = TblCompanies::where('company_id', $companyId)->first();
1550
1551        // Authoritative, flag- and hybrid-aware decision (same logic the save
1552        // uses). `matched` is true only when the matrix engine actually governs
1553        // this budget (flag on AND a matrix row exists); when false the caller
1554        // should keep the legacy client-side warning instead.
1555        $eval = $this->evaluateApprovalForBudget($data, $company);
1556
1557        // FIRE-1572: `reqTechnical` / `reqFinancial` are the raw threshold
1558        // decision — stateless, so an already-approved budget keeps reporting
1559        // "requires approval" merely for being over the threshold. Retyping the
1560        // same 15.000 € that both approvers already signed off lit up the red
1561        // warning under the amount field. When the caller identifies the budget
1562        // (`id`), also return what would ACTUALLY be requested on save: the raw
1563        // requirement minus the approvals that still stand.
1564        $pendingTech = $eval['reqTechnical'];
1565        $pendingFin = $eval['reqFinancial'];
1566
1567        if ($eval['matched'] && ! empty($data['id'])) {
1568            $row = TblQuotations::where('id', $data['id'])->first();
1569            if ($row) {
1570                $pending = $this->pendingApprovalDimensions($data, $row, $eval['reqTechnical'], $eval['reqFinancial'], false, $eval['financialMinimumsApplied']);
1571                $pendingTech = $pending['tech'];
1572                $pendingFin = $pending['fin'];
1573            }
1574        }
1575
1576        $eval['pendingTechnical'] = $pendingTech;
1577        $eval['pendingFinancial'] = $pendingFin;
1578        $eval['pendingApproval'] = $pendingTech || $pendingFin;
1579
1580        return response([
1581            'message' => 'OK',
1582            'engineActive' => (bool) config('approvals.use_matrix_engine'),
1583            'approval' => $eval,
1584            'approvers' => $this->resolveApprovers($companyId, $pendingTech, $pendingFin),
1585        ]);
1586    }
1587
1588    /**
1589     * Approval circuit v2 (SOP §5) — confirmation gate, part 2: CONFIRM.
1590     *
1591     * Called only after the comercial confirms the modal. Re-evaluates the
1592     * saved budget with the engine (never trusts the client), and if it still
1593     * requires approval, marks it Pendiente (`for_approval` + `approval_type`),
1594     * stamps `importe_avisado`, resets any stale approve/reject slots and sends
1595     * the approval email (E1). If it no longer requires approval, it just
1596     * clears the flags. This is the ONLY place a v2 approval request is sent.
1597     */
1598    public function confirm_approval_request(Request $request, $id): ResponseFactory|HttpResponse
1599    {
1600        try {
1601            $result = TblQuotations::where('id', $id)->first();
1602            if (! $result) {
1603                return response(['message' => 'KO', 'error' => 'not_found']);
1604            }
1605
1606            $company = TblCompanies::where('company_id', $result->company_id)->first();
1607
1608            // Resolve the requirement. Draft-until-confirm (engine path) leaves
1609            // for_approval null on save, so re-evaluate here — authoritative,
1610            // never trusting the client. The legacy path already recorded
1611            // for_approval on save, so we honour that directly.
1612            $forApproval = $result->for_approval;
1613            $approvalType = $result->approval_type;
1614            $eval = null;
1615
1616            if ($forApproval === null) {
1617                $eval = $this->evaluateApprovalForBudget($result->getAttributes(), $company);
1618                if (! $eval['requiresApproval']) {
1619                    // Corrected below threshold before confirming → nothing to send.
1620                    return response(['message' => 'OK', 'requiresApproval' => false, 'for_approval' => null]);
1621                }
1622                // for_approval mirrors the type (1 = technical, 2 = financial,
1623                // 3 = both). Do NOT collapse financial-only to 1 — that mislabels
1624                // the order as technical and blocks the financial approver.
1625                $forApproval = $eval['approvalType'];
1626                $approvalType = $eval['approvalType'];
1627            }
1628
1629            // E2 (re-approval) when this budget had already been approved.
1630            $isReapproval = $result->approved_at !== null || $result->approved_at_v2 !== null;
1631            $previousAmount = $result->importe_avisado; // for the X→Y line in E2
1632
1633            // Mark Pendiente and reset the prior decision slots (revert on
1634            // re-approval). This is the only place a v2 request is emailed.
1635            //
1636            // FIRE-1572: scoped to the dimension(s) being requested. On a
1637            // technical-only re-request (the save decided Finance's approval still
1638            // stands because the amount didn't change) the V2 slot must survive,
1639            // otherwise the circuit demands both approvals again.
1640            $update = [
1641                'for_approval' => $forApproval,
1642                'approval_type' => $approvalType,
1643                'importe_avisado' => $result->amount,
1644                'approval_requested_at' => now(),
1645                'approval_last_reminded_at' => null,
1646            ];
1647
1648            $requestedType = (int) $approvalType;
1649
1650            if ($requestedType === 1 || $requestedType === 3) {
1651                $update += [
1652                    'approved_at' => null, 'approved_by' => null,
1653                    'rejected_at' => null, 'rejected_by' => null,
1654                ];
1655            }
1656
1657            if ($requestedType === 2 || $requestedType === 3) {
1658                $update += [
1659                    'approved_at_v2' => null, 'approved_by_v2' => null,
1660                    'rejected_at_v2' => null, 'rejected_by_v2' => null,
1661                ];
1662            }
1663
1664            TblQuotations::where('id', $id)->update($update);
1665
1666            // Sequential workflow (Operations → Finance): the FIRST request always
1667            // goes to the technical approver (Operaciones) when technical approval
1668            // is required. Finance (financial) is notified later, only after
1669            // Operations approves (see approve_quotation). A financial-only budget
1670            // notifies Finance directly.
1671            if ($eval !== null && $eval['matched']) {
1672                $dimensions = $eval['reqTechnical'] ? ['technical'] : ['financial'];
1673                $conditions = [
1674                    'technical' => $eval['technicalThreshold'],
1675                    'financial' => $eval['financialThreshold'],
1676                    'minMargin' => $eval['minInvoiceMargin'],
1677                    'minRevenue' => $eval['minRevenuePerEmployeeDay'],
1678                    'generalCosts' => $eval['generalCosts'],
1679                ];
1680            } else {
1681                // Legacy path (engine not governing, or for_approval already
1682                // persisted on save so $eval is null). Route off the authoritative
1683                // approval_type: financial-only (2) e-mails Finance directly;
1684                // technical (1) and dual (3) e-mail Operations first (dual advances
1685                // to Finance in approve_quotation once Operations approves).
1686                // Previously this hard-coded ['technical'], so a financial-only
1687                // budget's approvers (tbl_approvers_v2) were never notified.
1688                $dimensions = ((int) $approvalType === 2) ? ['financial'] : ['technical'];
1689                $conditions = null;
1690            }
1691
1692            // SOP §10 redesigned E1/E2 email (per-dimension technical/financial).
1693            $this->sendApprovalEmailV2($result, $company, $dimensions, $isReapproval, $previousAmount, $conditions);
1694
1695            $this->addUpdateLog($id, $this->userId, 'send_approval_notification', null, null, 5);
1696            ResultCache::forgetDomain(['quotations', 'users']);
1697
1698            return response([
1699                'message' => 'OK',
1700                'requiresApproval' => true,
1701                'for_approval' => $forApproval,
1702                'approval_type' => $approvalType,
1703                'isReapproval' => $isReapproval,
1704            ]);
1705        } catch (\Exception $e) {
1706            report(AppException::fromException($e, 'CONFIRM_APPROVAL_REQUEST_EXCEPTION'));
1707
1708            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1709        }
1710    }
1711
1712    /** Resolve the approver users for each required dimension (V1 technical / V2 financial). */
1713    private function resolveApprovers(int $companyId, bool $reqTechnical, bool $reqFinancial): array
1714    {
1715        $query = function (string $table) use ($companyId) {
1716            return DB::table($table.' as a')
1717                ->join('tbl_users as u', 'a.user_id', '=', 'u.id')
1718                ->where('a.company_id', $companyId)
1719                ->get(['u.id', 'u.name', 'u.email'])
1720                ->toArray();
1721        };
1722
1723        return [
1724            'technical' => $reqTechnical ? $query('tbl_approvers') : [],
1725            'financial' => $reqFinancial ? $query('tbl_approvers_v2') : [],
1726        ];
1727    }
1728
1729    /**
1730     * SOP §6 / FIRE-1345: an approval-relevant figure (importe, margin, budget
1731     * or customer type) changed on a budget that is STILL pending the same
1732     * approval. No new email is sent (per SOP §6), but the approver(s) get an
1733     * in-app message so they see the change before they approve/reject. When
1734     * the amount moved, the X → Y line is included; otherwise it just flags
1735     * that the budget was modified (e.g. margin only).
1736     */
1737    private function notifyApproversBudgetChanged($result, $company, bool $reqTech, bool $reqFin, $oldAmount, $newAmount): void
1738    {
1739        $msg = 'El presupuesto #'.$result->quote_id.' ha sido modificado y sigue pendiente de tu aprobación.';
1740        if ($newAmount !== null && (float) $oldAmount !== (float) $newAmount) {
1741            $msg .= ' Importe: '.$this->currency($oldAmount, 1).' → '.$this->currency($newAmount, 1).'.';
1742        }
1743
1744        $this->pushApproverNotifications($result, $company, $reqTech, $reqFin, $msg);
1745    }
1746
1747    /**
1748     * FIRE-1345: an edit dropped the budget below the approval threshold, so it
1749     * no longer requires approval. Tell the approver(s) who WERE assigned (via
1750     * the prior approval_type) that no action is needed, so they stop waiting
1751     * for it. In-app only, mirroring the client-side "ya no requiere" popup.
1752     */
1753    private function notifyApproversNoLongerRequired($result, $company, bool $reqTech, bool $reqFin): void
1754    {
1755        $msg = 'El presupuesto #'.$result->quote_id.' ya no requiere aprobación '
1756            .'(las cifras han quedado por debajo del umbral). No es necesaria ninguna acción por tu parte.';
1757
1758        $this->pushApproverNotifications($result, $company, $reqTech, $reqFin, $msg);
1759    }
1760
1761    /** Fan out an in-app notification to each unique assigned approver. */
1762    private function pushApproverNotifications($result, $company, bool $reqTech, bool $reqFin, string $msg): void
1763    {
1764        if ($company === null) {
1765            return;
1766        }
1767
1768        $approvers = $this->resolveApprovers((int) $company->company_id, $reqTech, $reqFin);
1769        $recipients = array_merge($approvers['technical'] ?? [], $approvers['financial'] ?? []);
1770        if (empty($recipients)) {
1771            return;
1772        }
1773
1774        $url = config('app.frontend_url')."orders/{$result->id}?company_id={$result->company_id}";
1775
1776        $seen = [];
1777        foreach ($recipients as $ap) {
1778            if (isset($seen[$ap->id])) {
1779                continue;
1780            }
1781            $seen[$ap->id] = true;
1782            TblNotifications::create([
1783                'user_id' => $ap->id,
1784                'content' => $msg,
1785                'is_open' => 1,
1786                'created_by' => 'System',
1787                'link' => $url,
1788            ]);
1789        }
1790    }
1791
1792    /** Map a persisted approval_type (1=technical, 2=financial, 3=both) to its dimensions. */
1793    private function approvalDimsFromType(?int $type): array
1794    {
1795        return [
1796            'tech' => $type === 1 || $type === 3,
1797            'fin' => $type === 2 || $type === 3,
1798        ];
1799    }
1800
1801    private function intOrNull($value): ?int
1802    {
1803        return ($value === null || $value === '') ? null : (int) $value;
1804    }
1805
1806    private function floatOrNull($value): ?float
1807    {
1808        return ($value === null || $value === '') ? null : (float) $value;
1809    }
1810
1811    /**
1812     * tbl_quotations.amount is a varchar(50), so anything the caller sends is
1813     * stored verbatim — «2.536€,», «4030/ 4290», «NaN» and the literal string
1814     * "null" all got in, and every SUM / CAST over the column then silently
1815     * reads them as 0 or a truncated number. Returns a KO response when the
1816     * payload carries an amount that is not a plain number, null otherwise.
1817     * Same 200 + message=KO shape as quote_exists / in_progress: the orders
1818     * form only surfaces `error` through that branch (it has no HTTP error
1819     * callback), so a 4xx would leave the save spinner stuck with no message.
1820     *
1821     * Accepted: absent, null, '', 'null', int/float, or a string of digits with an
1822     * optional leading minus and '.' decimal (what the orders form sends once
1823     * ngx-mask strips the formatting). A trailing '.' («1167.») is tolerated —
1824     * the form produces it and it casts cleanly.
1825     */
1826    private function invalidAmountResponse(array $data): ?HttpResponse
1827    {
1828        if (! array_key_exists('amount', $data)) {
1829            return null;
1830        }
1831
1832        $amount = $data['amount'];
1833
1834        // The orders form sends a blank amount as the literal "null" (see
1835        // OrderFormService.buildQuotationFormData); treat it as empty.
1836        if ($amount === null || $amount === '' || $amount === 'null') {
1837            return null;
1838        }
1839
1840        if ((is_int($amount) || is_float($amount)) && is_finite((float) $amount)) {
1841            return null;
1842        }
1843
1844        if (is_string($amount) && preg_match('/^-?\d+(\.\d*)?$/', trim($amount))) {
1845            return null;
1846        }
1847
1848        return response([
1849            'message' => 'KO',
1850            'error' => 'El importe debe ser un número (por ejemplo 2536.50). Valor recibido: '.(is_scalar($amount) ? (string) $amount : gettype($amount)),
1851        ]);
1852    }
1853
1854    /**
1855     * Like floatOrNull, but treats a zero as "no measurement" rather than
1856     * "measured zero".
1857     *
1858     * Applied to BOTH invoice_margin and revenue_per_date_per_worked (FIRE-1730,
1859     * 2026-08-18): G3W-imported budgets carry those columns as "0" when the
1860     * source doesn't compute them, and the frontend serializes empty numeric
1861     * fields as 0. Treating that placeholder 0 as a genuine below-minimum
1862     * reading forced technical approval on budgets far under any threshold. The
1863     * engine's contract is that `null` skips a financial minimum while `0`
1864     * fails it, so the caller must normalize the placeholder up front.
1865     */
1866    private function measuredFloatOrNull($value): ?float
1867    {
1868        $f = $this->floatOrNull($value);
1869
1870        return ($f === null || $f == 0.0) ? null : $f;
1871    }
1872
1873    /**
1874     * Shared approval evaluation (matrix engine + legacy workflow-question
1875     * trigger), respecting the `approvals.use_matrix_engine` flag. Used by
1876     * confirm_approval_request to re-derive the requirement for a draft budget.
1877     * Returns matched=false when the flag is off or the company has no matrix
1878     * row (the caller then relies on the persisted legacy for_approval instead).
1879     *
1880     * @param  array<string, mixed>  $d  quotation attributes (amount, budget_type_id, …)
1881     * @return array{matched: bool, reqTechnical: bool, reqFinancial: bool, requiresApproval: bool, approvalType: int|null, isQuestion: bool, financialMinimumsApplied: bool}
1882     */
1883    private function evaluateApprovalForBudget(array $d, $company): array
1884    {
1885        $none = ['matched' => false, 'reqTechnical' => false, 'reqFinancial' => false, 'requiresApproval' => false, 'approvalType' => null, 'isQuestion' => false, 'technicalThreshold' => null, 'financialThreshold' => null, 'minInvoiceMargin' => null, 'minRevenuePerEmployeeDay' => null, 'minAmountForMarginCheck' => null, 'generalCosts' => null, 'financialMinimumsApplied' => false];
1886
1887        if ($company === null || ! config('approvals.use_matrix_engine')) {
1888            return $none;
1889        }
1890
1891        $engine = new ApprovalThresholdEngine;
1892        $row = $engine->resolveRow(
1893            (int) $company->company_id,
1894            $this->intOrNull($d['budget_type_id'] ?? null),
1895            $this->intOrNull($d['customer_type_id'] ?? null),
1896        );
1897        if ($row === null) {
1898            return $none;
1899        }
1900
1901        // FIRE-1345: both financial-minimum inputs (margin AND revenue/employee/day)
1902        // are only meaningful when budget-margin tracking is enabled. The frontend
1903        // serializes an empty numeric field as 0 (parseFormValue: `value || '0'`),
1904        // so on a fresh budget revenue arrives as 0 and — if not gated — trips
1905        // `revenue_below_min`, forcing technical approval even below the amount
1906        // threshold. Gate revenue the same way margin already is, so an
1907        // unentered financial figure is treated as "not evaluated" (null), not 0.
1908        //
1909        // Gating on the flag alone did not finish the job: a budget can have
1910        // `budget_margin_enabled = 1` and still carry revenue 0 because no worked
1911        // days were ever entered — which is every budget arriving from G3W, since
1912        // the sync imports no worked-day data. Those then tripped
1913        // `revenue_per_employee_day_below_min` and demanded technical approval on
1914        // €10 budgets whose margin was perfectly healthy. Zero revenue is absence
1915        // of a measurement, so it is passed as null (see measuredFloatOrNull).
1916        $marginTrackingOn = ($d['budget_margin_enabled'] ?? 0) > 0;
1917        $eval = $engine->evaluateForRow(
1918            $row,
1919            $this->floatOrNull($d['amount'] ?? null),
1920            $marginTrackingOn ? $this->measuredFloatOrNull($d['invoice_margin'] ?? null) : null,
1921            $marginTrackingOn ? $this->measuredFloatOrNull($d['revenue_per_date_per_worked'] ?? null) : null,
1922        );
1923
1924        $reqTech = $eval['reqTechnical'];
1925        $reqFin = $eval['reqFinancial'];
1926        $isQuestion = false;
1927        if (($d['question_enabled'] ?? 0) > 0
1928            && ! empty($d['question_ids_no'])
1929            && $company->workflow_budget_size !== null
1930            && (float) ($d['amount'] ?? 0) >= (float) $company->workflow_budget_size) {
1931            $reqTech = true;
1932            $isQuestion = true;
1933        }
1934
1935        return [
1936            'matched' => true,
1937            'reqTechnical' => $reqTech,
1938            'reqFinancial' => $reqFin,
1939            'requiresApproval' => $reqTech || $reqFin,
1940            'approvalType' => ($reqTech && $reqFin) ? 3 : ($reqFin ? 2 : ($reqTech ? 1 : null)),
1941            'isQuestion' => $isQuestion,
1942            // Revenue gate: false when the budget is under the row's
1943            // margin-check amount, so the margin / revenue-per-employee-day
1944            // minimums were not evaluated at all.
1945            'financialMinimumsApplied' => $eval['financialMinimumsApplied'],
1946            'technicalThreshold' => $row->technical_threshold,
1947            'minAmountForMarginCheck' => $row->min_amount_for_margin_check ?? null,
1948            'financialThreshold' => $row->financial_threshold,
1949            'minInvoiceMargin' => $row->min_invoice_margin,
1950            'minRevenuePerEmployeeDay' => $row->min_revenue_per_employee_day,
1951            'generalCosts' => $row->general_costs,
1952        ];
1953    }
1954
1955    /**
1956     * Approval circuit v2 (SOP §10) — the redesigned E1 (first request) / E2
1957     * (re-approval) email. Sends a per-dimension message: the technical
1958     * approvers (V1) get the "Aprobación técnica" version, the financial
1959     * approvers (V2) get the "Aprobación financiera" version, each with the
1960     * relevant threshold in the Nota. E2 shows the previous → new amount.
1961     * Reuses the queued SendApprovalEmail job and the in-app notification, and
1962     * honours SENDGRID_STAGING (redirect to the logged-in tester).
1963     *
1964     * @param  array<int, string>  $dimensions  subset of ['technical','financial']
1965     * @param  array{technical: mixed, financial: mixed}|null  $thresholds
1966     */
1967    /**
1968     * SOP §10 approval-request email (E1/E2), per dimension.
1969     *
1970     * Public because the G3W sync emits the same notification — see
1971     * `PresupuestosService::sendApprovalNotificationOnly`. Keeping it private
1972     * forced the sync down the legacy `send_approval_notification` path, which is
1973     * why the same budget produced two different emails depending on whether it
1974     * arrived from G3W or was created in Titan.
1975     *
1976     * `$q` only needs the readable fields (id, quote_id, company_id,
1977     * budget_type_id, customer_type_id, amount, created_by/updated_by), so a
1978     * plain object is acceptable where no persisted row exists yet.
1979     */
1980    public function sendApprovalEmailV2($q, $company, array $dimensions, bool $isReapproval, $previousAmount, ?array $conditions): void
1981    {
1982        $typeName = optional(TblBudgetTypes::where('budget_type_id', $q->budget_type_id)->first())->name ?? '—';
1983        $clientName = optional(TblCustomerTypes::where('customer_type_id', $q->customer_type_id)->first())->name ?? '—';
1984        $orgName = $company?->name ?? '—';
1985        $amountFmt = $this->currency($q->amount, 1);
1986        $prevFmt = $previousAmount !== null ? $this->currency($previousAmount, 1) : null;
1987        $url = config('app.frontend_url')."orders/{$q->id}?company_id={$q->company_id}";
1988        $createdBy = $q->created_by ?? $q->updated_by ?? '';
1989
1990        $subject = $isReapproval
1991            ? "Presupuesto de {$typeName} por {$amountFmt} requiere nueva aprobación"
1992            : "Presupuesto de {$typeName} por {$amountFmt} requiere tu aprobación";
1993
1994        // Staging: only the logged-in user, or SENDGRID_TO_EMAIL when there is
1995        // none (a script/cron). Never the real approvers.
1996        $isStaging = (bool) config('services.sendgrid.staging');
1997        $stagingEmail = $isStaging ? (request()->user()?->email ?: config('services.sendgrid.to_email')) : null;
1998        if ($isStaging && ! $stagingEmail) {
1999            return;
2000        }
2001
2002        foreach ($dimensions as $dim) {
2003            $approvers = DB::table(($dim === 'financial' ? 'tbl_approvers_v2' : 'tbl_approvers').' as a')
2004                ->join('tbl_users as u', 'a.user_id', '=', 'u.id')
2005                ->where('a.company_id', $q->company_id)
2006                ->get(['u.id', 'u.name', 'u.email']);
2007            if ($approvers->isEmpty()) {
2008                continue;
2009            }
2010
2011            $dimLabel = $dim === 'financial' ? 'financiero' : 'técnico';
2012            if ($isReapproval) {
2013                [$tagText, $tagColor, $tagBg] = ['Re-aprobación', '#b45309', '#fdf3e3'];
2014            } elseif ($dim === 'financial') {
2015                [$tagText, $tagColor, $tagBg] = ['Aprobación financiera', '#7c3aed', '#f3ecfb'];
2016            } else {
2017                [$tagText, $tagColor, $tagBg] = ['Aprobación técnica', '#22429b', '#eaeefb'];
2018            }
2019
2020            $notaHtml = $this->buildApprovalConditionsNota($conditions, $dim, $dimLabel, $typeName, $clientName, $orgName, $amountFmt);
2021
2022            foreach ($approvers as $ap) {
2023                $intro = $isReapproval
2024                    ? "{$createdBy} ha modificado un presupuesto que ya había sido aprobado en {$orgName}. El importe se ha actualizado de <b>".($prevFmt ?? '—')."</b> a <b>{$amountFmt}</b> y requiere una nueva aprobación — #{$q->quote_id}."
2025                    : "{$createdBy} ha creado un presupuesto en {$orgName} que requiere tu aprobación como <b>aprobador {$dimLabel}</b> — #{$q->quote_id}.";
2026
2027                $toEmail = $stagingEmail ?: $ap->email;
2028
2029                // Outlook-classic compatible: table layout, inline styles, no
2030                // flexbox; button as a bgcolor <td>; logo as a cid image.
2031                $card = '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f5f7;"><tr><td align="center" style="padding:20px;">'
2032                    .'<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="width:480px;max-width:480px;background:#ffffff;border:1px solid #e5e7eb;">'
2033                    .'<tr><td style="padding:20px;font-family:Arial,Helvetica,sans-serif;color:#1f2937;font-size:14px;">'
2034                    ."<div style=\"font-size:16px;font-weight:bold;margin:0 0 10px;\">{$subject}</div>"
2035                    .'<table role="presentation" cellpadding="0" cellspacing="0"><tr>'
2036                    ."<td bgcolor=\"{$tagBg}\" style=\"padding:3px 9px;font-size:11px;font-weight:bold;color:{$tagColor};font-family:Arial,Helvetica,sans-serif;\">{$tagText}</td>"
2037                    .'</tr></table>'
2038                    ."<p style=\"margin:14px 0 8px;\">Hola {$ap->name},</p>"
2039                    ."<p style=\"margin:0 0 12px;line-height:1.5;\">{$intro}</p>"
2040                    .'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f9fafb;border:1px solid #e5e7eb;margin:0 0 12px;"><tr>'
2041                    .'<td style="padding:9px 12px;font-size:13px;color:#6b7280;">Importe</td>'
2042                    ."<td align=\"right\" style=\"padding:9px 12px;font-size:13px;font-weight:bold;\">{$amountFmt}</td>"
2043                    .'</tr></table>'
2044                    .$notaHtml
2045                    .'<table role="presentation" cellpadding="0" cellspacing="0" style="margin:16px 0 6px;"><tr>'
2046                    ."<td bgcolor=\"#2f56c7\" style=\"padding:10px 18px;\"><a href=\"{$url}\" style=\"color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:bold;text-decoration:none;\">Revisar y aprobar</a></td>"
2047                    .'</tr></table>'
2048                    .'<p style="margin:6px 0 14px;font-size:11px;color:#6b7280;">La aprobación se realiza dentro del presupuesto, desde este enlace.</p>'
2049                    .'<img src="cid:fireservicetitan" alt="Fire Service Titan" width="150" style="display:block;height:auto;border:0;outline:none;text-decoration:none;" />'
2050                    .'</td></tr></table>'
2051                    .'</td></tr></table>';
2052
2053                $html = '<!DOCTYPE html><html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body style="margin:0;padding:0;background:#f4f5f7;">'.$card.'</body></html>';
2054
2055                TblNotifications::create([
2056                    'user_id' => $ap->id,
2057                    'content' => strip_tags($intro),
2058                    'is_open' => 1,
2059                    'created_by' => 'System',
2060                    'link' => $url,
2061                ]);
2062
2063                SendApprovalEmail::dispatch(
2064                    toEmail: (string) $toEmail,
2065                    subject: $subject,
2066                    html: $html,
2067                    bcc: [],
2068                    quoteId: (string) $q->quote_id,
2069                    companyId: (int) $q->company_id,
2070                )->onQueue('email');
2071
2072                if ($stagingEmail) {
2073                    return; // one email to the tester is enough in staging
2074                }
2075            }
2076        }
2077    }
2078
2079    /**
2080     * The "Nota" block listing the approval conditions of the matched row
2081     * (thresholds + financial minimums), so the approver sees exactly why
2082     * approval is required. Falls back to a generic line when the conditions
2083     * aren't known (legacy path).
2084     *
2085     * @param  array{technical: mixed, financial: mixed, minMargin: mixed, minRevenue: mixed, generalCosts: mixed}|null  $c
2086     */
2087    private function buildApprovalConditionsNota(?array $c, string $dim, string $dimLabel, string $typeName, string $clientName, string $orgName, string $amountFmt): string
2088    {
2089        if ($c === null) {
2090            return '<p style="margin:0 0 4px;font-size:12px;color:#6b7280;line-height:1.5;"><b style="color:#1f2937;">Nota:</b> la aprobación es necesaria según la configuración de umbrales de '.$orgName.'.</p>';
2091        }
2092
2093        $items = '';
2094        if ($c['technical'] !== null && (float) $c['technical'] > 0) {
2095            $items .= '<li>Umbral técnico: '.$this->currency($c['technical'], 1).'</li>';
2096        }
2097        if ($c['financial'] !== null && (float) $c['financial'] > 0) {
2098            $items .= '<li>Umbral financiero: '.$this->currency($c['financial'], 1).'</li>';
2099        }
2100        if ($c['minMargin'] !== null && (float) $c['minMargin'] > 0) {
2101            $items .= '<li>Margen mínimo en factura: '.rtrim(rtrim(number_format((float) $c['minMargin'], 2, ',', '.'), '0'), ',').' %</li>';
2102        }
2103        if ($c['minRevenue'] !== null && (float) $c['minRevenue'] > 0) {
2104            $items .= '<li>Ingresos mín. por empleado/día: '.$this->currency($c['minRevenue'], 1).'</li>';
2105        }
2106
2107        $threshold = $c[$dim] ?? null;
2108        $because = ($threshold !== null && (float) $threshold > 0)
2109            ? "Se requiere aprobación porque el importe ({$amountFmt}) es igual o superior al umbral {$dimLabel} ("
2110                .$this->currency($threshold, 1).').'
2111            : "Se requiere aprobación por no cumplir algún mínimo financiero de la fila (importe {$amountFmt}).";
2112
2113        return '<div style="font-size:12px;color:#6b7280;line-height:1.5;">'
2114            ."<b style=\"color:#1f2937;\">Nota — condiciones de aprobación</b> para {$typeName} · clientes {$clientName} en {$orgName}:"
2115            .'<ul style="margin:6px 0;padding-left:18px;">'.$items.'</ul>'
2116            .$because
2117            .'</div>';
2118    }
2119
2120    /**
2121     * Approval circuit v2 (SOP §9) — the approver's inbox. Lists the budgets
2122     * awaiting the logged-in user's decision: a technical (V1) slot open on a
2123     * company they approve, or a financial (V2) slot open on a dual-level
2124     * request. `acting_type` is the slot they'd act on (technical preferred,
2125     * mirroring approverActingType); `amount_changed` drives the X→Y hint.
2126     */
2127    public function list_my_pending_approvals(): ResponseFactory|HttpResponse
2128    {
2129        try {
2130            $userId = (int) $this->userId;
2131
2132            $v1Companies = DB::table('tbl_approvers')->where('user_id', $userId)->pluck('company_id')->all();
2133            $v2Companies = DB::table('tbl_approvers_v2')->where('user_id', $userId)->pluck('company_id')->all();
2134            $approverCompanies = array_map('intval', array_values(array_unique(array_merge($v1Companies, $v2Companies))));
2135
2136            // Scope to the top-left selector: a specific company when one is
2137            // chosen, otherwise the region-scoped set ($this->companyIds, derived
2138            // from the Region header in the constructor — all the user's companies
2139            // when region is "All"). Then intersect with the companies the user
2140            // actually approves for.
2141            $selectedCompany = (int) request()->query('company_id', 0);
2142            $scope = $selectedCompany !== 0 ? [$selectedCompany] : array_map('intval', $this->companyIds);
2143            $companies = array_values(array_intersect($approverCompanies, $scope));
2144
2145            if (empty($companies)) {
2146                return response(['message' => 'OK', 'data' => []]);
2147            }
2148
2149            $budgets = DB::table('tbl_quotations as a')
2150                ->leftJoin('tbl_companies as b', 'a.company_id', '=', 'b.company_id')
2151                ->leftJoin('tbl_budget_types as d', 'a.budget_type_id', '=', 'd.budget_type_id')
2152                ->leftJoin('tbl_customer_types as c', 'a.customer_type_id', '=', 'c.customer_type_id')
2153                ->whereIn('a.company_id', $companies)
2154                ->whereNotNull('a.for_approval')
2155                ->where('a.for_approval', '!=', 0)
2156                ->where('a.for_add', 0)
2157                ->orderByDesc('a.approval_requested_at')
2158                ->get([
2159                    'a.id', 'a.quote_id', 'a.company_id', 'b.name as company_name', 'a.client',
2160                    'a.amount', 'a.importe_avisado', 'd.name as budget_type', 'c.name as customer_type',
2161                    'a.for_approval', 'a.approval_type', 'a.approved_by', 'a.approved_by_v2',
2162                    'a.rejected_by', 'a.rejected_by_v2', 'a.created_by', 'a.commercial',
2163                    'a.approval_requested_at',
2164                ]);
2165
2166            $v1 = array_flip(array_map('intval', $v1Companies));
2167            $v2 = array_flip(array_map('intval', $v2Companies));
2168
2169            $out = [];
2170            foreach ($budgets as $r) {
2171                $cid = (int) $r->company_id;
2172                // approval_type is authoritative (for_approval was historically
2173                // mislabeled 1 for financial-only); fall back to for_approval on
2174                // legacy rows without it. Mirrors isApproverAuthorizedFor().
2175                $type = $r->approval_type !== null
2176                    ? (int) $r->approval_type
2177                    : (int) $r->for_approval;
2178                $technicalOpen = ($type === 1 || $type === 3)
2179                    && $r->approved_by === null && $r->rejected_by === null && isset($v1[$cid]);
2180                // Finance sees a financial-only budget (type 2) immediately, or —
2181                // in a dual (both) flow — only AFTER Operations approves (and
2182                // hasn't rejected). Without the type-2 case, finance-only budgets
2183                // never appeared in the financial approver's queue.
2184                $financialOpen = (
2185                    ($type === 2 && $r->approved_by_v2 === null && $r->rejected_by_v2 === null)
2186                    || ($type === 3 && $r->approved_by !== null && $r->rejected_by === null
2187                        && $r->approved_by_v2 === null && $r->rejected_by_v2 === null)
2188                ) && isset($v2[$cid]);
2189
2190                if (! $technicalOpen && ! $financialOpen) {
2191                    continue; // user's slot already decided (or they don't hold it)
2192                }
2193
2194                $r->acting_type = $technicalOpen ? 'technical' : 'financial';
2195                $r->amount_changed = $r->importe_avisado !== null
2196                    && (float) $r->importe_avisado !== (float) $r->amount;
2197                $out[] = $r;
2198            }
2199
2200            return response(['message' => 'OK', 'data' => $out]);
2201        } catch (\Exception $e) {
2202            report(AppException::fromException($e, 'LIST_MY_PENDING_APPROVALS_EXCEPTION'));
2203
2204            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2205        }
2206    }
2207
2208    /**
2209     * @param  string|null  $actingType  When non-null ('technical'/'financial') the
2210     *                                   caller already recorded the rejection slot
2211     *                                   (see recordApprovalDecision) and this method
2212     *                                   must not write it again. Null keeps the
2213     *                                   legacy self-recording behaviour used by the
2214     *                                   OngoingJobs callers.
2215     */
2216    public function send_rejected_notification($userId, $username, $email, $companyName, $budgetType, $amount, $id, string $quoteId, $companyId, $endpoint, string $reason = '', ?string $actingType = null): void
2217    {
2218
2219        $fendpoint = '';
2220
2221        if ($endpoint == 'orders') {
2222            if ($this->locale == 'es') {
2223                $fendpoint = 'presupuesto';
2224            } else {
2225                $fendpoint = 'budget';
2226            }
2227
2228        } else {
2229            if ($this->locale == 'es') {
2230                $fendpoint = 'trabajo';
2231            } else {
2232                $fendpoint = 'job';
2233            }
2234        }
2235
2236        $query = "SELECT
2237                    u.id AS user_id,
2238                    u.name,
2239                    u.email,
2240                    u.sender_email,
2241                    CASE
2242                        WHEN a.user_id IS NOT NULL AND c.user_id IS NOT NULL THEN 'both'
2243                        WHEN a.user_id IS NOT NULL THEN 'approvers'
2244                        WHEN c.user_id IS NOT NULL THEN 'approvers_v2'
2245                        ELSE 'none'
2246                    END AS exists_in
2247                FROM tbl_users u
2248                LEFT JOIN tbl_approvers a
2249                    ON u.id = a.user_id AND a.company_id = {$companyId}
2250                LEFT JOIN tbl_approvers_v2 c
2251                    ON u.id = c.user_id AND c.company_id = {$companyId}
2252                WHERE u.id = {$this->userId}";
2253
2254        $user = DB::select($query);
2255
2256        $user = $user[0] ?? null;
2257
2258        // FIRE-1092: same defensive null check as send_approved_notification.
2259        if ($user === null) {
2260            Log::channel('email_log')->warning("send_rejected_notification: logged-in user {$this->userId} not found in tbl_users; skipping notification for quote {$quoteId}.");
2261
2262            return;
2263        }
2264
2265        $toEmail = $email;
2266        $amount = $this->currency($amount, 1);
2267
2268        $imgpath = file_get_contents(public_path('fireservicetitan.png'));
2269        $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
2270
2271        $url = config('app.frontend_url')."{$endpoint}/{$id}?company_id={$companyId}";
2272        $href = "<a href='{$url}'>{$quoteId}</a>";
2273
2274        $body = __('language.send_rejected_notification.body_hello');
2275        $body = str_replace('{{creator}}', $username, $body);
2276
2277        $body .= __('language.send_rejected_notification.body_message');
2278        $body = str_replace('{{approver}}', $user->name, $body);
2279        $body = str_replace('{{company}}', $companyName, $body);
2280        $body = str_replace('{{type}}', $budgetType, $body);
2281        $body = str_replace('{{amount}}', $amount, $body);
2282        $body = str_replace('{{quote_id}}', $href, $body);
2283        $body = str_replace('{{endpoint}}', $fendpoint, $body);
2284
2285        // Append the reason written by the rejecter. Escape it first — the
2286        // value is shown both as an HTML email and as an in-app notification,
2287        // so unescaped input would be a stored-XSS vector.
2288        $reason = trim($reason);
2289        if ($reason !== '') {
2290            $body .= '<p><b>'.__('language.send_rejected_notification.reason').'</b><br>'.nl2br(e($reason)).'</p><br>';
2291        }
2292
2293        $content = $body;
2294
2295        // SOP §10 redesigned shell (was the old plain body + inline logo).
2296        $html = $this->buildTitanEmailCard(
2297            $this->locale == 'es' ? 'No aprobado' : 'Not approved',
2298            '#e04747',
2299            '#fdecec',
2300            $this->locale == 'es' ? 'Solicitud de aprobación rechazada' : 'Approval request rejected',
2301            $content,
2302            $url,
2303            ($this->locale == 'es' ? 'Ver ' : 'Open ').$fendpoint,
2304        );
2305
2306        $subject = __('language.send_rejected_notification.subject');
2307        $subject = str_replace('{{quote_id}}', $quoteId, $subject);
2308        $subject = str_replace('{{endpoint}}', ucfirst($fendpoint), $subject);
2309
2310        // FIRE-1092: same shape as send_approved_notification — record
2311        // the rejection FIRST, send the email on best-effort. For orders the
2312        // caller (reject_quotation) owns the write and passes $actingType, so
2313        // the slot follows what was authorized instead of the approver's table
2314        // membership (see send_approved_notification for why 'both' broke).
2315        if ($endpoint == 'orders') {
2316            if ($actingType === null) {
2317                if ($user->exists_in == 'approvers' || $user->exists_in == 'both') {
2318                    TblQuotations::where('id', $id)->update([
2319                        'rejected_at' => date('Y-m-d H:i:s'),
2320                        'rejected_by' => $user->name,
2321                    ]);
2322                } elseif ($user->exists_in == 'approvers_v2') {
2323                    TblQuotations::where('id', $id)->update([
2324                        'rejected_at_v2' => date('Y-m-d H:i:s'),
2325                        'rejected_by_v2' => $user->name,
2326                    ]);
2327                }
2328            }
2329        } else {
2330            TblOngoingJobs::where('id', $id)->update([
2331                'rejected_at' => date('Y-m-d H:i:s'),
2332                'rejected_by' => $user->name,
2333            ]);
2334        }
2335
2336        TblNotifications::create([
2337            'user_id' => $userId,
2338            'content' => $content,
2339            'is_open' => 1,
2340            'created_by' => 'System',
2341            'link' => $url,
2342        ]);
2343
2344        $this->addUpdateLog($id, $userId, 'send_rejected_notification', null, null, 5);
2345
2346        // FIRE-1147: dispatch the email send. The rejection record, in-app
2347        // notification and audit log at L1135-1162 already landed
2348        // synchronously, so SendGrid downtime doesn't lose the action.
2349        if ($toEmail != null) {
2350            if (config('services.sendgrid.staging')) {
2351                // Staging: route to the fixed test inbox (SENDGRID_TO_EMAIL) so the
2352                // tester receives it regardless of which user they've switched to
2353                // (same rationale as the approved email above). Falls back to the
2354                // authenticated user, then $user.
2355                $toEmail = config('services.sendgrid.to_email')
2356                    ?: request()->user()?->email ?: $user->email;
2357            }
2358
2359            SendRejectedEmail::dispatch(
2360                toEmail: (string) $toEmail,
2361                subject: $subject,
2362                html: $html,
2363                quoteId: $quoteId,
2364                companyId: (int) $companyId,
2365            )->onQueue('email');
2366        }
2367
2368    }
2369
2370    public function update_quotation(Request $request, $id): ResponseFactory|HttpResponse
2371    {
2372        $approvalMinimumOrderSize = null;
2373        $approvalIsQuestion = null;
2374        $approvalQuestionIdsNo = null;
2375        $approvalN = null;
2376        $approvalMinimumMargin = null;
2377        $approvalId = null;
2378        $approvalForAdd = null;
2379        $approvalInvoiceMargin = null;
2380        $sendApprovalNotification = false;
2381        $sendApprovalMarginNotification = false;
2382        $needToSendReminder = false;
2383        // Confirmation-gate payload returned to the frontend. The engine (draft-
2384        // until-confirm) path sets it directly; the legacy path builds it below.
2385        $needsApprovalConfirmation = null;
2386
2387        // try {
2388
2389        // Titan → Zeus bridge (see create_quotation above and config/zeus.php).
2390        // Runs before Titan touches the row: the region is resolved from the
2391        // quotation's current company when the payload omits company_id, and
2392        // Zeus keys updateQuotation on the same legacy id Titan uses, so the id
2393        // is passed straight through with no translation.
2394        // Reject a non-numeric amount before the Zeus bridge, so a payload
2395        // Titan refuses is never mirrored to Zeus either.
2396        if ($invalid = $this->invalidAmountResponse($request->all())) {
2397            return $invalid;
2398        }
2399
2400        $zeus = app(ZeusBridge::class);
2401        $forward = $zeus->updateQuotation($request, $id);
2402
2403        if ($zeus->shouldReturnZeusResponse($forward)) {
2404            return $forward->toTitanResponse();
2405        }
2406
2407        $data = $request->all();
2408        $id = addslashes((string) $id);
2409        // Only feeds the audit log: fall back to the authenticated user when
2410        // a caller omits it instead of dying on an undefined key.
2411        $data['user_id'] ??= request()->user()?->id;
2412        $userId = addslashes((string) $data['user_id']);
2413
2414        // "Replace quotation" (sustitutos). The add form reserves its quote
2415        // number up front, so this method - not create_quotation - is what
2416        // actually saves a brand-new quote from the UI. Only the add form
2417        // sends this field; the edit form has no Replace section yet.
2418        // Unset because it is not a tbl_quotations column.
2419        $replacedQuoteId = trim((string) ($data['replaced_quote_id'] ?? ''));
2420        unset($data['replaced_quote_id']);
2421
2422        // FIRE-1753: mirror of the create_quotation guard — refuse to write
2423        // company_id = 22 (CLM). See the block in create_quotation for the
2424        // full context. Belt-and-braces for the edit path in case the FE
2425        // tries to move a Madrid row back to CLM.
2426        if (! empty($data['company_id']) && (int) $data['company_id'] === 22) {
2427            Log::channel('g3w')->warning(sprintf(
2428                'FIRE-1753: rewriting company_id 22 → 18 on update_quotation. quotation_id=%s, updated_by=%s',
2429                $id,
2430                $data['updated_by'] ?? '?',
2431            ));
2432            $data['company_id'] = 18;
2433        }
2434
2435        // FIRE-1377: normalise the send channel and enforce the €5,000 rule.
2436        // Only touch send_channel when the payload carries it (or an amount that
2437        // could trip the threshold) so partial updates don't clobber a channel
2438        // the rep previously chose. Falls back to the stored values otherwise.
2439        if (array_key_exists('send_channel', $data) || array_key_exists('amount', $data)) {
2440            $currentChannel = $data['send_channel']
2441                ?? TblQuotations::where('id', $id)->value('send_channel');
2442            $effectiveAmount = $data['amount']
2443                ?? TblQuotations::where('id', $id)->value('amount');
2444            $data['send_channel'] = $this->normalizeSendChannel($currentChannel, $effectiveAmount);
2445        }
2446
2447        // FIRE-1260 — verify the código (if present) matches the source
2448        // for this quotation. On update either field can arrive alone, so
2449        // fall back to the row's current value for whichever isn't in the
2450        // payload. Empty/null codigo_id is a valid "clear" and passes.
2451        if (array_key_exists('codigo_id', $data) && ! empty($data['codigo_id'])) {
2452            $effectiveSource = $data['source_id']
2453                ?? TblQuotations::where('id', $id)->value('source_id');
2454            $belongs = TblSourceCodigos::where('id', $data['codigo_id'])
2455                ->where('source_id', $effectiveSource)
2456                ->exists();
2457            if (! $belongs) {
2458                return response([
2459                    'message' => 'KO',
2460                    'error' => 'El código no pertenece a la fuente seleccionada',
2461                ], 422);
2462            }
2463        }
2464
2465        if (! TblQuotationsLog::where('quotation_id', $id)->exists()) {
2466            $categoryLog = ($data['budget_status_id'] ?? null) == 6 ? 0 : 2;
2467            $this->addUpdateLog($id, $data['user_id'], 'create_quotation', null, null, $categoryLog);
2468        }
2469        $forApproval = null;
2470        unset($data['user_id']);
2471
2472        $r = ['amount', 'order_number', 'budget_type_id', 'acceptance_date'];
2473        $job = [];
2474
2475        foreach ($data as $key => $value) {
2476            if ($value == 'null') {
2477                $data[$key] = null;
2478            }
2479
2480            if (in_array($key, $r)) {
2481                $job[$key] = $value;
2482            }
2483        }
2484
2485        $files = $request->file('files');
2486        unset($data['files']);
2487
2488        $internalFiles = $request->file('internal_files');
2489        unset($data['internal_files']);
2490
2491        $query = '
2492            SELECT
2493                SUM(CASE WHEN is_internal IS NULL THEN 1 ELSE 0 END) as external_count,
2494                SUM(CASE WHEN is_internal = 1 THEN 1 ELSE 0 END) as internal_count
2495            FROM tbl_files
2496            WHERE quotation_id = ?';
2497
2498        $counts = DB::select($query, [$id]);
2499        $fileCount = $counts[0]->external_count;
2500        $internalFileCount = $counts[0]->internal_count;
2501
2502        if ($fileCount > 0 || ! empty($files)) {
2503            $data['has_attachment'] = 1;
2504        }
2505
2506        if ($files) {
2507            $totalFiles = $fileCount + count($files);
2508            if ($totalFiles > 10) {
2509                return response(['message' => 'KO', 'error' => __('language.file_count_exceeded')]);
2510            }
2511        }
2512
2513        if ($internalFileCount > 0 || ! empty($internalFiles)) {
2514            $data['has_attachment'] = 1;
2515        }
2516
2517        if ($internalFiles) {
2518            $totalInternalFileCount = $internalFileCount + count($internalFiles);
2519            if ($totalInternalFileCount > 10) {
2520                return response(['message' => 'KO', 'error' => __('language.file_count_exceeded')]);
2521            }
2522        }
2523
2524        if (isset($data['request_date']) && isset($data['issue_date'])) {
2525            $requestDate = strtotime($data['request_date']);
2526            $issueDate = strtotime($data['issue_date']);
2527            $dateDiff = $issueDate - $requestDate;
2528            $data['duration'] = round($dateDiff / (60 * 60 * 24));
2529        }
2530
2531        $result = TblQuotations::where('id', $id)->first();
2532
2533        // Approval circuit v2 (SOP §5): remember whether this budget was already
2534        // requiring approval BEFORE this save, so we can tell a NEW requirement
2535        // (→ show the confirmation modal) from a re-save of an already-pending
2536        // one (→ stay silent; the approver sees the change via the pop-up).
2537        $previousForApproval = $result->for_approval ?? null;
2538
2539        // FIRE-982 follow-up: the manual-create flow can leave the
2540        // frontend with a stub id that has already been deleted (either
2541        // by the duplicate-redirect retarget below, or by a separate
2542        // cleanup). Crashing on a null `$result` here surfaces as an
2543        // unhandled "Attempt to read property quote_id on null" instead
2544        // of a recoverable error the UI can show, so guard the lookup.
2545        if (! $result) {
2546            return response([
2547                'message' => 'KO',
2548                'error' => 'quotation_not_found',
2549                'id' => $id,
2550            ], 404);
2551        }
2552
2553        // FST New Features (2026-06-26) points 2 & 3: hard-block the transition
2554        // to "Enviado" (2) — the point-2 maintenance question must be answered
2555        // and a coverage contract must be attached so it is sent automatically
2556        // with the offer. The point-3 SIGNED question is handled at acceptance
2557        // and is NOT a hard block (offer already accepted), so it is not checked
2558        // here. Uses incoming values where present, falling back to the row.
2559        if (isset($data['budget_status_id']) && (int) $data['budget_status_id'] === 2) {
2560            $sopCheck = (object) [
2561                'id' => $id,
2562                'company_id' => $result->company_id,
2563                'amount' => $data['amount'] ?? $result->amount,
2564                'budget_type_id' => $data['budget_type_id'] ?? $result->budget_type_id,
2565                'maintenance_potential' => array_key_exists('maintenance_potential', $data)
2566                    ? $data['maintenance_potential']
2567                    : $result->maintenance_potential,
2568            ];
2569            // Pass whether this same request is uploading client file(s) — the
2570            // SOP check runs before those rows are inserted (~line 2040), so a
2571            // contract attached in the same save wouldn't be seen otherwise.
2572            $sopBlockers = $this->sopBlockingRequirements($sopCheck, ! empty($files));
2573            if (! empty($sopBlockers)) {
2574                // 200 + 'KO' (like quote_exists / in_progress) so the
2575                // update_quotation success handler surfaces this real reason via
2576                // Swal(response.error); a 422 would be swallowed by the global
2577                // HTTP error interceptor and shown as the generic "contact admin".
2578                return response([
2579                    'message' => 'KO',
2580                    'error' => implode(' ', $sopBlockers),
2581                    'sop_blockers' => $sopBlockers,
2582                ]);
2583            }
2584        }
2585
2586        if ($result->quote_id != $data['quote_id']) {
2587
2588            // Look up the OTHER row that owns this quote_id (excluding the
2589            // row being updated).
2590            $existing = TblQuotations::where('quote_id', (string) $data['quote_id'])
2591                ->where('company_id', $result->company_id)
2592                ->where('id', '<>', $id)
2593                ->first();
2594
2595            if ($existing) {
2596
2597                if ($result->for_add == 1) {
2598                    // Manual-create flow: the frontend opened the "Crear
2599                    // manualmente" form and spawned a stub row; the user
2600                    // typed a quote_id that already belongs to another
2601                    // record. Treat the submission as an edit of that
2602                    // existing record — delete the orphan stub and
2603                    // retarget the update so the rest of this function
2604                    // applies the form data to `$existing`.
2605                    //
2606                    // The manual-create form sends `null` (or the literal
2607                    // string "null") for fields it doesn't expose —
2608                    // `internal_quote_id`, `box_work_g3w`, `order_number`,
2609                    // and friends. Mass-assigning those to a G3W-imported
2610                    // existing row would silently nuke its sync metadata,
2611                    // so drop empty submitted values when the existing row
2612                    // already has a value there. Real edits (e.g. user
2613                    // typed a new client name) still go through; only
2614                    // form-blank-vs-existing-populated keys are skipped.
2615                    foreach ($data as $key => $value) {
2616                        $isFormBlank = $value === null
2617                            || $value === ''
2618                            || $value === 'null';
2619                        if ($isFormBlank && ! is_null($existing->$key) && $existing->$key !== '') {
2620                            unset($data[$key]);
2621                        }
2622                    }
2623
2624                    TblQuotations::where('id', $id)->delete();
2625                    $id = $existing->id;
2626                    $result = $existing;
2627                    // fall through into the normal update path below
2628                } else {
2629                    // Non-stub edit: a real quotation is trying to rename
2630                    // its quote_id to one already owned by another row.
2631                    // Silently merging here would clobber the other row's
2632                    // data, so we keep the original protection — return an
2633                    // error and suggest the next free number.
2634                    $latestBudget = TblQuotations::where('company_id', $result->company_id)
2635                        ->orderByRaw('CAST(quote_id AS DOUBLE) DESC')
2636                        ->first();
2637
2638                    $number = $latestBudget->quote_id;
2639                    $x = true;
2640
2641                    while ($x) {
2642
2643                        if (is_numeric(substr((string) $number, -1))) {
2644                            $number++;
2645                        } else {
2646                            $number .= '1';
2647                        }
2648
2649                        $check = TblQuotations::where('company_id', $result->company_id)
2650                            ->where('quote_id', (string) $number)
2651                            ->count();
2652
2653                        if ($check == 0) {
2654                            $x = false;
2655                        }
2656                    }
2657
2658                    return response([
2659                        'message' => 'KO',
2660                        'error' => 'quote_exists',
2661                        'number' => $number,
2662                    ]);
2663                }
2664            }
2665        }
2666
2667        // Preserve existing budget_type_id when the incoming payload would
2668        // null it out. The frontend marks the field required, but the
2669        // validator is cleared on Solicitud/Visita/Anulado statuses and
2670        // re-loading a row with no type seeds the form value to null
2671        // (orders.component.ts:2265). FormData previously serialised that
2672        // null as the literal string "null", which the foreach above at
2673        // :1098 converts to PHP null — and the bare update($data) at
2674        // :1703 would then wipe a previously-set budget_type_id. The
2675        // companion frontend fix in order-form.service.ts now omits the
2676        // field when blank instead of sending "null"; this guard backs
2677        // that up and keeps $data['budget_type_id'] defined so the
2678        // downstream comparisons at :1322 and :1402 don't trip undefined
2679        // array key errors. Solicitudes with a legitimately-null
2680        // budget_type_id still write null — only populated rows are
2681        // protected.
2682        $incomingBudgetTypeId = $data['budget_type_id'] ?? null;
2683        if (
2684            $incomingBudgetTypeId === null
2685            || $incomingBudgetTypeId === ''
2686            || $incomingBudgetTypeId === 'null'
2687        ) {
2688            $data['budget_type_id'] = $result->budget_type_id;
2689        }
2690
2691        // PHP-LARAVEL-1F: payloads without these keys died on undefined array
2692        // keys. Absent means unchanged (or, for the author, the logged-in user).
2693        $data['updated_by'] ??= request()->user()?->name ?? $result->updated_by;
2694        $data['commercial'] ??= $result->commercial;
2695        $data['budget_status_id'] ??= $result->budget_status_id;
2696
2697        $action = 0;
2698        if ($result->created_by == null || $result->for_add == 1) {
2699            $action = 1;
2700            $data['created_by'] = $data['updated_by'];
2701            $data['for_add'] = 0;
2702        }
2703
2704        $company = TblCompanies::where('company_id', $result->company_id)->first();
2705        // $company can be null (row deleted, e.g. CLM id 22). The approval
2706        // block below is already skipped then; everything after it reads the
2707        // id from here instead of $company->company_id (PHP-LARAVEL-1G).
2708        // Captured now because $result is reassigned to a raw row further down.
2709        $quoteCompanyId = $result->company_id;
2710
2711        $commercial = TblUsers::where('name', $data['commercial'])->first();
2712        $status = TblBudgetStatus::where('budget_status_id', $data['budget_status_id'])->first();
2713
2714        // $checkQuotation = TblQuotations::where(function($query) use ($data, $result) {
2715        //     $query->where('internal_quote_id', $data['internal_quote_id'])
2716        //         ->orWhere('internal_quote_id', 'O-25/'.$data['internal_quote_id']);
2717        // })
2718        //     ->where('company_id', $result->company_id)
2719        //     ->first();
2720
2721        // if($checkQuotation) {
2722        //     $url = "orders/" . $checkQuotation->id . "?company_id=" . $checkQuotation->company_id;
2723        //     return response([
2724        //         'message' => 'KO',
2725        //         'error' => "Presupuesto ya creado. Puedes verlo <a href='$url' target='_blank'>aquí</a>."
2726        //     ]);
2727        // }
2728
2729        $limitReminderEmails = $company->limit_reminder_emails ?? 3;
2730
2731        if ($result->total_sent == $limitReminderEmails) {
2732            $data['total_sent'] = 0;
2733        }
2734
2735        if ($result->budget_status_id != $data['budget_status_id'] || $result->commercial != $data['commercial']) {
2736            if ($data['budget_status_id'] == 12) {
2737                if ($company && $commercial) {
2738                    $inProgressCount = TblQuotations::where('budget_status_id', 12)->where('company_id', $result->company_id)->where('commercial', $data['commercial'])->count();
2739                    if ($company->process_limit <= $inProgressCount) {
2740                        return response(['message' => 'KO', 'error' => 'in_progress', 'limit' => $company->process_limit]);
2741                    }
2742                } else {
2743                    return response(['message' => 'KO', 'error' => 'in_progress', 'limit' => 0]);
2744                }
2745            }
2746        }
2747
2748        $sendNotification = false;
2749        if ($result->commercial != $data['commercial']) {
2750            if (! empty($commercial)) {
2751                $createdByX = ($result->created_by == null) ? $data['created_by'] : $result->created_by;
2752                if ($createdByX != $data['commercial']) {
2753                    $action = 0;
2754                    $sendNotification = true;
2755                }
2756            }
2757        }
2758
2759        // FIRE-1092: skip the approval recompute when the budget is in a
2760        // terminal status — Aceptado (3), Rechazado (4), Rechazado
2761        // automáticamente (7), or Rechazado-duplicado (20). Once a budget
2762        // is closed (accepted or rejected) any later edits — bookkeeping
2763        // adjustments, final invoice amount, etc. — should NOT drag the
2764        // row back into "Requiere aprobación". The resulting status is
2765        // taken from the incoming payload when present, falling back to
2766        // the row's current status so an edit that doesn't touch
2767        // `budget_status_id` still honours the terminal state.
2768        $resultingStatusId = (int) ($data['budget_status_id'] ?? $result->budget_status_id);
2769        $terminalStatuses = [3, 4, 7, 20];
2770        $isTerminalStatus = in_array($resultingStatusId, $terminalStatuses, true);
2771
2772        // A budget in "En proceso" (12) is already in execution — approval
2773        // belongs to the pre-execution stage, so edits made while the work is
2774        // underway must not drag the row back into "Requiere aprobación" nor
2775        // fire an approval notification. Skip the recompute for this status,
2776        // same as the terminal statuses above.
2777        $isInProgressStatus = $resultingStatusId === 12;
2778
2779        if (! $isTerminalStatus
2780            && ! $isInProgressStatus
2781            && (isset($data['amount']) || isset($data['budget_type_id']) || isset($data['customer_type_id']) || isset($data['invoice_margin']) || isset($data['question_enabled']))
2782        ) {
2783            if ($company) {
2784
2785                // This block runs when ANY of these inputs is in the payload,
2786                // but reads ALL of them. A partial update (e.g. only amount)
2787                // crashed with Undefined array key "budget_type_id"/"amount"
2788                // (PHP-LARAVEL-22). Absent means unchanged, so take the stored
2789                // value; the row update then writes the same value back.
2790                foreach (['amount', 'budget_type_id', 'customer_type_id', 'invoice_margin'] as $approvalInput) {
2791                    if (! array_key_exists($approvalInput, $data)) {
2792                        $data[$approvalInput] = $result->{$approvalInput};
2793                    }
2794                }
2795
2796                $n = 0;
2797                // null (not 0) is the "no margin computed" sentinel. Keeping a
2798                // genuine 0% margin distinguishable from "not applicable" is
2799                // what lets the margin-approval rule fire at 0 — a 0 that came
2800                // from real cost data must require approval, an unset one must not.
2801                $invoiceMargin = null;
2802                $minimumMargin = 0;
2803                $minimumOrderSize = 0;
2804                $customerTypeIds = [];
2805
2806                // Whether an approval-driving input actually changed on this
2807                // save. Only when this is true have we genuinely re-evaluated,
2808                // so it also gates the "no longer requires approval" clear
2809                // (FIRE §12) — unrelated edits must never wipe a valid pending
2810                // approval.
2811                $approvalInputsChanged = $result->amount != $data['amount'] ||
2812                    $result->budget_type_id != $data['budget_type_id'] ||
2813                    $result->customer_type_id != $data['customer_type_id'] ||
2814                    $result->invoice_margin != $data['invoice_margin'];
2815
2816                $questionInputsChanged = isset($data['question_enabled']) && (
2817                    ($data['question_ids_no'] ?? null) != $result->question_ids_no
2818                    || $data['budget_type_id'] != $result->budget_type_id
2819                    || $data['customer_type_id'] != $result->customer_type_id
2820                    || $data['amount'] != $result->amount
2821                );
2822
2823                // AUTHORITY (SOP v2): when the feature flag is on AND the approval
2824                // matrix has a row for this (company, budget type, customer type),
2825                // the engine governs. Companies not in the matrix — and every
2826                // company while the flag is off — keep the legacy thresholds in
2827                // the else branch, so nothing loses approval gating during rollout.
2828                $matrixRow = config('approvals.use_matrix_engine')
2829                    ? (new ApprovalThresholdEngine)->resolveRow(
2830                        (int) $company->company_id,
2831                        $this->intOrNull($data['budget_type_id'] ?? null),
2832                        $this->intOrNull($data['customer_type_id'] ?? null),
2833                    )
2834                    : null;
2835
2836                if ($matrixRow !== null) {
2837                    if ($approvalInputsChanged || $questionInputsChanged) {
2838                        // FIRE-1345: gate BOTH financial-minimum inputs (margin AND
2839                        // revenue/employee/day) on budget-margin tracking. An empty
2840                        // numeric field is serialized as 0 by the frontend, so an
2841                        // unentered revenue would otherwise read 0 and trip
2842                        // `revenue_below_min`, forcing technical approval on a budget
2843                        // whose amount is nowhere near the threshold (e.g. 1 €). Same
2844                        // fix as evaluateApprovalForBudget().
2845                        //
2846                        // Gating on the flag alone is not enough: a budget can have
2847                        // margin tracking ON and still carry revenue 0 because no
2848                        // worked days were entered. Zero revenue is absence of a
2849                        // measurement, so pass null (see measuredFloatOrNull).
2850                        $marginTrackingOn = ($data['budget_margin_enabled'] ?? 0) > 0;
2851                        $eval = (new ApprovalThresholdEngine)->evaluateForRow(
2852                            $matrixRow,
2853                            $this->floatOrNull($data['amount'] ?? null),
2854                            $marginTrackingOn ? $this->measuredFloatOrNull($data['invoice_margin'] ?? null) : null,
2855                            $marginTrackingOn ? $this->measuredFloatOrNull($data['revenue_per_date_per_worked'] ?? null) : null,
2856                        );
2857
2858                        // Legacy workflow-question trigger (not part of the matrix)
2859                        // still forces a technical approval.
2860                        $reqTech = $eval['reqTechnical'];
2861                        $reqFin = $eval['reqFinancial'];
2862                        $isQuestion = 0;
2863                        if (($data['question_enabled'] ?? 0) > 0
2864                            && ! empty($data['question_ids_no'])
2865                            && $company->workflow_budget_size !== null
2866                            && (float) ($data['amount'] ?? 0) >= (float) $company->workflow_budget_size) {
2867                            $reqTech = true;
2868                            $isQuestion = 1;
2869                        }
2870
2871                        // FIRE-1572: only re-request the dimension whose own inputs
2872                        // moved — an approval that still stands is not re-asked.
2873                        $pending = $this->pendingApprovalDimensions($data, $result, $reqTech, $reqFin, $questionInputsChanged, $eval['financialMinimumsApplied']);
2874                        $pendingTech = $pending['tech'];
2875                        $pendingFin = $pending['fin'];
2876
2877                        if ($pendingTech || $pendingFin) {
2878                            $newType = ($pendingTech && $pendingFin) ? 3 : ($pendingFin ? 2 : 1);
2879                            // for_approval must match the type; a financial-only
2880                            // requirement is 2, not 1 (else the financial approver
2881                            // is blocked with approval_not_authorized).
2882                            $forApprovalVal = $newType;
2883                            $alreadyPendingSame = $result->for_approval !== null
2884                                && (int) $result->approval_type === $newType;
2885
2886                            // Mark the budget pending on the SAVE whenever it crosses
2887                            // the threshold — same as the legacy (flag-off) path, on
2888                            // any status. This is what enters the approval flow. The
2889                            // modal + confirm still control sending the approval
2890                            // email; a re-save at the same level stays silent (no new
2891                            // modal) but keeps the flag.
2892                            $data['for_approval'] = $forApprovalVal;
2893                            $data['approval_type'] = $newType;
2894
2895                            // Baseline the "notified amount" the first time a budget
2896                            // enters the circuit (was not pending before), so a later
2897                            // amount change has a reference for the X → Y comparison
2898                            // even if the request wasn't sent via the confirm step.
2899                            if ($result->for_approval === null && ! array_key_exists('importe_avisado', $data)) {
2900                                $data['importe_avisado'] = $data['amount'] ?? null;
2901                            }
2902
2903                            if (! $alreadyPendingSame) {
2904                                $needsApprovalConfirmation = [
2905                                    'approvalType' => $newType,
2906                                    'amount' => $data['amount'] ?? null,
2907                                    'isReapproval' => $result->approved_at !== null || $result->approved_at_v2 !== null,
2908                                    // The modal lists only the approver(s) actually
2909                                    // being asked — a dimension that stays approved
2910                                    // (its inputs didn't change) is not re-requested.
2911                                    'approvers' => $this->resolveApprovers(
2912                                        (int) $company->company_id,
2913                                        $pendingTech,
2914                                        $pendingFin,
2915                                    ),
2916                                ];
2917                            } elseif ($approvalInputsChanged) {
2918                                // SOP §6 / FIRE-1345: an approval-relevant figure
2919                                // (importe, margin, budget/customer type) changed on an
2920                                // already-pending budget of the SAME approval type → NO
2921                                // new email, but send the approver(s) an in-app message
2922                                // so they see the change before they approve/reject.
2923                                // importe_avisado (the formally-requested amount) is
2924                                // left untouched so the existing "amount changed since
2925                                // notified" pop-up and inbox hint still work.
2926                                $oldAmount = $result->importe_avisado ?? $result->amount;
2927                                $newAmount = $data['amount'] ?? $result->amount;
2928                                $this->notifyApproversBudgetChanged($result, $company, $pendingTech, $pendingFin, $oldAmount, $newAmount);
2929                            }
2930                        } elseif ($result->for_approval !== null) {
2931                            // FIRE §12 / FIRE-1345: matched a row and it no longer
2932                            // requires any approval (amount dropped / margin recovered)
2933                            // → clear the flag AND tell the approver(s) who were
2934                            // assigned so they stop waiting for it.
2935                            $priorDims = $this->approvalDimsFromType($this->intOrNull($result->approval_type));
2936                            $this->notifyApproversNoLongerRequired($result, $company, $priorDims['tech'], $priorDims['fin']);
2937                            $data['for_approval'] = null;
2938                            $data['approval_type'] = null;
2939                        }
2940                    }
2941                } else {
2942                    $project = TblProjectTypes::where('company_id', $company->company_id)
2943                        ->where('budget_type_id', $data['budget_type_id'])
2944                        ->first();
2945
2946                    if ($approvalInputsChanged) {
2947                        if ($project) {
2948                            if (! empty($project->customer_type_ids)) {
2949                                $customerTypeIds = array_map(intval(...), explode(',', (string) $project->customer_type_ids));
2950                            }
2951                            // Strictly positive, for the same reason the tier-2
2952                            // guard below is: `minimum_order_size` is a varchar and
2953                            // "0" / "0.0000" / "" are the operator's "no threshold"
2954                            // placeholders. `!= null` lets those through, and since
2955                            // `amount >= 0` always holds, every budget in such a
2956                            // company would demand approval.
2957                            if ((float) $project->minimum_order_size > 0 && in_array($data['customer_type_id'], $customerTypeIds)) {
2958                                if ((float) $data['amount'] >= (float) $project->minimum_order_size) {
2959                                    $data['for_approval'] = 1;
2960                                    $n = 1;
2961                                }
2962                            }
2963                            $minimumOrderSize = $project->minimum_order_size;
2964
2965                            // FIRE-1092: `minimum_order_size_v2` is a decimal column
2966                            // and Eloquent returns it as the string "0.0000" when the
2967                            // operator left it at 0 (their "no tier-2 threshold" placeholder).
2968                            // PHP 8 no longer coerces numeric strings to null in loose
2969                            // comparisons, so `"0.0000" != null` is TRUE — promotion to
2970                            // dual-level approval would fire even when the operator meant
2971                            // "single level is enough", which strands budgets forever in
2972                            // companies that have no `tbl_approvers_v2` rows. Require the
2973                            // threshold to be strictly positive before promoting.
2974                            if ($n == 1 && (float) $project->minimum_order_size_v2 > 0 && in_array($data['customer_type_id'], $customerTypeIds)) {
2975                                if ($data['amount'] >= $project->minimum_order_size_v2) {
2976                                    $data['for_approval'] = 3;
2977                                    $n = 3;
2978                                }
2979                            }
2980                        } else {
2981                            if (! empty($company->customer_type_ids)) {
2982                                $customerTypeIds = array_map(intval(...), explode(',', (string) $company->customer_type_ids));
2983                            }
2984                            // Same strictly-positive guard as the project branch.
2985                            if ((float) $company->minimum_order_size > 0 && in_array($data['customer_type_id'], $customerTypeIds)) {
2986                                if ((float) $data['amount'] >= (float) $company->minimum_order_size) {
2987                                    $data['for_approval'] = 1;
2988                                    $n = 1;
2989                                }
2990                                $minimumOrderSize = $company->minimum_order_size;
2991
2992                                // FIRE-1092: same `> 0` guard as the project-level branch
2993                                // above — `!= null` is unreliable for a decimal column.
2994                                if ($n == 1 && (float) $company->minimum_order_size_v2 > 0 && in_array($data['customer_type_id'], $customerTypeIds)) {
2995                                    if ($data['amount'] >= $company->minimum_order_size_v2) {
2996                                        $data['for_approval'] = 3;
2997                                        $n = 3;
2998                                    }
2999                                }
3000                            }
3001                        }
3002                    }
3003
3004                    if ($data['budget_margin_enabled'] > 0) {
3005                        $costOfLabor = $data['cost_of_labor'];
3006                        $totalCostOfJob = $data['total_cost_of_job'];
3007
3008                        if ($totalCostOfJob > 0) {
3009                            $invoiceMargin = $data['invoice_margin'] ?? 0;
3010                        }
3011
3012                        $minimumMargin = $company->minimum_margin;
3013                        if (! empty($company->customer_type_ids)) {
3014                            $customerTypeIds = array_map(intval(...), explode(',', (string) $company->customer_type_ids));
3015                        }
3016
3017                        if ($project) {
3018                            $minimumMargin = $project->minimum_margin;
3019                            $minimumOrderSize = $project->minimum_order_size;
3020                            if (! empty($project->customer_type_ids)) {
3021                                $customerTypeIds = array_map(intval(...), explode(',', (string) $project->customer_type_ids));
3022                            }
3023                        }
3024
3025                        // A 0% margin must require approval. Use STRICT null check:
3026                        // the loose `!= null` is fatal here because PHP evaluates
3027                        // `0 != null` as false, so a genuine 0 margin was skipped.
3028                        // `!== null` lets 0 (and negatives) through while still
3029                        // ignoring the "no margin computed" sentinel.
3030                        if ($invoiceMargin !== null && $invoiceMargin < $minimumMargin) {
3031                            if (in_array($data['customer_type_id'], $customerTypeIds)) {
3032                                // FIRE-1229: do not downgrade an already-promoted
3033                                // dual-level approval. Tier-2 (`n=3`, amount crossed
3034                                // `minimum_order_size_v2`) is strictly stronger than
3035                                // the margin-flagged tier-1 (`n=2`) — a budget that
3036                                // qualifies for both reasons should keep its
3037                                // dual-level email routing so `tbl_approvers_v2`
3038                                // receives the notification. Only escalate from
3039                                // "no approval" or "tier-1 technical" up to
3040                                // tier-1 margin; never demote from tier-2.
3041                                //
3042                                // for_approval MUST mirror the approval type: a
3043                                // margin-only (financial) requirement is 2, not
3044                                // 1. Storing 1 mislabels the order as technical,
3045                                // so the financial approver is blocked
3046                                // (approval_not_authorized) and the frontend
3047                                // hides the pending state (finance-only was
3048                                // invisible). Keep 3 (dual) if the order-size
3049                                // tier already promoted it.
3050                                if (! isset($data['for_approval']) || $data['for_approval'] !== 3) {
3051                                    $data['for_approval'] = 2;
3052                                }
3053                                if ($n !== 3) {
3054                                    $n = 2;
3055                                }
3056                            }
3057                        }
3058                    }
3059
3060                    $isQuestion = 0;
3061                    $questionIdsNo = [];
3062                    if (isset($data['question_enabled'])) {
3063                        if ($data['question_ids_no'] != $result->question_ids_no
3064                            || $data['budget_type_id'] != $result->budget_type_id
3065                            || $data['customer_type_id'] != $result->customer_type_id
3066                            || $data['amount'] != $result->amount) {
3067                            if ($data['question_enabled'] > 0 && $n == 0) {
3068                                if (! empty($data['question_ids_no'])) {
3069                                    $questionIdsNo = array_map(intval(...), explode(',', (string) $data['question_ids_no']));
3070
3071                                    if ($company->workflow_budget_size != null) {
3072                                        if ($data['amount'] >= $company->workflow_budget_size) {
3073                                            $isQuestion = 1;
3074                                            $data['for_approval'] = 1;
3075                                            $n = 1;
3076                                        }
3077                                    }
3078                                    $minimumOrderSize = $company->workflow_budget_size;
3079
3080                                }
3081                            }
3082                        }
3083                    }
3084
3085                    if (($n == 1 || $n == 3) && $result->for_approval != $n) {
3086                        $sendApprovalNotification = true;
3087                        $approvalMinimumOrderSize = $minimumOrderSize;
3088                        $approvalId = $result->id;
3089                        $approvalForAdd = $result->for_add;
3090                        $approvalIsQuestion = $isQuestion;
3091                        $approvalQuestionIdsNo = $questionIdsNo;
3092                        $approvalN = $n;
3093                    }
3094
3095                    if ($n == 2) {
3096                        $sendApprovalMarginNotification = true;
3097                        $approvalMinimumMargin = $minimumMargin;
3098                        $approvalId = $result->id;
3099                        $approvalForAdd = $result->for_add;
3100                        $approvalInvoiceMargin = $invoiceMargin;
3101                    }
3102
3103                    // FIRE-1345 (legacy path): figures changed on a budget already
3104                    // pending at the SAME technical level (no escalation queued above,
3105                    // and not the margin path which re-emails on its own) → NO new
3106                    // email, but an in-app message so the approver sees the change.
3107                    // Mirrors the matrix-engine branch.
3108                    if ($approvalInputsChanged
3109                        && ($n == 1 || $n == 3)
3110                        && $result->for_approval !== null
3111                        && ! $sendApprovalNotification) {
3112                        $priorDims = $this->approvalDimsFromType($this->intOrNull($result->approval_type ?? $n));
3113                        $oldAmount = $result->importe_avisado ?? $result->amount;
3114                        $newAmount = $data['amount'] ?? $result->amount;
3115                        $this->notifyApproversBudgetChanged($result, $company, $priorDims['tech'], $priorDims['fin'], $oldAmount, $newAmount);
3116                    }
3117
3118                    // Persist WHICH kind of approval this is so it stays
3119                    // recoverable after save. `for_approval` alone collapses a
3120                    // technical (order-size, $n=1) and a financial (margin,
3121                    // $n=2) single-level approval into the same value 1, so once
3122                    // posted there's no way to tell them apart — only the
3123                    // dual-level case (3) is distinguishable. `approval_type`
3124                    // keeps the original reason:
3125                    //   1 = technical (order size / tbl_approvers, V1)
3126                    //   2 = financial (margin / tbl_approvers_v2, V2)
3127                    //   3 = both
3128                    if ($n == 1 || $n == 2 || $n == 3) {
3129                        $data['approval_type'] = $n;
3130                    }
3131
3132                    // FIRE §12 — clear a stale approval flag. When an approval input
3133                    // changed (so we truly re-evaluated) and the budget now requires
3134                    // NO approval of any kind ($n == 0), but it was previously flagged,
3135                    // drop the flag: "Aprobación requerida?" → No, the red banner
3136                    // disappears and the row leaves the "= Sí" filter. Guarded by
3137                    // $approvalInputsChanged so an unrelated edit can't wipe a pending
3138                    // approval it never re-evaluated. Note: an already-approved budget
3139                    // has for_approval = null already, so this never touches it.
3140                    if ($approvalInputsChanged && $n == 0 && $result->for_approval !== null) {
3141                        // FIRE-1345: tell the previously-assigned approver(s) it no
3142                        // longer requires approval before clearing the flag.
3143                        $priorDims = $this->approvalDimsFromType($this->intOrNull($result->approval_type));
3144                        $this->notifyApproversNoLongerRequired($result, $company, $priorDims['tech'], $priorDims['fin']);
3145                        $data['for_approval'] = null;
3146                        $data['approval_type'] = null;
3147                    }
3148                } // end legacy (non-matrix) approval branch
3149            }
3150        }
3151
3152        $data['updated_at'] = date('Y-m-d H:i:s');
3153        $job['updated_at'] = $data['updated_at'];
3154
3155        // FIRE-1551: recomputar g3w_warning y g3w_warning_fields con la
3156        // fuente canónica (PresupuestosService::computeG3wWarning) usando
3157        // los valores post-edit fusionados con los actuales del row. Antes
3158        // esto era un `$data['g3w_warning'] = 0;` hardcoded que apagaba el
3159        // flag en cada edit y dejaba `g3w_warning_fields` stale — 6607 filas
3160        // en prod con ese patrón. Ver findings/FIRE-1551_Investigation.md.
3161        $rowForG3wCheck = (object) [
3162            'budget_status_id' => $data['budget_status_id'] ?? $result->budget_status_id,
3163            'budget_type_id' => $data['budget_type_id'] ?? $result->budget_type_id,
3164            'commercial' => array_key_exists('commercial', $data) ? $data['commercial'] : $result->commercial,
3165            'source_id' => $data['source_id'] ?? $result->source_id,
3166            'send_channel' => $data['send_channel'] ?? ($result->send_channel ?? 'email'),
3167            'email' => array_key_exists('email', $data) ? $data['email'] : $result->email,
3168            'client' => array_key_exists('client', $data) ? $data['client'] : $result->client,
3169            'amount' => array_key_exists('amount', $data) ? $data['amount'] : $result->amount,
3170        ];
3171        $g3w = app(PresupuestosService::class)->computeG3wWarning($rowForG3wCheck);
3172        $data['g3w_warning'] = $g3w['warning'];
3173        $data['g3w_warning_fields'] = $g3w['fields'];
3174
3175        if ($result->for_add == 1) {
3176            TblCompanies::where('company_id', $result->company_id)->update(['last_id' => $data['quote_id'], 'before_last_id' => $data['quote_id']]);
3177        }
3178
3179        $forApproval = @$data['for_approval'] ?? null;
3180
3181        // FIRE-1572: clear the decision slots ONLY for the dimension(s) actually
3182        // being (re-)requested, given by the type just written. Wiping all eight
3183        // unconditionally destroyed an approval that still stood — e.g. a margin
3184        // edit on a both-approved budget re-asked Finance for an amount it had
3185        // already signed off. Clearing the re-requested dimension is still
3186        // required: approverActingType() only opens a slot that is empty, so
3187        // leaving a stale approval there would deadlock its approver.
3188        if ($forApproval != null) {
3189            $requestedType = (int) ($data['approval_type'] ?? $forApproval);
3190
3191            if ($requestedType === 1 || $requestedType === 3) {
3192                $data['approved_at'] = null;
3193                $data['approved_by'] = null;
3194                $data['rejected_at'] = null;
3195                $data['rejected_by'] = null;
3196            }
3197
3198            if ($requestedType === 2 || $requestedType === 3) {
3199                $data['approved_at_v2'] = null;
3200                $data['approved_by_v2'] = null;
3201                $data['rejected_at_v2'] = null;
3202                $data['rejected_by_v2'] = null;
3203            }
3204        }
3205
3206        $actualQuotationValue = TblQuotations::where('id', $id)->first();
3207
3208        $differences = $this->compareArrays($data, $actualQuotationValue);
3209        $primaryAprovalsFields = ['budget_type_id', 'customer_type_id', 'budget_margin_enabled', 'amount', 'invoice_margin', 'margin_for_the_company', 'margin_on_invoice_per_day_per_worker', 'gross_margin'];
3210
3211        if (is_null($actualQuotationValue->customer_type_id)) {
3212            $needToSendReminder = true;
3213        }
3214
3215        foreach ($differences as $field => $value) {
3216            if (in_array($field, $primaryAprovalsFields)) {
3217                $needToSendReminder = true;
3218            }
3219            $statusId = $data['budget_status_id'] ?? $actualQuotationValue->budget_status_id;
3220            $categoryLog = $statusId == 6 ? 1 : 4;
3221            $this->addUpdateLog($id, $userId, $field, $value['oldData'], $value['newData'], $categoryLog);
3222        }
3223
3224        // check if the quotation are a solicitud and the user write the internal quote id
3225
3226        $budgetRequest = TblQuotations::where('id', $id)->first();
3227
3228        if (
3229            ($budgetRequest->budget_status_id == 6 || $budgetRequest->budget_status_id == 8)
3230            && (! is_null($data['internal_quote_id'] ?? null) && $data['internal_quote_id'] !== '')
3231            && (TblQuotations::where('internal_quote_id', $data['internal_quote_id'])
3232                ->where('company_id', $quoteCompanyId)
3233                ->whereNotIn('budget_status_id', [6, 8])
3234                ->exists())
3235            && ($id !== '')
3236        ) {
3237            $createdAt = $budgetRequest->created_at;
3238            $lastFollowUpComment = $budgetRequest->last_follow_up_comment;
3239
3240            TblQuotations::where('id', $id)->first()->update(['internal_quote_id', $data['internal_quote_id']]);
3241
3242            $solicitudLogs = TblQuotationsLog::where('quotation_id', $id)->get();
3243
3244            $budget = TblQuotations::where('internal_quote_id', $data['internal_quote_id'])->where('company_id', $quoteCompanyId)->first();
3245            TblFiles::where('quotation_id', $id)->where('is_internal', 1)->update(['quotation_id' => $budget->id]);
3246
3247            $this->callDeleteQuotation($id, $quoteCompanyId, $userId, $data['updated_by']);
3248
3249            $id = $budget->id;
3250
3251            $dataToChange = array_intersect_key($data, array_flip([
3252                'internal_quote_id',
3253                'client',
3254                'phone_number',
3255                'email',
3256                'source_id',
3257                'created_by',
3258                'updated_by',
3259                'updated_at',
3260                'request_date',
3261                'last_follow_up_comment',
3262            ]));
3263
3264            // FIRE-1063: when merging a solicitud into an existing
3265            // G3W-derived budget, the solicitud's manually-entered
3266            // client info wins (it's the latest sales-side input).
3267            // Empty solicitud values fall through to the budget's
3268            // existing data, which traces back to G3W's
3269            // `servicio → cliente` chain when the budget was originally
3270            // synced — so the resulting per-field cascade is
3271            // solicitud → G3W servicio → G3W cliente. Pre-fix only
3272            // `phone_number` had this guard; `client` and `email` were
3273            // unconditionally written by the merge, so an empty
3274            // solicitud field would wipe the budget's good value.
3275            foreach (['phone_number', 'client', 'email'] as $field) {
3276                $value = $data[$field] ?? null;
3277                if ($value === null
3278                    || trim((string) $value) === ''
3279                    || strtolower(trim((string) $value)) === 'null'
3280                    || empty($dataToChange[$field])
3281                ) {
3282                    unset($dataToChange[$field]);
3283                }
3284            }
3285
3286            // FIRE-1063: pre-fix the merge built $dataToChange but
3287            // never wrote it. The duplicate `if` block below at
3288            // :1554 was the only writer, and it can never fire because
3289            // `$id` has been reassigned to the budget — its
3290            // budget_status_id is no longer 6/8. As a result, the
3291            // solicitud's client/phone/email and the merge metadata
3292            // (preserved created_at, concatenated follow-up comment)
3293            // never made it onto the budget row even though the rest
3294            // of the merge — file moves, deletion of the solicitud —
3295            // completed normally.
3296            $dataToChange['budget_status_id'] = $budget->budget_status_id;
3297            $dataToChange['created_at'] = $createdAt;
3298            $dataToChange['last_follow_up_comment'] = trim(
3299                ($budget->last_follow_up_comment ?? '')."\n".($lastFollowUpComment ?? '')
3300            );
3301
3302            // FIRE-1063: if the budget was at 22 (Correo erroneo) only
3303            // because its email was previously empty/invalid, and the
3304            // merge fills in a now-valid email with no SendGrid
3305            // evidence of a real delivery failure (`x_message_id IS
3306            // NULL`), demote out of bucket 22 to 11 (Listo para enviar)
3307            // — the natural pre-send bucket. Without this, the row
3308            // stays in "Correo erroneo" forever even though the email
3309            // problem that put it there has been resolved by the
3310            // merge.
3311            $mergedEmail = $dataToChange['email'] ?? $budget->email;
3312            if (
3313                (int) $budget->budget_status_id === 22
3314                && $budget->x_message_id === null
3315                && $mergedEmail !== null
3316                && ! $this->isInvalidEmail($mergedEmail)
3317            ) {
3318                $dataToChange['budget_status_id'] = 11;
3319            }
3320
3321            TblQuotations::where('id', $id)->update($dataToChange);
3322
3323            if ($solicitudLogs->isNotEmpty()) {
3324                $nuevosLogs = array_map(function ($log) use ($budget) {
3325                    unset($log['id']);
3326                    $log['quotation_id'] = $budget->id;
3327
3328                    return $log;
3329                }, $solicitudLogs->toArray());
3330
3331                TblQuotationsLog::insert($nuevosLogs);
3332            }
3333
3334            // check if the quotation are a solicitud and the user write the internal quote id
3335
3336            $budgetRequest = TblQuotations::where('id', $id)->first();
3337
3338            if (
3339                ($budgetRequest->budget_status_id == 6 || $budgetRequest->budget_status_id == 8)
3340                && (! is_null($data['internal_quote_id'] ?? null) && $data['internal_quote_id'] !== '')
3341                && TblQuotations::where('internal_quote_id', $data['internal_quote_id'])->where('company_id', $quoteCompanyId)->exists()
3342                && (! is_null($id) && $id !== '')
3343            ) {
3344                $createdAt = $budgetRequest->created_at;
3345                $lastFollowUpComment = $budgetRequest->last_follow_up_comment;
3346
3347                TblQuotations::where('id', $id)->first()->update(['internal_quote_id', $data['internal_quote_id']]);
3348
3349                $solicitudLogs = TblQuotationsLog::where('quotation_id', $id)->get();
3350
3351                $budget = TblQuotations::where('internal_quote_id', $data['internal_quote_id'])->where('company_id', $quoteCompanyId)->first();
3352                TblFiles::where('quotation_id', $id)->where('is_internal', 1)->update(['quotation_id' => $budget->id]);
3353
3354                $this->callDeleteQuotation($id, $quoteCompanyId, $userId, $data['updated_by']);
3355
3356                $id = $budget->id;
3357
3358                $dataToChange = array_intersect_key($data, array_flip([
3359                    'internal_quote_id',
3360                    'client',
3361                    'phone_number',
3362                    'email',
3363                    'source_id',
3364                    'created_by',
3365                    'updated_by',
3366                    'updated_at',
3367                    'request_date',
3368                    'last_follow_up_comment',
3369                ]));
3370
3371                if ($data['phone_number'] === null || $data['phone_number'] === '' || empty($dataToChange['phone_number'])) {
3372                    unset($dataToChange['phone_number']);
3373                }
3374
3375                $dataToChange['budget_status_id'] = $budget->budget_status_id;
3376                $dataToChange['created_at'] = $createdAt;
3377                $dataToChange['last_follow_up_comment'] = $budget->last_follow_up_comment."\n".$lastFollowUpComment;
3378
3379                // FIRE-1551: recomputar flag + fields con la fuente canónica.
3380                // Antes había DOS bloques inline duplicados (uno aquí y otro
3381                // ~40 líneas abajo) que solo comprobaban 5 campos ignorando
3382                // FIRE-1278 y FIRE-1377, escribían a $data (nunca persistido
3383                // en esa rama) y dejaban $dataToChange sin g3w_warning ni
3384                // g3w_warning_fields. Ahora una única llamada + persistencia
3385                // en ambos arrays. Rama solicitud→presupuesto por
3386                // duplicación de internal_quote_id.
3387                $rowForG3wCheck = (object) [
3388                    'budget_status_id' => $budget->budget_status_id,
3389                    'budget_type_id' => $budget->budget_type_id,
3390                    'commercial' => $dataToChange['commercial'] ?? $budget->commercial,
3391                    'source_id' => $dataToChange['source_id'] ?? $budget->source_id,
3392                    'send_channel' => $dataToChange['send_channel'] ?? ($budget->send_channel ?? 'email'),
3393                    'email' => $dataToChange['email'] ?? $budget->email,
3394                    'client' => $dataToChange['client'] ?? $budget->client,
3395                    'amount' => $dataToChange['amount'] ?? $budget->amount,
3396                ];
3397                $g3w = app(PresupuestosService::class)->computeG3wWarning($rowForG3wCheck);
3398                $data['g3w_warning'] = $g3w['warning'];
3399                $data['g3w_warning_fields'] = $g3w['fields'];
3400                $dataToChange['g3w_warning'] = $g3w['warning'];
3401                $dataToChange['g3w_warning_fields'] = $g3w['fields'];
3402
3403                TblQuotations::where('id', $id)->update($dataToChange);
3404
3405                if (! empty($solicitudLogs)) {
3406                    $nuevosLogs = array_map(function (array $log) use ($budget): array {
3407                        unset($log['id']);
3408                        $log['quotation_id'] = $budget->id;
3409
3410                        return $log;
3411                    }, $solicitudLogs);
3412
3413                    TblQuotationsLog::insert($nuevosLogs);
3414                }
3415
3416                // FIRE-1551: el bloque duplicado inmediatamente arriba en el
3417                // código legacy hacía exactamente el mismo cálculo y persistía
3418                // el mismo $dataToChange. Se ha unificado — el UPDATE de abajo
3419                // repite el mismo state ya computado. Se mantiene el update
3420                // duplicado por seguridad hasta que se refactorice el flujo
3421                // completo.
3422
3423                TblQuotations::where('id', $id)->update($dataToChange);
3424
3425                if ($solicitudLogs->isNotEmpty()) {
3426                    $nuevosLogs = array_map(function ($log) use ($budget) {
3427                        unset($log['id']);
3428                        $log['quotation_id'] = $budget->id;
3429
3430                        return $log;
3431                    }, $solicitudLogs->toArray());
3432
3433                    TblQuotations::where('id', $id)->update(
3434                        [
3435                            'accepted_at' => $data['updated_at'],
3436                            'accepted_by' => $data['updated_by'],
3437                        ]
3438                    );
3439                }
3440
3441            }
3442
3443        } else {
3444            // FIRE-864 / FIRE-1377: if email is invalid (blacklisted, malformed,
3445            // or empty) and status is sendable, set to 22 (Correo erroneo). Only
3446            // for email-channel budgets — correo ordinario and WhatsApp budgets
3447            // never require a valid email and must never land in "emails with
3448            // error". Effective channel falls back to the stored value when the
3449            // payload doesn't carry it.
3450            $effectiveChannel = $data['send_channel']
3451                ?? TblQuotations::where('id', $id)->value('send_channel')
3452                ?? 'email';
3453            if ($effectiveChannel === 'email'
3454                && isset($data['email']) && $this->isInvalidEmail($data['email'])
3455                && isset($data['budget_status_id']) && in_array($data['budget_status_id'], [1, 2, 11, 17])) {
3456                $data['budget_status_id'] = 22;
3457            }
3458
3459            TblQuotations::where('id', $id)->update($data);
3460        }
3461
3462        TblOngoingJobs::where('quotation_id', $id)->update($job);
3463
3464        $this->update_commercial_numbers($result->company_id);
3465
3466        // Retire the quote this one replaces: status 20 (Rechazado-duplicado),
3467        // audit log, and the replaced_quotes link. Re-fetched rather than
3468        // reusing $result, which is the pre-update row. Non-fatal by design:
3469        // the new quote is already saved and must not be lost if the target
3470        // went stale while the form sat open.
3471        if ($replacedQuoteId !== '') {
3472            $newQuote = TblQuotations::where('id', $id)->first();
3473
3474            if ($newQuote) {
3475                $this->linkReplacedQuote(
3476                    $newQuote,
3477                    $replacedQuoteId,
3478                    (int) ($newQuote->company_id ?? 0),
3479                    $data['updated_by'] ?? null
3480                );
3481            }
3482        }
3483
3484        if ($result->budget_status_id != $data['budget_status_id']
3485            && $data['budget_status_id'] == 3) {
3486            $this->send_acceptance_notification($result->id, $result->company_id, $userId, $data['updated_by']);
3487
3488            TblQuotations::where('id', $id)->update(
3489                [
3490                    'accepted_at' => $data['updated_at'],
3491                    'accepted_by' => $data['updated_by'],
3492                ]
3493            );
3494
3495            // Promote lead to general when quotation is accepted
3496            $quotation = TblQuotations::find($id);
3497            if ($quotation && $quotation->client_id) {
3498                Client::where('id', $quotation->client_id)
3499                    ->where('client_type_id', Client::TYPE_LEAD)
3500                    ->update(['client_type_id' => Client::TYPE_GENERAL]);
3501            }
3502        }
3503
3504        // A manual status change TO Enviado / Enviado - IA from a different
3505        // status is a send, whatever the channel: the rep often sends from their
3506        // own mailbox (or by post, FIRE-1377's correo) and only records it here.
3507        // sent_date becomes this send (the latest), replacing the old
3508        // set-only-if-empty correo/WhatsApp rule. Accepting a quotation that was
3509        // never sent counts the acceptance as its send.
3510        $newStatus = $data['budget_status_id'] ?? $result->budget_status_id;
3511        if (QuotationSendRecorder::isSentTransition($result->budget_status_id, $newStatus)) {
3512            QuotationSendRecorder::record((int) $id, QuotationSendRecorder::MANUAL_STATUS,
3513                $data['updated_by'] ?? null, $data['updated_at'] ?? null);
3514        } elseif ((int) $newStatus === QuotationSendRecorder::ACCEPTED_STATUS_ID
3515            && (int) $result->budget_status_id !== QuotationSendRecorder::ACCEPTED_STATUS_ID
3516            && QuotationSendRecorder::neverSent((int) $id)) {
3517            QuotationSendRecorder::record((int) $id, QuotationSendRecorder::ACCEPTANCE,
3518                $data['updated_by'] ?? null, $data['updated_at'] ?? null);
3519        }
3520        // Sent with no send on record (e.g. re-dated by hand): sent_date
3521        // follows issue_date instead of staying empty.
3522        QuotationSendRecorder::fallbackToIssueDate((int) $id, $result->issue_date);
3523
3524        if ($files) {
3525
3526            $uploadedFiles = [];
3527            $i = 0;
3528
3529            $combinedFilesSize = 0;
3530            foreach ($files as $file) {
3531                $i++;
3532                $origFilename = $file->getClientOriginalName();
3533                $filename = $result->id.'-'.$result->company_id.'-FC'.time().'-'.$origFilename;
3534
3535                $combinedFilesSize = $combinedFilesSize + $file->getSize();
3536
3537                if ($combinedFilesSize > 25000000) {
3538                    return response(['message' => 'KO', 'error' => __('language.file_size_exceeded')]);
3539                }
3540
3541                if (in_array($origFilename, $uploadedFiles)) {
3542                    $origFilename = $origFilename.$i;
3543                }
3544
3545                // $fileContent = file_get_contents($file->getRealPath());
3546                // $fileHash = hash('sha256', $fileContent);
3547
3548                $s3path = Storage::disk('s3')->putFileAs(
3549                    'uploads',
3550                    $file,
3551                    $filename,
3552                    [
3553                        'ContentType' => $file->getMimeType(),
3554                    ]
3555                );
3556
3557                TblFiles::create(
3558                    [
3559                        'quotation_id' => $id,
3560                        'original_name' => $origFilename,
3561                        'filename' => $filename,
3562                        'uploaded_by' => $data['updated_by'],
3563                        // 'file' => $fileContent,
3564                        'file_size' => $file->getSize(),
3565                        // 'file_hash' => $fileHash,
3566                        'mime_type' => $file->getMimeType(),
3567                        'uploaded_at' => now(),
3568                    ]
3569                );
3570                $this->addUpdateLog($id, $data['updated_by'], 'upload_attachment', null, $filename, 4);
3571
3572                $uploadedFiles[] = $file->getClientOriginalName();
3573            }
3574        }
3575
3576        if ($internalFiles) {
3577
3578            $uploadedFiles = [];
3579            $i = 0;
3580
3581            $combinedFilesSize = 0;
3582            foreach ($internalFiles as $file) {
3583                $i++;
3584                $origFilename = $file->getClientOriginalName();
3585                $filename = $result->id.'-'.$result->company_id.'-FI'.time().'-'.$origFilename;
3586
3587                $combinedFilesSize = $combinedFilesSize + $file->getSize();
3588
3589                if ($combinedFilesSize > 25000000) {
3590                    return response(['message' => 'KO', 'error' => __('language.file_size_exceeded')]);
3591                }
3592
3593                if (in_array($origFilename, $uploadedFiles)) {
3594                    $origFilename = $origFilename.$i;
3595                }
3596
3597                // $fileContent = file_get_contents($file->getRealPath());
3598                // $fileHash = hash('sha256', $fileContent);
3599
3600                $s3path = Storage::disk('s3')->putFileAs(
3601                    'uploads',
3602                    $file,
3603                    $filename,
3604                    [
3605                        'ContentType' => $file->getMimeType(),
3606                    ]
3607                );
3608
3609                TblFiles::create(
3610                    [
3611                        'quotation_id' => $id,
3612                        'original_name' => $origFilename,
3613                        'filename' => $filename,
3614                        'uploaded_by' => $data['updated_by'],
3615                        // 'file' => $fileContent,
3616                        'file_size' => $file->getSize(),
3617                        // 'file_hash' => $fileHash,
3618                        'mime_type' => $file->getMimeType(),
3619                        'uploaded_at' => now(),
3620                        'is_internal' => 1,
3621                    ]
3622                );
3623                $this->addUpdateLog($id, $data['updated_by'], 'upload_attachment', null, $filename, 4);
3624
3625                $uploadedFiles[] = $file->getClientOriginalName();
3626            }
3627        }
3628
3629        $query = "SELECT
3630                        a.id,
3631                        a.quote_id,
3632                        a.company_id,
3633                        b.name company_name,
3634                        a.client,
3635                        c.name client_type,
3636                        c.customer_type_id,
3637                        a.request_date,
3638                        a.visit_date,
3639                        a.issue_date,
3640                        a.acceptance_date,
3641                        a.internal_quote_id,
3642                        DATE_FORMAT(a.request_date, '%d/%m/%Y') request_date_translate,
3643                        DATE_FORMAT(a.issue_date, '%d/%m/%Y') issue_date_translate,
3644                        DATE_FORMAT(a.acceptance_date, '%d/%m/%Y') acceptance_date_translate,
3645                        DATE_FORMAT(a.last_follow_up_date, '%d/%m/%Y') last_follow_up_date_translate,
3646                        -- DATEDIFF(a.issue_date, a.request_date) duration,
3647                        a.phone_number,
3648                        a.email,
3649                        a.send_channel,
3650                        a.direccion_postal,
3651                        a.sent_date,
3652                        a.duration,
3653                        a.order_number,
3654                        d.name 'type',
3655                        d.budget_type_id,
3656                        e.name 'status',
3657                        e.budget_status_id,
3658                        f.name source,
3659                        f.source_id,
3660                        a.codigo_id,
3661                        a.amount,
3662                        g.name reason_for_not_following_up,
3663                        a.reason_for_not_following_up_id,
3664                        a.reason_for_rejection_id,
3665                        a.last_follow_up_date,
3666                        a.last_follow_up_comment,
3667                        CASE WHEN a.reason_for_rejection_id IS NULL THEN a.reason_for_rejection ELSE h.name END reason_for_rejection,
3668                        a.commercial,
3669                        a.created_by,
3670                        a.created_at,
3671                        a.updated_by,
3672                        a.for_approval,
3673                        a.approval_type,
3674                        a.box_work_g3w,
3675                        a.people_assigned_to_the_job,
3676                        a.duration_of_job_in_days,
3677                        a.estimated_cost_of_materials,
3678                        a.budget_margin_enabled,
3679                        a.labor_manual_override,
3680                        a.question_enabled,
3681                        a.cost_of_labor,
3682                        a.total_cost_of_job,
3683                        CASE WHEN a.budget_margin_enabled > 0 THEN a.invoice_margin ELSE NULL END invoice_margin,
3684                        CASE WHEN a.budget_margin_enabled > 0 THEN a.margin_for_the_company ELSE NULL END margin_for_the_company,
3685                        a.margin_on_invoice_per_day_per_worker,
3686                        a.revenue_per_date_per_worked,
3687                        a.commission_cost,
3688                        a.commission_pct,
3689                        a.gross_margin,
3690                        a.labor_percentage,
3691                        a.question_ids,
3692                        a.question_ids_no,
3693                        a.approved_at,
3694                        a.approved_by,
3695                        a.rejected_at,
3696                        a.rejected_by,
3697                        a.approved_at_v2,
3698                        a.approved_by_v2,
3699                        a.rejected_at_v2,
3700                        a.rejected_by_v2,
3701                        a.accepted_at,
3702                        a.accepted_by,
3703                        a.is_validated,
3704                        a.maintenance_potential,
3705                        a.coverage_contract_signed,
3706                        a.resource_id,
3707                        a.x_status,
3708                        a.likehood,
3709                        a.updated_at
3710                    FROM
3711                        tbl_quotations a
3712                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
3713                        LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
3714                        LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
3715                        LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
3716                        LEFT JOIN tbl_sources f ON a.source_id = f.source_id
3717                        LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
3718                        LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
3719                        LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
3720                    WHERE a.id = {$id}";
3721
3722        $result = DB::select($query);
3723
3724        if ($sendNotification) {
3725            $this->send_notification(
3726                $commercial->email,
3727                $userId,
3728                $data['quote_id'],
3729                $id,
3730                $status->name,
3731                $commercial->id,
3732                $company?->name ?? '',
3733                0,
3734                $quoteCompanyId,
3735                $data['internal_quote_id']
3736            );
3737        }
3738
3739        // Approval circuit v2 (SOP §5) — CONFIRMATION GATE.
3740        //
3741        // We no longer auto-send the approval email on save. When this save
3742        // turns a budget that did NOT require approval into one that does (or
3743        // escalates it from technical-only to Ambas), we hand the details back
3744        // to the frontend, which shows the confirmation modal; the email is
3745        // sent only when the comercial confirms (confirmApprovalRequest). A
3746        // re-save of an already-pending budget at the same level stays silent.
3747        //
3748        // `$sendApprovalNotification` / `$sendApprovalMarginNotification` are the
3749        // recompute's "a new approval requirement was detected this save" flags;
3750        // they carried the old auto-send and now drive the modal instead.
3751        // Legacy path (flag off / company not in the matrix). Skipped when the
3752        // engine's draft-until-confirm path already populated the payload above.
3753        if ($needsApprovalConfirmation === null
3754            && ($sendApprovalNotification || $sendApprovalMarginNotification)
3755            && $forApproval != null
3756            && ($previousForApproval == null || $forApproval > $previousForApproval)
3757        ) {
3758            $approvalTypeForModal = $data['approval_type'] ?? $approvalN ?? null;
3759            $needsApprovalConfirmation = [
3760                'approvalType' => $approvalTypeForModal,        // 1 technical · 2 margin(technical) · 3 both
3761                'amount' => $data['amount'] ?? null,
3762                'approvers' => $this->resolveApprovers(
3763                    (int) $quoteCompanyId,
3764                    in_array($approvalTypeForModal, [1, 2, 3], true),
3765                    $approvalTypeForModal == 3,
3766                ),
3767            ];
3768        }
3769
3770        // FIRE-1199: removed the `budget_status_id == 6` gate so the duplicate
3771        // checker runs on every update path, not only Solicitud. See create_quotation
3772        // for the same change + rationale.
3773        if (isset($result['budget_status_id'])) {
3774            $data = [
3775                'id' => $result['id'] ?? null,
3776                'client' => $result['client'] ?? null,
3777                'email' => $result['email'] ?? null,
3778                'phone_number' => $result['phone_number'] ?? null,
3779                'last_follow_up_comment' => $result['last_follow_up_comment'] ?? null,
3780                'quote_id' => $result['quote_id'] ?? null,
3781                'request_date' => date('Y-m-d'),
3782                'updated_by' => 'IA',
3783                'user_id' => $result['user_id'] ?? null,
3784                'commercial' => $result['commercial'] ?? null,
3785                'budget_status_id' => $result['budget_status_id'],
3786                'internal_quote_id' => $result['internal_quote_id'] ?? null,
3787            ];
3788
3789            // FIRE-1147: same Lambda duplicate-checker as create_quotation.
3790            // Async dispatch — response was already unused inline (3-5 s wasted).
3791            CheckQuotationDuplicate::dispatch($data)->onQueue('default');
3792        }
3793
3794        // FIRE-1145: was Cache::flush() — update_quotation affects list_quotations + commercial counters.
3795        ResultCache::forgetDomain(['quotations', 'users']);
3796
3797        return response([
3798            'message' => 'OK',
3799            'data' => $result,
3800            'for_approval' => $forApproval,
3801            'needsApprovalConfirmation' => $needsApprovalConfirmation,
3802        ]);
3803
3804        // } catch (\Exception $e) {
3805        //     return response(['message' => 'KO', 'error' => $e->getMessage()]);
3806        // }
3807
3808    }
3809
3810    /**
3811     * @return array{newData: mixed, oldData: mixed}[]
3812     */
3813    private function compareArrays($data, $quotations): array
3814    {
3815        $differences = [];
3816        $attributes = $quotations->getAttributes();
3817
3818        foreach ($data as $field => $valueData) {
3819            if (array_key_exists($field, $attributes)) {
3820                $valueQuotations = $quotations->$field;
3821
3822                $valueData = $this->convertValue($valueData);
3823                $valueQuotations = $this->convertValue($valueQuotations);
3824
3825                if ($valueData !== $valueQuotations) {
3826                    if ($this->isEmpty($valueData) && $this->isEmpty($valueQuotations)) {
3827                        continue;
3828                    }
3829
3830                    $differences[$field] = [
3831                        'newData' => $valueData,
3832                        'oldData' => $valueQuotations,
3833                    ];
3834                }
3835            }
3836        }
3837
3838        return $differences;
3839    }
3840
3841    private function isEmpty($value): bool
3842    {
3843        return is_null($value) || $value === '' || $value === 0 || $value === '0';
3844    }
3845
3846    private function convertValue($value)
3847    {
3848        if ($value === null) {
3849            return null;
3850        }
3851
3852        if (is_numeric($value)) {
3853            return (int) $value;
3854        }
3855
3856        if ($value === 'NULL' || $value === 'null') {
3857            return null;
3858        }
3859
3860        if (is_string($value)) {
3861            if (preg_match('/^(\d{4}-\d{2}-\d{2})( \d{2}:\d{2}:\d{2})?$/', $value, $matches)) {
3862                return $matches[1];
3863            }
3864        }
3865
3866        return $value;
3867    }
3868
3869    protected function callDeleteQuotation($id, $company_id, $userId, $user)
3870    {
3871        $request = new Request([
3872            'company_id' => $company_id,
3873            'user_id' => $userId,
3874            'updated_by' => $user,
3875            'ids' => [$id],
3876            'filterModel' => [],
3877            'sortModel' => [],
3878            'searchText' => '',
3879            'ids_not_in' => [],
3880        ]);
3881
3882        return $this->delete_quotation($request, true);
3883    }
3884
3885    public function get_quotation($id): ResponseFactory|HttpResponse
3886    {
3887
3888        try {
3889
3890            // Titan → Zeus bridge (read). A Madrid quote is answered by Zeus;
3891            // if Zeus is unreachable or refuses, Titan answers as today.
3892            $zeus = app(ZeusBridge::class);
3893            $forward = $zeus->getQuotation(request(), $id);
3894
3895            if ($zeus->shouldReturnZeusResponse($forward)) {
3896                return $forward->toTitanResponse();
3897            }
3898
3899            $id = addslashes((string) $id);
3900
3901            $query = "SELECT
3902                        a.id,
3903                        a.quote_id,
3904                        a.company_id,
3905                        b.name company_name,
3906                        a.client,
3907                        c.name client_type,
3908                        c.customer_type_id,
3909                        s.name segment,
3910                        s.segment_id,
3911                        a.request_date,
3912                        a.visit_date,
3913                        a.issue_date,
3914                        a.acceptance_date,
3915                        a.internal_quote_id,
3916                        DATE_FORMAT(a.request_date, '%d/%m/%Y') request_date_translate,
3917                        DATE_FORMAT(a.issue_date, '%d/%m/%Y') issue_date_translate,
3918                        DATE_FORMAT(a.acceptance_date, '%d/%m/%Y') acceptance_date_translate,
3919                        DATE_FORMAT(a.last_follow_up_date, '%d/%m/%Y') last_follow_up_date_translate,
3920                        a.phone_number,
3921                        a.email,
3922                        a.send_channel,
3923                        a.direccion_postal,
3924                        a.sent_date,
3925                        a.duration,
3926                        a.order_number,
3927                        d.name 'type',
3928                        d.budget_type_id,
3929                        e.name 'status',
3930                        e.budget_status_id,
3931                        f.name source,
3932                        f.source_id,
3933                        a.codigo_id,
3934                        a.amount,
3935                        g.name reason_for_not_following_up,
3936                        a.reason_for_not_following_up_id,
3937                        a.reason_for_rejection_id,
3938                        a.last_follow_up_date,
3939                        a.last_follow_up_comment,
3940                        CASE WHEN a.reason_for_rejection_id IS NULL THEN a.reason_for_rejection ELSE h.name END reason_for_rejection,
3941                        a.commercial,
3942                        a.created_by,
3943                        a.created_at,
3944                        a.updated_by,
3945                        a.updated_at,
3946                        a.for_approval,
3947                        a.approval_type,
3948                        a.box_work_g3w,
3949                        a.people_assigned_to_the_job,
3950                        a.duration_of_job_in_days,
3951                        a.estimated_cost_of_materials,
3952                        a.budget_margin_enabled,
3953                        a.labor_manual_override,
3954                        a.question_enabled,
3955                        a.cost_of_labor,
3956                        a.total_cost_of_job,
3957                        CASE WHEN a.budget_margin_enabled > 0 THEN a.invoice_margin ELSE NULL END invoice_margin,
3958                        CASE WHEN a.budget_margin_enabled > 0 THEN a.margin_for_the_company ELSE NULL END margin_for_the_company,
3959                        a.margin_on_invoice_per_day_per_worker,
3960                        a.revenue_per_date_per_worked,
3961                        a.commission_cost,
3962                        a.commission_pct,
3963                        a.gross_margin,
3964                        a.labor_percentage,
3965                        a.question_ids,
3966                        a.question_ids_no,
3967                        a.approved_at,
3968                        a.approved_by,
3969                        a.rejected_at,
3970                        a.rejected_by,
3971                        a.approved_at_v2,
3972                        a.approved_by_v2,
3973                        a.rejected_at_v2,
3974                        a.rejected_by_v2,
3975                        a.accepted_at,
3976                        a.accepted_by,
3977                        a.is_validated,
3978                        a.maintenance_potential,
3979                        a.coverage_contract_signed,
3980                        a.resource_id,
3981                        a.sync_import,
3982                        a.sync_import_edited,
3983                        a.user_create_by_g3w,
3984                        a.user_commercial_by_g3w,
3985                        a.g3w_warning,
3986                        a.g3w_warning_fields,
3987                        a.id_solicitud_duplicity,
3988                        a.x_status
3989                    FROM
3990                        tbl_quotations a
3991                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
3992                        LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
3993                        LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
3994                        LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
3995                        LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
3996                        LEFT JOIN tbl_sources f ON a.source_id = f.source_id
3997                        LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
3998                        LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
3999                        LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
4000                    WHERE a.id = {$id}";
4001
4002            $result = DB::select($query);
4003
4004            // FIRE-1145: was Cache::flush() — read-only path, zero benefit. Removed.
4005
4006            // Approval circuit v2 (SOP §4): attach the derived approval-circuit
4007            // state (borrador/listo/pendiente/aprobado/no_aprobado) and whether
4008            // the amount moved since the approver was notified, so the banner
4009            // and the approver pop-ups read one authoritative value. Additive —
4010            // existing consumers ignore the extra fields.
4011            if (! empty($result)) {
4012                $raw = TblQuotations::where('id', $id)->first();
4013                $result[0]->importe_avisado = $raw?->importe_avisado;
4014                $resolver = new ApprovalStateResolver;
4015                $result[0]->approval_state = $resolver->resolve($result[0]);
4016                $result[0]->amount_changed_since_notified = $resolver->amountChangedSinceNotified($result[0]);
4017
4018                // Approver pop-up context (SOP §9): what the logged-in user should
4019                // see when they open this budget from the approval email.
4020                // acting_type = the open slot they may act on (technical/financial/
4021                // null); is_approver = they belong to an approver group for this
4022                // company (so we can show "ya aprobado" / "ya no requiere" rather
4023                // than nothing); already_approved_by feeds "ya aprobado por X".
4024                $companyId = (int) ($raw?->company_id ?? 0);
4025                $userId = (int) $this->userId;
4026                $isApprover = DB::table('tbl_approvers')->where('company_id', $companyId)->where('user_id', $userId)->exists()
4027                    || DB::table('tbl_approvers_v2')->where('company_id', $companyId)->where('user_id', $userId)->exists();
4028                // Sequential (Operations → Finance): which stage the circuit is
4029                // waiting on right now, so a Finance approver who opens a dual
4030                // quote before Operations has acted sees "Pendiente de aprobación
4031                // de Operaciones" instead of a blank/actionless screen.
4032                $waitingOn = null;
4033                if ($raw && (int) $raw->for_approval === 3) {
4034                    if ($raw->approved_by === null && $raw->rejected_by === null) {
4035                        $waitingOn = 'technical';
4036                    } elseif ($raw->approved_by !== null && $raw->rejected_by === null
4037                        && $raw->approved_by_v2 === null && $raw->rejected_by_v2 === null) {
4038                        $waitingOn = 'financial';
4039                    }
4040                }
4041                $result[0]->approver_context = [
4042                    'is_approver' => $isApprover,
4043                    'acting_type' => $raw ? $this->approverActingType($raw) : null,
4044                    'already_approved_by' => $raw?->approved_by_v2 ?? $raw?->approved_by,
4045                    'waiting_on' => $waitingOn,
4046                ];
4047            }
4048
4049            return response(['message' => 'OK', 'data' => $result]);
4050
4051        } catch (\Exception $e) {
4052            report(AppException::fromException($e, 'GET_QUOTATION_EXCEPTION'));
4053
4054            return response(['message' => 'KO', 'error' => $e->getMessage()]);
4055        }
4056    }
4057
4058    public function get_quotation_log($id)
4059    {
4060        $log = TblQuotationsLog::where('quotation_id', $id)->get()->toArray();
4061
4062        // Every send (tbl_quotation_sends) joins the history as its own row, in
4063        // the same six columns the history table shows: channel in words as the
4064        // field, status at that moment as the old value, the amount then as the
4065        // new value. ids are prefixed so they never clash with log ids.
4066        $label = [
4067            QuotationSendRecorder::TITAN_EMAIL => 'Envío por email desde Titan',
4068            QuotationSendRecorder::TITAN_WHATSAPP => 'Envío por WhatsApp desde Titan',
4069            QuotationSendRecorder::G3W_STATUS => 'Envío (Enviado en Gestiona)',
4070            QuotationSendRecorder::COFRAI_STATUS => 'Envío (Enviado en Cofrai)',
4071            QuotationSendRecorder::MANUAL_STATUS => 'Envío (estado cambiado a Enviado)',
4072            QuotationSendRecorder::IMPORT => 'Envío (importado ya Enviado)',
4073            QuotationSendRecorder::ACCEPTANCE => 'Envío (aceptado sin envío previo)',
4074        ];
4075        foreach (TblQuotationSends::where('quotation_id', $id)->orderBy('sent_at')->get() as $s) {
4076            $log[] = [
4077                'id' => 'send-'.$s->id,
4078                'quotation_id' => (int) $id,
4079                'category' => 'Envio del presupuesto',
4080                'user' => $s->user,
4081                'field' => $label[$s->channel] ?? 'Envío',
4082                'old_value' => $s->status,
4083                'new_value' => $s->amount !== null ? number_format((float) $s->amount, 2, ',', '.').' €' : null,
4084                // Same serialisation as the log rows (ISO 8601 UTC), so the
4085                // history sorts and displays both kinds of row identically.
4086                'updated_at' => Carbon::parse($s->sent_at)->toJSON(),
4087                'created_at' => Carbon::parse($s->sent_at)->toJSON(),
4088            ];
4089        }
4090
4091        return $log;
4092    }
4093
4094    public function send_notification($toEmail = null, $userId = null, $quoteId = null, $id = null, $status = null, $sendUserId = null, $companyName = null, $action = null, $companyId = null, $g3wQuoteId = null): void
4095    {
4096
4097        $user = TblUsers::where('id', $userId)->first();
4098
4099        $imgpath = file_get_contents(public_path('fireservicetitan.png'));
4100
4101        $url = config('app.frontend_url')."orders/{$id}?company_id={$companyId}";
4102        $href = "<a href='{$url}'>{$quoteId}</a>";
4103
4104        $body = '';
4105        $subject = '';
4106
4107        if ($g3wQuoteId) {
4108            $quoteId = $quoteId." - G3W #{$g3wQuoteId}";
4109        }
4110
4111        if ($action == 1) {
4112            $body = __('language.email_notification.body_created');
4113            $body = str_replace('{{creator}}', $user->name, $body);
4114            $subject = str_replace('{{quote_id}}', $quoteId, __('language.email_notification.subject_created'));
4115        } else {
4116            $body = __('language.email_notification.body_assigned');
4117            $body = str_replace('{{assignee}}', $user->name, $body);
4118            $subject = str_replace('{{quote_id}}', $quoteId, __('language.email_notification.subject_assigned'));
4119        }
4120
4121        $body = str_replace('{{quote_id}}', $href, $body);
4122        $body = str_replace('{{company}}', $companyName, $body);
4123        $body = str_replace('{{status}}', $status, $body);
4124
4125        $content = $body;
4126
4127        $body .= '<p>Fire Service Titan</p>';
4128        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
4129
4130        $html = '<!DOCTYPE html>';
4131        $html .= '<html>';
4132        $html .= '<head>';
4133        $html .= '<meta charset="UTF-8">';
4134        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
4135        $html .= '</head>';
4136        $html .= '<body>';
4137        $html .= $body;
4138        $html .= '</body>';
4139        $html .= '</html>';
4140
4141        if ($toEmail != null) {
4142            $email = new Mail;
4143
4144            if (config('services.sendgrid.staging')) {
4145                $toEmail = $user->email;
4146            }
4147
4148            $email->setFrom('fire@fire.es', 'Fire Service Titan');
4149            $email->setSubject($subject);
4150            $email->addTo($toEmail);
4151            $email->addContent('text/html', $html);
4152
4153            $email->addAttachment(
4154                $imgpath,
4155                'image/png',
4156                'fireservicetitan.png',
4157                'inline',
4158                'fireservicetitan'
4159            );
4160
4161            // FIRE-1930: commercial kill switch. A gated send (null) skips
4162            // only the email — the in-app notification is still created.
4163            $response = SendgridDispatcher::send(
4164                $email,
4165                SendgridDispatcher::BUCKET_COMMERCIAL,
4166                (int) $companyId,
4167                'Quotations::send_notification',
4168            );
4169            $gated = $response === null;
4170
4171            if ($gated || $response->statusCode() == 202) {
4172                if (! $gated) {
4173                    Log::channel('email_log')->info('ID:'.$quoteId.' : '.$status.' : '.$toEmail.' - EMAIL NOTIFICATION SENT');
4174                    $this->addUpdateLog($id, $sendUserId, 'send_notification', null, null, 5);
4175                }
4176
4177                TblNotifications::create(
4178                    [
4179                        'user_id' => $sendUserId,
4180                        'content' => $content,
4181                        'is_open' => 1,
4182                        'created_by' => 'System',
4183                        'link' => $url,
4184                    ]
4185                );
4186            } else {
4187                $error = true;
4188                Log::channel('email_log')->error('ID:'.$quoteId.' : '.$status.' : '.$toEmail.' - '.$response->body());
4189            }
4190        }
4191
4192    }
4193
4194    public function delete_quotation(Request $request, $isFromDeleteCall = false): ResponseFactory|HttpResponse
4195    {
4196
4197        try {
4198
4199            $data = $request->all();
4200            $result = [];
4201
4202            if (count($data['ids']) > 1) {
4203                $u = TblUsers::where('id', $data['user_id'])->first();
4204
4205                if ($u->role_id != 1) {
4206                    return response(['message' => 'KO', 'error' => 'more_than_one']);
4207                }
4208            }
4209
4210            $r = new Request([
4211                'filterModel' => $data['filterModel'] ?? [],
4212                'sortModel' => $data['sortModel'] ?? [],
4213                'start' => 0,
4214                'end' => 999999999,
4215                'company_id' => $data['company_id'],
4216                'user_id' => $data['user_id'],
4217                'ids' => $data['ids'],
4218                'searchText' => $data['searchText'] ?? '',
4219                'ids_not_in' => $data['ids_not_in'],
4220            ]);
4221
4222            $d = [];
4223
4224            $result = $this->list_quotations($r);
4225            $result = $result->original['data'];
4226
4227            $outputArray = [];
4228
4229            foreach ($result as $item) {
4230                if (isset($item->id)) {
4231                    $outputArray[] = $item->id;
4232                }
4233            }
4234
4235            if ($outputArray) {
4236
4237                TblQuotations::whereIn('id', $outputArray)->update(
4238                    [
4239                        'updated_at' => date('Y-m-d H:i:s'),
4240                        'updated_by' => $data['updated_by'],
4241                        'for_add' => $isFromDeleteCall ? 2 : ($data['for_add'] ?? 0),
4242                        'reason_id' => ($data['reason_id'] ?? null),
4243                        'reason_for_deletion' => ($data['reason_for_deletion'] ?? null),
4244                    ]
4245                );
4246
4247                $this->archiveQuotations($outputArray);
4248
4249                TblQuotations::whereIn('id', $outputArray)->delete();
4250                TblFiles::whereIn('quotation_id', $outputArray)->delete();
4251            }
4252
4253            foreach ($outputArray as $id) {
4254                $this->addUpdateLog($id, $data['user_id'], 'delete', null, null, 6);
4255            }
4256
4257            // FIRE-1145: was Cache::flush() — delete_quotation affects list_quotations + commercial counters.
4258            ResultCache::forgetDomain(['quotations', 'users']);
4259
4260            return response(['message' => 'OK', 'data' => $result]);
4261
4262        } catch (\Exception $e) {
4263            report(AppException::fromException($e, 'DELETE_QUOTATION_EXCEPTION'));
4264
4265            return response(['message' => 'KO', 'error' => $e->getMessage()]);
4266        }
4267
4268    }
4269
4270    /**
4271     * Copy quotations into tbl_quotations_deleted, matching columns BY NAME.
4272     *
4273     * PHP-LARAVEL-7. This was `INSERT INTO tbl_quotations_deleted SELECT *
4274     * FROM tbl_quotations WHERE id IN (...)`, which maps columns by ORDINAL
4275     * POSITION. That depends on the two tables having identical column counts
4276     * AND identical ordering — neither is enforced anywhere, and both drifted:
4277     *
4278     *   - `client_id` sits at position 2 in tbl_quotations (added 2026-03-26)
4279     *     but position 95 in the archive, so every value from position 2
4280     *     onward landed one column to the left.
4281     *   - `follow_up_commercial` exists only on tbl_quotations, making the
4282     *     counts 100 vs 99 and turning that silent misalignment into the loud
4283     *     SQLSTATE[21S01] this ticket reports.
4284     *
4285     * The loud error is the lucky outcome: it aborts before the hard delete in
4286     * the caller, so the quotation survives. While the counts happened to
4287     * match, this wrote scrambled rows and then deleted the originals — 1,735
4288     * archived rows carry the shift, identifiable by a NULL `quote_id`, which
4289     * never occurs in tbl_quotations.
4290     *
4291     * Matching by name removes the dependency on both count and order, so no
4292     * future column added to either table can reintroduce it.
4293     */
4294    private function archiveQuotations(array $ids): void
4295    {
4296        if ($ids === []) {
4297            return;
4298        }
4299
4300        $live = Schema::getColumnListing('tbl_quotations');
4301        $archive = Schema::getColumnListing('tbl_quotations_deleted');
4302
4303        // Intersect in the archive's own order. The SELECT list is emitted in
4304        // the same order as the INSERT list, so alignment holds however either
4305        // table happens to be physically laid out.
4306        $columns = array_values(array_intersect($archive, $live));
4307
4308        if ($columns === []) {
4309            throw new \RuntimeException('tbl_quotations_deleted shares no columns with tbl_quotations.');
4310        }
4311
4312        // A name-based copy silently drops anything the archive can't hold.
4313        // Say so, or the next drift is invisible until someone needs a field
4314        // that was never archived.
4315        $unarchivable = array_values(array_diff($live, $archive));
4316        if ($unarchivable !== []) {
4317            // Logging must never abort the delete: on 2026-10-08 the day's log
4318            // file was not writable, this warning threw, and Carlos Alonso could
4319            // not delete quote 49375.
4320            try {
4321                Log::warning('tbl_quotations_deleted is missing columns present on tbl_quotations; they will not be archived.', [
4322                    'columns' => $unarchivable,
4323                ]);
4324            } catch (\Throwable) {
4325                // The archive copy below still runs.
4326            }
4327        }
4328
4329        $list = implode(', ', array_map(fn ($c) => "`{$c}`", $columns));
4330        $placeholders = implode(',', array_fill(0, count($ids), '?'));
4331
4332        DB::insert(
4333            "INSERT INTO `tbl_quotations_deleted` ({$list})
4334             SELECT {$list} FROM `tbl_quotations` WHERE `id` IN ({$placeholders})",
4335            array_values($ids)
4336        );
4337    }
4338
4339    /** Placeholder email patterns (regex fragments, also used in SQL REGEXP). */
4340    private const BLACKLIST_EMAIL_PATTERNS = [
4341        "no\.no",
4342        "tiene\.email",
4343        "test\.com",
4344        "no\.tiene",
4345        "prueba\.com",
4346        "nomail@nomail\.com",
4347        "notiene@notiene\.notiene",
4348    ];
4349
4350    public function getBlacklistEmails(): array
4351    {
4352        return self::BLACKLIST_EMAIL_PATTERNS;
4353    }
4354
4355    /**
4356     * The one rule for "Pendientes de seguimiento" (a budget that needs a
4357     * follow-up reminder): status Enviado (2), an overdue last_follow_up_date,
4358     * no "reason for not following up", under the company's reminder limit,
4359     * a present + valid + non-placeholder email whose domains are not blocked
4360     * for the company, and not awaiting an approval decision.
4361     *
4362     * Used by the Orders filter, its bulk-button count, the dashboard tile and
4363     * the "Enviar recordatorios" pop-up (OngoingJobs::get_total_jobs_in_red).
4364     * They used to carry their own copies and drifted apart: the pop-up waited
4365     * 2 extra days and counted invalid, placeholder and pending-approval rows,
4366     * so its number never matched the list it sent the salesperson to.
4367     *
4368     * Append to a query over `tbl_quotations a` joined to `tbl_companies b`.
4369     */
4370    public static function pendingFollowUpSql(): string
4371    {
4372        $emailRegex = '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$';
4373        $blacklist = implode('|', self::BLACKLIST_EMAIL_PATTERNS);
4374
4375        $sql = " AND a.budget_status_id IN (2)
4376            AND a.for_add = 0
4377            AND a.last_follow_up_date IS NOT NULL
4378            AND a.last_follow_up_date > 0
4379            AND a.last_follow_up_date < NOW()
4380            AND a.reason_for_not_following_up_id IS NULL
4381            AND a.total_sent < b.limit_reminder_emails
4382            AND a.email IS NOT NULL
4383            AND TRIM(a.email) <> ''
4384            AND a.email REGEXP '{$emailRegex}'
4385            AND NOT EXISTS (
4386                SELECT 1 FROM tbl_blocked_domains bd
4387                WHERE a.email LIKE CONCAT('%', bd.domain, '%')
4388                AND bd.company_id = a.company_id
4389            ) ";
4390        if ($blacklist !== '') {
4391            $sql .= " AND a.email NOT REGEXP '({$blacklist})' ";
4392        }
4393
4394        return $sql.' AND '.self::NOT_PENDING_APPROVAL_SQL.' ';
4395    }
4396
4397    public function validate_email(Request $request)
4398    {
4399        $email = $request->input('email');
4400
4401        if (! $email || trim($email) === '') {
4402            return response()->json([
4403                'valid' => false,
4404                'reason' => 'El email está vacío',
4405            ]);
4406        }
4407
4408        $emailPattern = '/^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/';
4409        $emails = explode(',', $email);
4410
4411        foreach ($emails as $e) {
4412            $trimmed = trim($e);
4413
4414            if (! preg_match($emailPattern, $trimmed)) {
4415                return response()->json([
4416                    'valid' => false,
4417                    'reason' => "El email '{$trimmed}' tiene un formato incorrecto",
4418                ]);
4419            }
4420
4421            if ($this->isBlacklistedEmail($trimmed)) {
4422                return response()->json([
4423                    'valid' => false,
4424                    'reason' => "El email '{$trimmed}' está en la lista de direcciones no válidas",
4425                ]);
4426            }
4427        }
4428
4429        return response()->json([
4430            'valid' => true,
4431            'reason' => null,
4432        ]);
4433    }
4434
4435    private function isBlacklistedEmail(?string $email): bool
4436    {
4437        if (! $email || trim($email) === '') {
4438            return true;
4439        }
4440
4441        // FIRE-864 (2026-04-30): use `getBlacklistEmails()` as the single
4442        // source of truth. Pre-fix this method had its own hardcoded
4443        // pattern that was inconsistent with the array — missing `no\.no`
4444        // and `no\.tiene`, and `^no@` was over-anchored (missed
4445        // `xxx@no.no`). The `Emails con error` badge filter and the
4446        // backfill migration both already consume `getBlacklistEmails()`,
4447        // so aligning here closes the gap that left rows in `Listo para
4448        // enviar` after Berta's reclassification expected to catch them.
4449        $pattern = '/'.implode('|', $this->getBlacklistEmails()).'/i';
4450
4451        $emails = explode(',', $email);
4452        foreach ($emails as $e) {
4453            if (preg_match($pattern, trim($e))) {
4454                return true;
4455            }
4456        }
4457
4458        return false;
4459    }
4460
4461    /**
4462     * FIRE-864 (2026-04-30): a row's email is "invalid" when it's empty,
4463     * malformed (failing the standard email regex), OR matches the
4464     * blacklist. The runtime classifier in `update_quotation` was only
4465     * checking `isBlacklistedEmail()`, so malformed emails like
4466     * "ricardo@" or "no email" never got reclassified to budget_status 22
4467     * and stayed in `Listo para enviar` indefinitely.
4468     *
4469     * The `invalid_email=1` filter in `list_quotations` (line 2974) and
4470     * the SQL backfill migration both use the same three-pronged check;
4471     * this mirrors that for in-process classification.
4472     */
4473    private function isInvalidEmail(?string $email): bool
4474    {
4475        if (! $email || trim($email) === '') {
4476            return true;
4477        }
4478
4479        $emailPattern = '/^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/';
4480        foreach (explode(',', $email) as $e) {
4481            $trimmed = trim($e);
4482            if ($trimmed === '') {
4483                return true;
4484            }
4485            if (! preg_match($emailPattern, $trimmed)) {
4486                return true;
4487            }
4488        }
4489
4490        return $this->isBlacklistedEmail($email);
4491    }
4492
4493    /**
4494     * FIRE-1377: multichannel budget sending. Resolves the send channel a
4495     * budget should use, applying the two product rules:
4496     *  - only 'email', 'correo' (ordinary mail) and 'whatsapp' are valid;
4497     *    anything else (including null/empty) falls back to 'email'.
4498     *  - budgets of €5,000 or more must go by email, so correo/whatsapp are
4499     *    forced back to email above the threshold (better visibility of what
4500     *    is sent). The amount is taken from the budget's Importe (€) field.
4501     */
4502    private function normalizeSendChannel(?string $channel, mixed $amount): string
4503    {
4504        $channel = in_array($channel, ['email', 'correo', 'whatsapp'], true) ? $channel : 'email';
4505
4506        $numericAmount = is_numeric($amount) ? (float) $amount : (float) str_replace(',', '.', (string) $amount);
4507        if ($numericAmount >= 5000) {
4508            return 'email';
4509        }
4510
4511        return $channel;
4512    }
4513
4514    public function list_quotations(Request $request)
4515    {
4516
4517        // try {
4518
4519        $data = $request->all();
4520        $companyId = addslashes((string) $data['company_id']);
4521        $userId = addslashes((string) $data['user_id']);
4522        $filter = $data['filterModel'];
4523        $sort = $data['sortModel'];
4524        $result = [];
4525        $subquery = '';
4526        $where = '';
4527        $having = '';
4528        $orderBy = '';
4529
4530        // FIRE-1174: gate the 10-min query cache to avoid per-keystroke churn.
4531        // Cache keys embed the literal $searchText so every short prefix the
4532        // user types (s → so → sol → soli …) is a distinct miss + write.
4533        // Caching is useful for the "page loaded, no filter yet" cold path
4534        // and for stable searches (≥ 3 chars); skip everything in between.
4535        $cacheSearch = trim((string) ($data['searchText'] ?? ''));
4536        $shouldCacheList = $cacheSearch === '' || strlen($cacheSearch) >= 3;
4537        $start = addslashes((string) $data['start']);
4538        $end = addslashes((string) $data['end']);
4539        $totalRowCount = 0;
4540        $withFilters = '';
4541        $logFilter = @$data['log_filter'];
4542        $isInvalidEmail = (isset($data['invalid_email']) && $data['invalid_email'] == 1);
4543        $isFollowUp = (isset($data['is_follow_up']) && $data['is_follow_up'] == 1);
4544        $isNoEmailFollowUp = (isset($data['is_no_email_follow_up']) && $data['is_no_email_follow_up'] == 1);
4545
4546        $filterType = [
4547            'contains' => "LIKE '%[value]%'",
4548            'notContains' => "NOT LIKE '%[value]%'",
4549            'equals' => "= '[value]'",
4550            'notEqual' => "<> '[value]'",
4551            'startsWith' => "LIKE '[value]%'",
4552            'endsWith' => "LIKE '%[value]'",
4553            'blank' => 'IS NULL',
4554            'notBlank' => 'IS NOT NULL',
4555            'lessThan' => '< [value]',
4556            'lessThanOrEqual' => '<= [value]',
4557            'greaterThan' => '> [value]',
4558            'greaterThanOrEqual' => '>= [value]',
4559            'inRange' => 'BETWEEN [value1] AND [value2]',
4560            'in' => 'IN ([value])',
4561        ];
4562
4563        /*if(isset($data['internal_quote_id']) && count($data['internal_quote_id']) > 0){
4564            $internalIds = implode(",", $data['internal_quote_id']);
4565            $where = " AND a.internal_quote_id IN ({$internalIds}) ";
4566        }*/
4567
4568        // Filter to positive integers before emitting IN clauses. Frontend
4569        // can send [null] (from [NaN]) when localStorage holds a non-numeric
4570        // string, and implode(',', [null]) produces "" — that ships
4571        // `a.id IN ()` and crashes MySQL with 1064.
4572        if (isset($data['ids']) && is_array($data['ids'])) {
4573            $numericIds = array_values(array_filter(
4574                array_map('intval', $data['ids']),
4575                fn ($n) => $n > 0
4576            ));
4577            if (count($numericIds) > 0) {
4578                $where .= ' AND a.id IN ('.implode(',', $numericIds).') ';
4579            }
4580        }
4581
4582        if (isset($data['ids_not_in']) && is_array($data['ids_not_in'])) {
4583            $numericIdsNotIn = array_values(array_filter(
4584                array_map('intval', $data['ids_not_in']),
4585                fn ($n) => $n > 0
4586            ));
4587            if (count($numericIdsNotIn) > 0) {
4588                $where .= ' AND a.id NOT IN ('.implode(',', $numericIdsNotIn).') ';
4589            }
4590        }
4591
4592        $lasLeftJoin = '';
4593        $whereBlocked = '';
4594
4595        if (isset($data['last_follow_up_date']) && ! empty($data['last_follow_up_date'])) {
4596            if ($data['last_follow_up_date'] == 1) {
4597
4598                $lasLeftJoin = " LEFT JOIN (
4599                        SELECT
4600                          a.id,
4601                          SUBSTRING_INDEX(
4602                            SUBSTRING_INDEX(a.email, ',', n.digit + 1),
4603                            ',',
4604                            -1
4605                          ) AS email_domain
4606                        FROM
4607                          tbl_quotations a
4608                          INNER JOIN (
4609                            SELECT
4610                              0 AS digit
4611                            UNION ALL
4612                            SELECT
4613                              1
4614                            UNION ALL
4615                            SELECT
4616                              2
4617                            UNION ALL
4618                            SELECT
4619                              3
4620                            UNION ALL
4621                            SELECT
4622                              4
4623                            UNION ALL
4624                            SELECT
4625                              5
4626                            UNION ALL
4627                            SELECT
4628                              6
4629                            UNION ALL
4630                            SELECT
4631                              7
4632                            UNION ALL
4633                            SELECT
4634                              8
4635                            UNION ALL
4636                            SELECT
4637                              9
4638                          ) n ON LENGTH(
4639                            REPLACE(a.email, ',', '')
4640                          ) <= LENGTH(a.email)- n.digit
4641                          GROUP BY a.id
4642                      ) temp ON a.id = temp.id ";
4643
4644                $whereBlocked = " AND a.last_follow_up_date < NOW()
4645                            AND a.budget_status_id IN (2)
4646                            AND a.email IS NOT NULL
4647                            AND a.email <> ''
4648                            AND NOT EXISTS (
4649                                SELECT
4650                                1
4651                                FROM
4652                                tbl_blocked_domains bd
4653                                WHERE
4654                                temp.email_domain LIKE CONCAT('%', bd.domain, '%')
4655                                AND bd.company_id = a.company_id
4656                            )
4657                            AND a.last_follow_up_date IS NOT NULL
4658                            AND a.reason_for_not_following_up_id IS NULL
4659                            AND a.last_follow_up_date > 0
4660                            AND a.total_sent < b.limit_reminder_emails
4661                            AND a.for_add = 0 ";
4662            }
4663        }
4664
4665        if (isset($data['visit_date']) && ! empty($data['visit_date'])) {
4666            if ($data['visit_date'] == 1) {
4667                $where = " AND DATE_FORMAT(a.visit_date, '%Y-%m-%d') <= DATE_FORMAT(NOW(), '%Y-%m-%d') ";
4668            }
4669        }
4670
4671        if ($companyId != 0) {
4672            $where .= " AND a.company_id = {$companyId} ";
4673        } elseif ($this->companyId) {
4674            $where .= " AND a.company_id IN ({$this->companyId}) ";
4675        }
4676
4677        $matchScoreCol = '';
4678        $matchScoreOrderBy = '';
4679
4680        if (isset($data['searchText']) && $data['searchText'] != null) {
4681
4682            $availableParameters = [
4683                'a.quote_id',
4684                'a.internal_quote_id',
4685                'a.box_work_g3w',
4686                's.name',
4687                'b.name',
4688                'a.client',
4689                'c.name',
4690                'a.phone_number',
4691                'a.email',
4692                'a.order_number',
4693                'a.request_date',
4694                'a.issue_date',
4695                'a.acceptance_date',
4696                'a.created_at',
4697                'a.updated_at',
4698                'a.rejected_at',
4699                'a.accepted_at',
4700                'd.name',
4701                'e.name',
4702                'f.name',
4703                'a.amount',
4704                'g.name',
4705                'a.last_follow_up_comment',
4706                'a.x_status',
4707                'h.name',
4708                'a.commercial',
4709                'a.user_commercial_by_g3w',
4710                'a.user_create_by_g3w',
4711                'a.created_by',
4712                'a.updated_by',
4713                'a.approved_by',
4714                'a.rejected_by',
4715                'a.accepted_by',
4716                'a.sync_import',
4717                'a.sync_import_edited',
4718                'a.g3w_warning',
4719            ];
4720
4721            $searchText = addslashes((string) $data['searchText']);
4722            $searchTextArray = explode(' ', $searchText);
4723
4724            $searchArray = [];
4725            $splitSearchArray = [];
4726            $matchScoreArray = [];
4727            $sc = 1;
4728            foreach ($availableParameters as $field) {
4729                if ($field == 'a.client' || $field == 'a.amount' || $field == 'a.created_at') {
4730                    $sc = 3;
4731                } elseif ($field == 'a.acceptance_date') {
4732                    $sc = 2;
4733                } else {
4734                    $sc = 1;
4735                }
4736
4737                $l = "{$field} LIKE '%{$searchText}%'";
4738                if ($field == 'a.last_follow_up_comment') {
4739                    $l = "{$field} = '{$searchText}'";
4740                } else {
4741
4742                    $d = "IFNULL((LENGTH(LOWER({$field})) - LENGTH(REPLACE(LOWER({$field}), LOWER('{$searchText}'), ''))) / LENGTH(LOWER('{$searchText}')), 0) * {$sc}";
4743
4744                    if (count($searchTextArray) > 1) {
4745                        foreach ($searchTextArray as $word) {
4746                            if (! is_numeric($word)) {
4747                                $d .= " + IFNULL((LENGTH(LOWER({$field})) - LENGTH(REPLACE(LOWER({$field}), LOWER('{$word}'), ''))) / LENGTH(LOWER('{$word}')), 0) * {$sc}";
4748                            }
4749                        }
4750                    }
4751
4752                    array_push($matchScoreArray, $d);
4753                }
4754
4755                if (is_numeric($searchText)) {
4756                    array_push($searchArray, "({$l} OR {$field} = CAST('{$searchText}' AS UNSIGNED))");
4757                } else {
4758                    array_push($searchArray, "({$l} OR DATE_FORMAT({$field}, '%d/%m/%Y') = DATE_FORMAT(STR_TO_DATE('{$searchText}', '%d/%m/%Y'), '%d/%m/%Y'))");
4759                }
4760
4761                if (count($searchTextArray) > 1) {
4762                    foreach ($searchTextArray as $word) {
4763
4764                        $l = "{$field} LIKE '%{$word}%'";
4765                        if ($field == 'a.last_follow_up_comment') {
4766                            $l = "{$field} = '{$word}'";
4767                        }
4768
4769                        if (is_numeric($word)) {
4770                            array_push($splitSearchArray, "{$l} OR {$field} = CAST('{$word}' AS UNSIGNED)");
4771                        } else {
4772                            array_push($splitSearchArray, "{$l} OR DATE_FORMAT({$field}, '%d/%m/%Y') = DATE_FORMAT(STR_TO_DATE('{$word}', '%d/%m/%Y'), '%d/%m/%Y')");
4773                        }
4774                    }
4775                }
4776
4777                $sc = 1;
4778            }
4779
4780            if (count($splitSearchArray) > 0) {
4781                $splitSearchArray = implode(' OR ', $splitSearchArray);
4782                $splitSearchArray = " OR ({$splitSearchArray}) ";
4783            } else {
4784                $splitSearchArray = '';
4785            }
4786
4787            $searchArray = implode(' OR ', $searchArray);
4788            $matchScoreArray = implode(',', $matchScoreArray);
4789            $matchScoreCol = ", GREATEST({$matchScoreArray}) match_score";
4790            $matchScoreOrderBy = 'match_score DESC,';
4791            $where .= " AND ({$searchArray} {$splitSearchArray})";
4792        }
4793
4794        if (count($sort) > 0) {
4795            $field = $sort[0]['colId'];
4796            $sortBy = $sort[0]['sort'];
4797
4798            if (strpos($field, 'translate') !== false) {
4799                $field = str_replace('_translate', '', $field);
4800            } else {
4801                if ($field == 'client_type') {
4802                    $field = 'c.name';
4803                } elseif ($field == 'segment') {
4804                    $field = 's.name';
4805                } elseif ($field == 'type') {
4806                    $field = 'd.name';
4807                } elseif ($field == 'status') {
4808                    $field = 'e.name';
4809                } elseif ($field == 'source') {
4810                    $field = 'g.name';
4811                } elseif ($field == 'codigo') {
4812                    $field = 'co.name';
4813                } elseif ($field == 'reason_for_not_following_up') {
4814                    $field = 'g.name';
4815                } elseif ($field == 'reason_for_rejection') {
4816                    $field = 'h.name';
4817                } elseif ($field == 'amount') {
4818                    $field = 'CAST(a.amount AS DOUBLE)';
4819                } elseif ($field == 'duration') {
4820                    $field = 'CAST(a.duration AS DOUBLE)';
4821                } elseif ($field == 'quote_id' || $field == 'internal_quote_id') {
4822                    $field = "CAST(a.{$field} AS DOUBLE)";
4823                } elseif ($field == 'company_name') {
4824                    $field = 'b.name';
4825                }
4826
4827            }
4828
4829            if ($matchScoreOrderBy) {
4830                $matchScoreOrderBy = ', match_score DESC';
4831            }
4832
4833            $orderBy = " ORDER BY {$field} {$sortBy} {$matchScoreOrderBy}";
4834        } else {
4835            $orderBy = " ORDER BY {$matchScoreOrderBy} a.id DESC";
4836        }
4837
4838        foreach ($filter as $key => $data) {
4839            if (strpos($key, 'translate') !== false) {
4840
4841                $field = str_replace('_translate', '', $key);
4842                if ($field == 'created_at') {
4843                    $field = 'a.created_at';
4844                } elseif ($field == 'last_follow_up_date') {
4845                    $field = 'a.last_follow_up_date';
4846                } elseif ($field == 'issue_date') {
4847                    $field = 'a.issue_date';
4848                } elseif ($field == 'request_date') {
4849                    $field = 'a.request_date';
4850                } elseif ($field == 'acceptance_date') {
4851                    $field = 'a.acceptance_date';
4852                } elseif ($field == 'internal_quote_id') {
4853                    $field = 'a.internal_quote_id';
4854                }
4855
4856                $whereDates = '';
4857                $z = 0;
4858
4859                if (isset($data['filters']) && ! empty($data['filters'])) {
4860                    $yearsMonths = [];
4861                    $yearsWeeks = [];
4862                    $yearsMW = [];
4863                    foreach ($data['filters'] as $yearKey => $yearData) {
4864
4865                        if ($yearData['isChecked']) {
4866
4867                            if ($yearData['isCheckedAllMonths'] && $yearData['isCheckedAllWeeks']) {
4868                                if ($z > 0) {
4869                                    $whereDates .= " OR YEAR($field) = {$yearKey} ";
4870                                } else {
4871                                    $whereDates .= " YEAR($field) = {$yearKey} ";
4872                                }
4873                            } else {
4874
4875                                if ($yearData['isCheckedAllWeeks']) {
4876                                    for ($i = 0; $i < count($yearData['weeks']); $i++) {
4877                                        if ($yearData['weeks'][$i]['isChecked']) {
4878                                            array_push($yearsMW, " YEARWEEK({$field}, 1) = '{$yearKey}{$yearData['weeks'][$i]['value']}' ");
4879                                        }
4880                                    }
4881                                }
4882
4883                                if ($yearData['isCheckedAllMonths']) {
4884                                    for ($i = 0; $i < count($yearData['months']); $i++) {
4885                                        if ($yearData['months'][$i]['isChecked']) {
4886                                            array_push($yearsMW, " DATE_FORMAT({$field}, '%Y%m') = '{$yearKey}{$yearData['months'][$i]['value']}' ");
4887                                        }
4888                                    }
4889                                }
4890
4891                                if (! $yearsMW) {
4892                                    if (! $yearData['isCheckedAllMonths']) {
4893                                        if ($z > 0) {
4894                                            $whereDates .= " OR YEAR($field) = {$yearKey} ";
4895                                        } else {
4896                                            $whereDates .= " YEAR($field) = {$yearKey} ";
4897                                        }
4898                                    }
4899                                }
4900                            }
4901
4902                            $z++;
4903                        }
4904
4905                    }
4906
4907                    if ($yearsMW) {
4908                        $whereDates .= implode(' OR ', $yearsMW);
4909                    }
4910                }
4911
4912                $whereDataUptoToday = '';
4913                if (isset($data['isDataUptoToday'])) {
4914                    if ($data['isDataUptoToday']) {
4915                        $whereDates = '';
4916                        $whereDataUptoToday .= " AND {$field} < NOW() AND {$field} > 0 ";
4917                    }
4918                }
4919
4920                $whereBlanks = '';
4921                if (isset($data['isBlanks'])) {
4922                    if ($data['isBlanks']) {
4923                        $conj = 'OR';
4924                        if ($whereDates == '') {
4925                            $conj = '';
4926                        }
4927                        $whereBlanks .= " {$conj} {$field} IS NULL ";
4928                    } else {
4929                        $conj = 'AND';
4930                        if ($whereDates == '') {
4931                            $conj = '';
4932                        }
4933                        $whereBlanks .= " {$conj} {$field} IS NOT NULL ";
4934                    }
4935                }
4936
4937                $where .= " AND ({$whereDates} {$whereBlanks} {$whereDataUptoToday}) ";
4938            } else {
4939                if ($data['filterType'] == 'number') {
4940                    if (array_key_exists('operator', $data)) {
4941                        if ($data['condition1']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
4942                            $data['condition1']['filter'] = addslashes($data['condition1']['filter']);
4943                            $data['condition2']['filter'] = addslashes($data['condition2']['filter']);
4944
4945                            if ($data['condition1']['type'] == 'inRange') {
4946                                $data['condition1']['filterTo'] = addslashes($data['condition1']['filterTo']);
4947                                $inRange = str_replace('[value1]', $data['condition1']['filter'], $filterType['inRange']);
4948                                $val1 = str_replace('[value2]', $data['condition1']['filterTo'], $inRange);
4949                            } else {
4950                                $val1 = str_replace('[value]', $data['condition1']['filter'], $filterType[$data['condition1']['type']]);
4951                            }
4952
4953                            if ($data['condition2']['type'] == 'inRange') {
4954                                $data['condition2']['filterTo'] = addslashes($data['condition2']['filterTo']);
4955                                $inRange = str_replace('[value1]', $data['condition2']['filter'], $filterType['inRange']);
4956                                $val2 = str_replace('[value2]', $data['condition2']['filterTo'], $inRange);
4957                            } else {
4958                                $val2 = str_replace('[value]', $data['condition2']['filter'], $filterType[$data['condition2']['type']]);
4959                            }
4960
4961                        } else {
4962                            $val1 = $filterType[$data['condition1']['type']];
4963                            $val2 = $filterType[$data['condition2']['type']];
4964                        }
4965
4966                        $where .= " AND a.{$key} {$val1} {$data['operator']} a.{$key} {$val2} ";
4967                    } else {
4968                        if ($data['type'] != 'blank' && $data['type'] != 'notBlank') {
4969                            $data['filter'] = addslashes($data['filter']);
4970
4971                            if ($data['type'] == 'inRange') {
4972                                $data['filterTo'] = addslashes($data['filterTo']);
4973                                $inRange = str_replace('[value1]', $data['filter'], $filterType['inRange']);
4974                                $val = str_replace('[value2]', $data['filterTo'], $inRange);
4975                            } else {
4976                                $val = str_replace('[value]', $data['filter'], $filterType[$data['type']]);
4977                            }
4978                        } else {
4979                            $val = $filterType[$data['type']];
4980                        }
4981
4982                        $where .= " AND a.{$key} {$val} ";
4983                    }
4984                }
4985
4986                if ($data['filterType'] == 'text') {
4987                    if ($key == 'id') {
4988                        continue;
4989                    }
4990
4991                    if (array_key_exists('operator', $data)) {
4992                        $val1 = '';
4993                        $val2 = '';
4994                        if ($data['condition1']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
4995                            $data['condition1']['filter'] = addslashes($data['condition1']['filter']);
4996                            $val1 = str_replace('[value]', $data['condition1']['filter'], $filterType[$data['condition1']['type']]);
4997                        }
4998
4999                        if ($data['condition2']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
5000                            $data['condition2']['filter'] = addslashes($data['condition2']['filter']);
5001                            $val2 = str_replace('[value]', $data['condition2']['filter'], $filterType[$data['condition2']['type']]);
5002                        }
5003
5004                        $where .= " AND {$key} {$val1} {$data['operator']} {$key} {$val2} ";
5005                    } else {
5006
5007                        $type = $data['type'];
5008                        $filter = $data['filter'];
5009
5010                        if (($type === 'in' || $type === 'contains') && strpos($filter, ',') !== false) {
5011                            $values = explode(',', $filter);
5012                            $escaped = array_map('addslashes', $values);
5013                            $val = "IN ('".implode("','", $escaped)."')";
5014                        } elseif ($type !== 'blank' && $type !== 'notBlank') {
5015                            $data['filter'] = addslashes($data['filter']);
5016                            $val = str_replace('[value]', $data['filter'], $filterType[$type]);
5017                        } else {
5018                            $val = $filterType[$type];
5019                        }
5020
5021                        $where .= " AND {$key} {$val} ";
5022
5023                    }
5024                }
5025
5026                if ($data['filterType'] == 'set') {
5027                    $statusName = $key;
5028
5029                    if ($key == 'client_type') {
5030                        $statusName = 'c.name';
5031                    } elseif ($key == 'segment') {
5032                        $statusName = 's.name';
5033                    } elseif ($key == 'type') {
5034                        $statusName = 'd.name';
5035                    } elseif ($key == 'status') {
5036                        $statusName = 'e.name';
5037                    } elseif ($key == 'source') {
5038                        $statusName = 'f.name';
5039                    } elseif ($key == 'codigo') {
5040                        $statusName = 'co.name';
5041                    } elseif ($key == 'reason_for_not_following_up') {
5042                        $statusName = 'g.name';
5043                    } elseif ($key == 'reason_for_rejection') {
5044                        $statusName = 'h.name';
5045                    } elseif ($key == 'created_by') {
5046                        $statusName = 'a.created_by';
5047                    } elseif ($key == 'has_attachment') {
5048                        $statusName = 'a.has_attachment';
5049                        if ($data['values']) {
5050                            foreach ($data['values'] as $k => $v) {
5051                                if ($v == 'No') {
5052                                    $data['values'][$k] = 0;
5053                                } else {
5054                                    $data['values'][$k] = 1;
5055                                }
5056                            }
5057                        }
5058                    } elseif ($key == 'for_approval') {
5059                        $statusName = 'a.for_approval';
5060                        if ($data['values']) {
5061                            // FIRE-1092: a "Sí" selection must surface BOTH
5062                            // single-level (`for_approval = 1`) and
5063                            // dual-level (`for_approval = 3`) pending rows.
5064                            // Pre-fix it mapped to `1` only, hiding every
5065                            // dual-level pending approval from the filter.
5066                            // Expand the single value into both ids so the
5067                            // downstream IN(...) clause matches both.
5068                            $expanded = [];
5069                            foreach ($data['values'] as $v) {
5070                                if ($v == 'No') {
5071                                    $expanded[] = 0;
5072                                } else {
5073                                    $expanded[] = 1;
5074                                    $expanded[] = 3;
5075                                }
5076                            }
5077                            $data['values'] = array_values(array_unique($expanded));
5078                        }
5079                    } elseif ($key == 'sync_import') {
5080                        // FIRE-1159 follow-up #2: the "Origen" filter must
5081                        // mirror the frontend `originLabel()` rule, which is
5082                        // user_create_by_g3w-first: 'flu' -> FluencyLabs,
5083                        // 'dig' -> Diggening, regardless of sync_import; only
5084                        // when neither alias matches do we use sync_import = 1
5085                        // to mean G3W and otherwise Manual.
5086                        // Earlier iterations of this fix gated FluencyLabs /
5087                        // Diggening on `sync_import = 1`, which dropped rows
5088                        // like order 158956 (sync_import = 0, user_create_by_g3w
5089                        // = 'flu' — Titan row later matched to its G3W twin via
5090                        // internal_quote_id) out of the FluencyLabs filter
5091                        // even though it is unambiguously a FluencyLabs origin.
5092                        if (! empty($data['values'])) {
5093                            $parts = [];
5094                            foreach ($data['values'] as $v) {
5095                                if ($v === 'FluencyLabs') {
5096                                    $parts[] = "(LOWER(TRIM(a.user_create_by_g3w)) = 'flu')";
5097                                } elseif ($v === 'Diggening' || $v === 'WhatsApp AI Quotes') {
5098                                    // The label was renamed 'Diggening' -> 'WhatsApp AI Quotes'
5099                                    // on the frontend (originLabel() / synImportValues) without
5100                                    // updating this branch, so selecting it fell through to the
5101                                    // Manual `else` below and quietly returned Manual rows
5102                                    // instead. Both names are accepted so old saved filter
5103                                    // models and bookmarked links keep working.
5104                                    $parts[] = "(LOWER(TRIM(a.user_create_by_g3w)) = 'dig')";
5105                                } elseif ($v === 'G3W') {
5106                                    $parts[] = "(a.sync_import = 1 AND (a.user_create_by_g3w IS NULL OR LOWER(TRIM(a.user_create_by_g3w)) NOT IN ('flu','dig')))";
5107                                } else { // Manual (default)
5108                                    $parts[] = "((a.sync_import IS NULL OR a.sync_import != 1) AND (a.user_create_by_g3w IS NULL OR LOWER(TRIM(a.user_create_by_g3w)) NOT IN ('flu','dig')))";
5109                                }
5110                            }
5111                            $where .= ' AND ('.implode(' OR ', $parts).') ';
5112                        }
5113
5114                        continue;
5115                    } elseif ($key == 'g3w_warning') {
5116                        $statusName = 'a.g3w_warning';
5117                        if ($data['values']) {
5118                            foreach ($data['values'] as $k => $v) {
5119                                if ($v == 'No') {
5120                                    $data['values'][$k] = 0;
5121                                } else {
5122                                    $data['values'][$k] = 1;
5123                                }
5124                            }
5125                        }
5126                    } elseif ($key == 'company_name') {
5127                        $statusName = 'b.name';
5128                    }
5129
5130                    $val = implode("','", $data['values']);
5131
5132                    if (in_array(null, $data['values'], true)) {
5133                        $where .= " AND ({$statusName} IN ('{$val}') OR {$statusName} IS NULL) ";
5134                    } else {
5135                        $where .= " AND {$statusName} IN ('{$val}') ";
5136                    }
5137                }
5138            }
5139        }
5140
5141        $whereSendToClient = $where;
5142
5143        $offset = $start;
5144        $limit = $end - $start;
5145
5146        $subquery = ",(SELECT can_write FROM tbl_company_users WHERE company_id = a.company_id AND user_id = {$userId}) can_write";
5147
5148        // Quotations accepted without acceptance_date
5149        // Quotations with state "No encontrado" or "Estado no reconocido en FST"
5150        // Quotations with not comercial in out database
5151        // Phone number on null
5152        // Source on null
5153        // Client name on null
5154        // Budget Type on null
5155        if (isset($data['g3w_warning'])) {
5156            $g3w_warning = $data['g3w_warning'] == 'No' ? 0 : 1;
5157            /*$where .= "
5158            AND a.sync_import = 1
5159                AND (
5160                    a.budget_status_id IN (13, 14)
5161                    OR (
5162                        a.commercial IS NULL
5163                        OR NOT EXISTS (
5164                            SELECT 1 FROM tbl_users u WHERE u.name = a.commercial
5165                        )
5166                        OR a.phone_number IS NULL
5167                        OR a.source_id IS NULL
5168                        OR a.budget_type_id IS NULL
5169                        OR (a.client IS NULL OR TRIM(a.client) = '')
5170                        OR (a.email IS NULL OR TRIM(a.email) = '')
5171                    )
5172                )
5173             ";*/
5174            $where .= '
5175                AND (a.sync_import = 1 OR a.sync_import_edited = 1)
5176                AND a.g3w_warning = '.$g3w_warning;
5177        }
5178
5179        if ($isInvalidEmail) {
5180            $blacklist = implode('|', $this->getBlacklistEmails());
5181
5182            // FIRE-864 follow-up (04/05): regex anchored with `^...$` so
5183            // garbage-prefix-then-valid-email values like `no tiene@notien.com`
5184            // are flagged as malformed. The pre-fix un-anchored pattern matched
5185            // the substring `tiene@notien.com` and let those rows slip past the
5186            // bucket reclassifier — leaving 17 Cataluña rows in `Enviado/Nuevo/
5187            // Listo para enviar` despite showing up in the badge count.
5188            $where .= "
5189                AND
5190                (
5191                    a.x_status IN ('Error','Error - Bounce','Error - Spam')
5192                    OR (
5193                        a.email IS NULL
5194                        OR TRIM(a.email) = ''
5195                        OR a.email NOT REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$'
5196                        OR a.email REGEXP '($blacklist)'
5197                    )
5198                )
5199                AND a.budget_status_id IN(1, 2, 11, 17, 21, 22)
5200                AND (a.send_channel IS NULL OR a.send_channel = 'email')";
5201            // FIRE-1377: only email-channel budgets belong in "emails with
5202            // error"; correo ordinario / WhatsApp are never email-validated.
5203            // NULL covers legacy rows predating the send_channel column.
5204        }
5205
5206        if ($isFollowUp) {
5207            $blacklist = implode('|', $this->getBlacklistEmails());
5208
5209            // FIRE-864 follow-up (04/05): anchored email pattern so `no
5210            // tiene@notien.com` and friends are correctly excluded from
5211            // follow-ups too. Mirror of the invalid_email branch above.
5212            $where .= "
5213                AND (
5214                    a.email IS NOT NULL
5215                    AND TRIM(a.email) != ''
5216                    AND a.email REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$'
5217                    AND a.email NOT REGEXP '($blacklist)'
5218                )";
5219        }
5220
5221        if ($isNoEmailFollowUp) {
5222            // Seguimiento de clientes sin mail: pending follow-ups for
5223            // quotations whose email is missing/invalid/blacklisted, so
5224            // they can be chased through other channels (WhatsApp, phone,
5225            // regular mail). Mirrors the follow-up gating (status 2,
5226            // overdue last_follow_up_date, total_sent under company limit)
5227            // but inverts the email-quality check.
5228            $blacklist = implode('|', $this->getBlacklistEmails());
5229            $where .= "
5230                AND a.budget_status_id = 2
5231                AND a.last_follow_up_date IS NOT NULL
5232                AND a.last_follow_up_date > 0
5233                AND a.last_follow_up_date < NOW()
5234                AND a.reason_for_not_following_up_id IS NULL
5235                AND (
5236                    a.email IS NULL
5237                    OR TRIM(a.email) = ''
5238                    OR a.email NOT REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$'
5239                    OR a.email REGEXP '($blacklist)'
5240                )";
5241        }
5242
5243        $query = "SELECT
5244                        a.id,
5245                        a.quote_id,
5246                        a.internal_quote_id,
5247                        a.company_id,
5248                        b.name company_name,
5249                        a.client,
5250                        c.name client_type,
5251                        c.customer_type_id,
5252                        s.name segment,
5253                        s.segment_id,
5254                        a.request_date,
5255                        a.visit_date,
5256                        a.issue_date,
5257                        a.acceptance_date,
5258                        a.internal_quote_id,
5259                        DATE_FORMAT(a.request_date, '%d/%m/%Y') request_date_translate,
5260                        DATE_FORMAT(a.issue_date, '%d/%m/%Y') issue_date_translate,
5261                        DATE_FORMAT(a.acceptance_date, '%d/%m/%Y') acceptance_date_translate,
5262                        DATE_FORMAT(a.last_follow_up_date, '%d/%m/%Y') last_follow_up_date_translate,
5263                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
5264                        DATE_FORMAT(a.accepted_at, '%d/%m/%Y') accepted_at_translate,
5265                        a.phone_number,
5266                        a.email,
5267                        a.send_channel,
5268                        a.direccion_postal,
5269                        a.sent_date,
5270                        a.duration,
5271                        a.order_number,
5272                        d.name 'type',
5273                        d.budget_type_id,
5274                        e.name 'status',
5275                        e.budget_status_id,
5276                        f.name as source,
5277                        f.source_id,
5278                        a.codigo_id,
5279                        co.name AS codigo,
5280                        a.amount,
5281                        g.name reason_for_not_following_up,
5282                        a.reason_for_not_following_up_id,
5283                        a.reason_for_rejection_id,
5284                        a.last_follow_up_date,
5285                        a.last_follow_up_comment,
5286                        CASE WHEN a.reason_for_rejection_id IS NULL THEN a.reason_for_rejection ELSE h.name END reason_for_rejection,
5287                        a.commercial,
5288                        a.user_commercial_by_g3w,
5289                        a.user_create_by_g3w,
5290                        a.created_by,
5291                        a.created_at,
5292                        a.updated_by,
5293                        a.updated_at,
5294                        a.total_sent,
5295                        a.has_attachment,
5296                        a.for_approval,
5297                        a.approval_type,
5298                        a.requires_technical_office,
5299                        a.box_work_g3w,
5300                        a.people_assigned_to_the_job,
5301                        a.duration_of_job_in_days,
5302                        a.estimated_cost_of_materials,
5303                        a.budget_margin_enabled,
5304                        a.labor_manual_override,
5305                        a.question_enabled,
5306                        a.cost_of_labor,
5307                        a.total_cost_of_job,
5308                        a.invoice_margin invoice_margin,
5309                        a.margin_for_the_company margin_for_the_company,
5310                        a.margin_on_invoice_per_day_per_worker,
5311                        a.revenue_per_date_per_worked,
5312                        a.commission_cost,
5313                        a.commission_pct,
5314                        a.gross_margin,
5315                        a.labor_percentage,
5316                        a.question_ids,
5317                        a.question_ids_no,
5318                        a.approved_at,
5319                        a.approved_by,
5320                        a.rejected_at,
5321                        a.rejected_by,
5322                        a.approved_at_v2,
5323                        a.approved_by_v2,
5324                        a.rejected_at_v2,
5325                        a.rejected_by_v2,
5326                        a.accepted_at,
5327                        a.accepted_by,
5328                        a.is_validated,
5329                        a.maintenance_potential,
5330                        a.coverage_contract_signed,
5331                        a.resource_id,
5332                        a.x_status,
5333                        a.likehood,
5334                        a.sync_import,
5335                        a.sync_import_edited,
5336                        a.sync_cofrai_import,
5337                        a.g3w_warning,
5338                        a.g3w_warning_fields,
5339                        a.id_solicitud_duplicity,
5340                        SUBSTRING_INDEX(a.email, '@', -1) domain
5341                        {$matchScoreCol}
5342                        {$subquery}
5343                    FROM
5344                        tbl_quotations a
5345                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
5346                        LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
5347                        LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
5348                        LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
5349                        LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
5350                        LEFT JOIN tbl_sources f ON a.source_id = f.source_id
5351                        LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
5352                        LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
5353                        LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
5354                        {$lasLeftJoin}
5355                    WHERE a.for_add = 0 {$where} {$whereBlocked}
5356                    {$orderBy}
5357                    LIMIT {$offset}, {$limit}
5358                    ";
5359        // FIRE-1174: GROUP BY a.id removed. Every LEFT JOIN above is eq_ref on
5360        // PK of a tiny lookup table — none can duplicate a.id. The
5361        // `lasLeftJoin` email-split temp also has its own inner GROUP BY a.id
5362        // before joining back on a.id, so it returns at most 1 row per a.id.
5363        // Verified on prod 2026-06-01: count with vs. without GROUP BY a.id
5364        // returned exactly 47,820 rows. The outer GROUP BY was costing a
5365        // temp table + filesort for zero dedup benefit.
5366        // return $query;
5367        // FIRE-1174 + FIRE-1145: skip the cache layer entirely for short in-progress
5368        // search inputs (1-2 chars). For empty searchText or ≥ 3 chars we still
5369        // cache via ResultCache (domain-tagged so mutations forget only the
5370        // 'quotations' bucket, not the whole app cache).
5371        if ($shouldCacheList) {
5372            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
5373        } else {
5374            $result = DB::select($query);
5375        }
5376
5377        $totalQuery = "SELECT
5378                            COUNT(a.id) totalRowCount,
5379                            SUM(CAST(a.amount AS DECIMAL(10,2))) totalAmount
5380                        FROM
5381                            tbl_quotations a
5382                            LEFT JOIN tbl_companies b ON a.company_id = b.company_id
5383                            LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
5384                            LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
5385                            LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
5386                            LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
5387                            LEFT JOIN tbl_sources f ON a.source_id = f.source_id
5388                            LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
5389                            LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
5390                            LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
5391                            {$lasLeftJoin}
5392                        WHERE a.for_add = 0
5393                        {$where} {$whereBlocked}";
5394
5395        // FIRE-1174 + FIRE-1145: see $shouldCacheList note — same gating, tagged.
5396        if ($shouldCacheList) {
5397            $countQuery = ResultCache::remember('quotations', $totalQuery, 600, fn () => DB::select($totalQuery));
5398        } else {
5399            $countQuery = DB::select($totalQuery);
5400        }
5401
5402        $totalToFollowUpQuery = "SELECT
5403                                        COUNT(DISTINCT a.id) totalRowCount
5404                                    FROM
5405                                        tbl_quotations a
5406                                    LEFT JOIN tbl_companies b ON a.company_id = b.company_id
5407                                    LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
5408                                    LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
5409                                    LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
5410                                    LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
5411                                    LEFT JOIN tbl_sources f ON a.source_id = f.source_id
5412                                    LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
5413                                    LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
5414                                    LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
5415                                    LEFT JOIN (
5416                                        SELECT
5417                                        a.id,
5418                                        SUBSTRING_INDEX(
5419                                            SUBSTRING_INDEX(a.email, ',', n.digit + 1),
5420                                            ',',
5421                                            -1
5422                                        ) AS email_domain
5423                                        FROM
5424                                        tbl_quotations a
5425                                        INNER JOIN (
5426                                            SELECT
5427                                            0 AS digit
5428                                            UNION ALL
5429                                            SELECT
5430                                            1
5431                                            UNION ALL
5432                                            SELECT
5433                                            2
5434                                            UNION ALL
5435                                            SELECT
5436                                            3
5437                                            UNION ALL
5438                                            SELECT
5439                                            4
5440                                            UNION ALL
5441                                            SELECT
5442                                            5
5443                                            UNION ALL
5444                                            SELECT
5445                                            6
5446                                            UNION ALL
5447                                            SELECT
5448                                            7
5449                                            UNION ALL
5450                                            SELECT
5451                                            8
5452                                            UNION ALL
5453                                            SELECT
5454                                            9
5455                                        ) n ON LENGTH(
5456                                            REPLACE(a.email, ',', '')
5457                                        ) <= LENGTH(a.email)- n.digit
5458                                        GROUP BY a.id
5459                                    ) temp ON a.id = temp.id
5460                                    WHERE
5461                                    a.last_follow_up_date < NOW()
5462                                    AND a.budget_status_id IN (2)
5463                                    AND a.budget_type_id IS NOT NULL
5464                                    AND a.email IS NOT NULL
5465                                    AND a.email <> ''
5466                                    AND NOT EXISTS (
5467                                        SELECT
5468                                        1
5469                                        FROM
5470                                        tbl_blocked_domains bd
5471                                        WHERE
5472                                        temp.email_domain LIKE CONCAT('%', bd.domain, '%')
5473                                        AND bd.company_id = a.company_id
5474                                    )
5475                                    AND a.last_follow_up_date IS NOT NULL
5476                                    AND a.reason_for_not_following_up_id IS NULL
5477                                    AND a.last_follow_up_date > 0
5478                                    AND a.total_sent < b.limit_reminder_emails
5479                                    AND a.for_add = 0
5480                                    {$where}";
5481
5482        // FIRE-1174 + FIRE-1145: see $shouldCacheList note — same gating, tagged.
5483        if ($shouldCacheList) {
5484            $countToFollowUpQuery = ResultCache::remember('quotations', $totalToFollowUpQuery, 600, fn () => DB::select($totalToFollowUpQuery));
5485        } else {
5486            $countToFollowUpQuery = DB::select($totalToFollowUpQuery);
5487        }
5488
5489        $query = 'SELECT
5490                            COUNT(1) as count,
5491                            SUM(a.amount) as total_amount
5492                        FROM tbl_quotations a
5493                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
5494                        LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
5495                        LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
5496                        LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
5497                        LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
5498                        LEFT JOIN tbl_sources f ON a.source_id = f.source_id
5499                        LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
5500                        LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
5501                        LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
5502                        WHERE a.budget_status_id = 11
5503                        AND a.email IS NOT NULL
5504                        AND a.budget_type_id IS NOT NULL
5505                        -- Budgets still inside the approval circuit are not
5506                        -- sendable, so they must not inflate this counter
5507                        -- either. See the is_send_to_client filter.
5508                        AND '.self::NOT_PENDING_APPROVAL_SQL."
5509                        {$whereSendToClient}
5510                        ";
5511
5512        // FIRE-1174 + FIRE-1145: see $shouldCacheList note — same gating, tagged.
5513        if ($shouldCacheList) {
5514            $totalSendToClient = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
5515        } else {
5516            $totalSendToClient = DB::select($query);
5517        }
5518
5519        return response([
5520            'message' => 'OK',
5521            'data' => $result,
5522            'totalAmount' => $countQuery[0]->totalAmount,
5523            'totalRowCount' => $countQuery[0]->totalRowCount,
5524            'totalToFollowUpRowCount' => $countToFollowUpQuery[0]->totalRowCount,
5525            'totalSendToClient' => $totalSendToClient[0]->count,
5526            'totalSendToClientAmount' => $totalSendToClient[0]->total_amount,
5527        ]);
5528
5529        // } catch (\Exception $e) {
5530        //     return response(['message' => 'KO', 'error' => $e->getMessage()]);
5531        // }
5532
5533    }
5534
5535    /**
5536     * Orders table listing for the new <app-data-table>.
5537     *
5538     * Intentionally minimal: every valid budget (for_add = 0) for the user's
5539     * company scope — no search, sort or pagination. Returns the same row shape
5540     * the front end expects ({ data, totalRowCount, totalAmount }) so the table
5541     * and the edit modal keep working. The legacy list_quotations stays in
5542     * place for the many other callers that depend on its richer filter model.
5543     */
5544    public function list_orders_table(Request $request): ResponseFactory|HttpResponse
5545    {
5546        try {
5547            // Titan → Zeus bridge (read). Only a listing scoped to ONE bridged
5548            // company is forwarded — "all companies in scope" spans regions and
5549            // no single upstream can answer it. Zeus aliases listOrdersTable to
5550            // the same handler, so the wire path follows the route that was hit.
5551            $zeus = app(ZeusBridge::class);
5552            $forward = $zeus->listQuotations(
5553                $request,
5554                str_contains((string) $request->path(), 'listOrdersTable')
5555                    ? '/api/listOrdersTable'
5556                    : '/api/listQuotations',
5557            );
5558
5559            if ($zeus->shouldReturnZeusResponse($forward)) {
5560                return $forward->toTitanResponse();
5561            }
5562
5563            $data = $request->all();
5564
5565            $companyId = (int) ($data['company_id'] ?? 0);
5566
5567            // Pagination window — the table infinite-scrolls 300 rows at a time
5568            // (start = rows already loaded, end = start + 300). ORDER BY a.id
5569            // DESC + LIMIT rides idx_listquot_company_id_desc (company_id,
5570            // id DESC) → ~7ms per page regardless of table size.
5571            $start = max(0, (int) ($data['start'] ?? 0));
5572            $limit = (int) ($data['end'] ?? 300) - $start;
5573            $limit = $limit > 0 ? min($limit, 1000) : 300;
5574
5575            // FIRE-1174: gate the 10-min query cache to avoid per-keystroke churn
5576            // (same policy as list_quotations). Cache the cold "no search" path
5577            // and stable searches (>= 3 chars); skip the noisy 1-2 char prefixes.
5578            $cacheSearch = trim((string) ($data['searchText'] ?? ''));
5579            $shouldCacheList = $cacheSearch === '' || strlen($cacheSearch) >= 3;
5580
5581            // for_add = 0 (valid budgets) + server-side company scoping.
5582            $where = ' AND a.for_add = 0 ';
5583            if ($companyId != 0) {
5584                $where .= " AND a.company_id = {$companyId} ";
5585            } elseif ($this->companyId) {
5586                $where .= " AND a.company_id IN ({$this->companyId}) ";
5587            }
5588
5589            // Company-only scope, captured before the advanced filters are
5590            // appended — used by the distinct-values mode below so the filter
5591            // modal offers every value in scope, not just those left after a
5592            // partially-applied filter.
5593            $scopeWhere = $where;
5594
5595            // Advanced Search — explicit Order IDs.
5596            if (isset($data['ids']) && is_array($data['ids'])) {
5597                $numericIds = array_values(array_filter(
5598                    array_map('intval', $data['ids']),
5599                    fn ($n) => $n > 0
5600                ));
5601                if (count($numericIds) > 0) {
5602                    $where .= ' AND a.id IN ('.implode(',', $numericIds).') ';
5603                }
5604            }
5605
5606            // Advanced Search — explicit Order IDs to EXCLUDE (the select-all
5607            // "all matching except these unticked rows" path). Mirrors the `ids`
5608            // include filter above. Previously this param was accepted by every
5609            // caller but never applied here, so unticked rows in a select-all
5610            // selection were still actioned (e.g. follow-ups sent to a budget
5611            // the user had unchecked). No-op when empty.
5612            if (isset($data['ids_not_in']) && is_array($data['ids_not_in'])) {
5613                $excludeIds = array_values(array_filter(
5614                    array_map('intval', $data['ids_not_in']),
5615                    fn ($n) => $n > 0
5616                ));
5617                if (count($excludeIds) > 0) {
5618                    $where .= ' AND a.id NOT IN ('.implode(',', $excludeIds).') ';
5619                }
5620            }
5621
5622            // Advanced Search — "Seguimiento de clientes sin mail": overdue
5623            // follow-ups (status Enviado) whose email is missing/invalid/blacklisted
5624            // (mirrors the same clause in list_quotations).
5625            if (! empty($data['is_no_email_follow_up'])) {
5626                $blacklist = implode('|', $this->getBlacklistEmails());
5627                $emailConds = [
5628                    'a.email IS NULL',
5629                    "TRIM(a.email) = ''",
5630                    "a.email NOT REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$'",
5631                ];
5632                if ($blacklist !== '') {
5633                    $emailConds[] = "a.email REGEXP '($blacklist)'";
5634                }
5635                $where .= '
5636                    AND a.budget_status_id = 2
5637                    AND a.last_follow_up_date IS NOT NULL
5638                    AND a.last_follow_up_date > 0
5639                    AND a.last_follow_up_date < NOW()
5640                    AND a.reason_for_not_following_up_id IS NULL
5641                    AND ('.implode(' OR ', $emailConds).')';
5642            }
5643
5644            // Whether any clause references a joined table (forces the count /
5645            // ids_only queries to include the joins).
5646            $forceJoins = false;
5647
5648            // Advanced Search — "Pendientes de seguimiento": rows that need a
5649            // follow-up. Matches get_total_quotations_by_budget_status
5650            // (totalPendingFollowUps) EXACTLY — the authoritative "needs follow up"
5651            // total: status Enviado (2), an overdue last_follow_up_date, no "reason
5652            // for not following up", under the per-company reminder limit, a
5653            // present + valid + non-blacklisted email NOT on a company-blocked
5654            // domain. (No budget_type requirement.)
5655            if (! empty($data['is_send_follow_up'])) {
5656                // A follow-up is a client-facing email about the budget, so a
5657                // budget awaiting approval is not chased either (part of the
5658                // shared rule). This bucket is also the selection source for
5659                // send_email_follow_ups.
5660                $where .= self::pendingFollowUpSql();
5661                $forceJoins = true; // references b.limit_reminder_emails
5662            }
5663
5664            // Advanced Search — "Pendientes de envío a cliente".
5665            //
5666            // Status 11 comes from Gestiona, which knows nothing about Titan's
5667            // approval circuit, so "Listo para enviar" on its own does NOT mean
5668            // sendable: a budget over threshold sits at 11 while still awaiting
5669            // its approver. This bucket doubles as the selection source for
5670            // `send_email_to_client` (it passes is_send_to_client = 1), so
5671            // leaving pending rows in it is what let unapproved budgets reach
5672            // clients. Same predicate as the "Requiere aprobación" column
5673            // filter and as the edit form's `sendBlockedByApproval`.
5674            if (! empty($data['is_send_to_client'])) {
5675                $where .= ' AND a.budget_status_id = 11 AND a.email IS NOT NULL AND a.budget_type_id IS NOT NULL '
5676                    .' AND '.self::NOT_PENDING_APPROVAL_SQL.' ';
5677            }
5678
5679            // Advanced Search — "Solicitudes y visitas" (dashboard tile
5680            // totalRequestAndVisit): Solicitud (6), Visita (8). "En curso"
5681            // (12) is intentionally excluded from this filter.
5682            if (! empty($data['is_request_visit'])) {
5683                $where .= ' AND a.budget_status_id IN (6, 8) ';
5684            }
5685
5686            // Advanced Search — "Emails con error" (dashboard tile totalError):
5687            // a SendGrid error status, or a missing / malformed / blacklisted
5688            // email, among the still-in-pipeline statuses.
5689            //
5690            // FIRE-1560: los presupuestos rechazados/anulados y sus variantes
5691            // no deben aparecer en "Emails con error" — Berta pidió excluir
5692            // los mismos estados que en el tile de G3W (títulos del ticket
5693            // "no cuenten para fallos ni de email ni en gestiona"). Esto
5694            // implica sacar 17, 21, 22 del whitelist previo, dejando solo
5695            // los estados vivos donde un error de email sigue siendo
5696            // accionable: 1 Nuevo, 2 Enviado, 11 Listo para enviar.
5697            if (! empty($data['is_email_error'])) {
5698                $emailRegex = '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$';
5699                $blacklist = implode('|', $this->getBlacklistEmails());
5700                $emailConds = [
5701                    'a.email IS NULL',
5702                    "TRIM(a.email) = ''",
5703                    "a.email NOT REGEXP '{$emailRegex}'",
5704                ];
5705                if ($blacklist !== '') {
5706                    $emailConds[] = "a.email REGEXP '({$blacklist})'";
5707                }
5708                $where .= "
5709                    AND (
5710                        a.x_status IN ('Error','Error - Bounce','Error - Spam')
5711                        OR (".implode(' OR ', $emailConds).')
5712                    )
5713                    AND a.budget_status_id IN (1, 2, 11)
5714                    AND (a.send_channel IS NULL OR a.send_channel = \'email\') ';
5715                // FIRE-1377: only email-channel budgets can be "emails with
5716                // error". Correo ordinario / WhatsApp budgets are never
5717                // validated for email and must never surface in this bucket.
5718                // NULL covers legacy rows created before the column existed.
5719            }
5720
5721            // Advanced Search — "Fallos en G3W" (dashboard tile totalG3WError).
5722            // IFEX rows are also sync_import=1 and can carry g3w_warning=1
5723            // when they lack a budget_type_id (or other required fields), but
5724            // they are NOT G3W issues — they belong to a separate IFEX
5725            // integration (commercial='Ifex'). Exclude them from this bucket
5726            // to keep the tile semantically pure. The user-facing column
5727            // filter (build_orders_table_filters) is untouched so ops can
5728            // still list ALL g3w_warning rows including IFEX when needed.
5729            //
5730            // FIRE-1560: presupuestos rechazados/anulados (y sus variantes)
5731            // no deben contar como warning de G3W. Berta pidió excluir
5732            // budget_status_id IN (4,5,7,12,15,17,18,20,21,22) del tile y
5733            // del filtro de lista. Mismo criterio abajo en el contador del
5734            // tile (~10896).
5735            if (! empty($data['is_g3w_warning'])) {
5736                $where .= " AND a.g3w_warning = 1
5737                            AND (a.commercial IS NULL OR a.commercial <> 'Ifex')
5738                            AND a.budget_status_id NOT IN (4, 5, 7, 12, 15, 17, 18, 20, 21, 22) ";
5739            }
5740
5741            // Advanced Search: "Solo duplicados" — show only quotes still flagged
5742            // as an active duplicate by the Lambda checkduplicate writer
5743            // (id_solicitud_duplicity holds the target quote's id/quote_id).
5744            // The 'R' prefix marks duplicates the user already rejected/dismissed
5745            // via setSolicitudDuplicity(), so exclude those to match the
5746            // frontend's own startsWith('R') "already actioned" interpretation.
5747            if (! empty($data['is_only_duplicates'])) {
5748                $where .= " AND a.id_solicitud_duplicity IS NOT NULL
5749                            AND a.id_solicitud_duplicity <> ''
5750                            AND a.id_solicitud_duplicity NOT LIKE 'R%' ";
5751            }
5752
5753            // Global quick search — match the keyword against every meaningful
5754            // field (OR), mirroring the field set list_quotations searches.
5755            if (isset($data['searchText']) && trim((string) $data['searchText']) !== '') {
5756                $searchText = addslashes(trim((string) $data['searchText']));
5757                $searchFields = [
5758                    'a.quote_id', 'a.internal_quote_id', 'a.box_work_g3w', 's.name', 'b.name',
5759                    'a.client', 'c.name', 'a.phone_number', 'a.email', 'a.order_number',
5760                    'd.name', 'e.name', 'f.name', 'a.amount', 'g.name', 'h.name',
5761                    'a.last_follow_up_comment', 'a.x_status', 'a.likehood', 'a.commercial',
5762                    'a.user_commercial_by_g3w', 'a.user_create_by_g3w', 'a.created_by',
5763                    'a.updated_by', 'a.approved_by', 'a.rejected_by', 'a.accepted_by',
5764                    'a.g3w_warning_fields', 'a.reason_for_rejection',
5765                ];
5766                $likes = array_map(fn ($f) => "{$f} LIKE '%{$searchText}%'", $searchFields);
5767                $where .= ' AND ('.implode(' OR ', $likes).') ';
5768                $forceJoins = true; // references joined columns (b/c/d/e/f/g/h.name)
5769            }
5770
5771            // Advanced filter modal — combined per-field filters (AND-ed).
5772            $filterWhere = $this->build_orders_table_filters($data['filterModel'] ?? []);
5773            $where .= $filterWhere;
5774            // Filters may reference joined columns (e.name, d.name, …) so the
5775            // otherwise join-free count / ids_only queries need the joins too.
5776            $hasJoinFilter = $filterWhere !== '' || $forceJoins;
5777
5778            $fromJoins = '
5779                FROM tbl_quotations a
5780                LEFT JOIN tbl_companies b ON a.company_id = b.company_id
5781                LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
5782                LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
5783                LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
5784                LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
5785                LEFT JOIN tbl_sources f ON a.source_id = f.source_id
5786                LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
5787                LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
5788                LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id ';
5789
5790            // Distinct-values mode (same endpoint): returns the distinct values
5791            // for the requested fields within the company scope, so the filter
5792            // modal can render checkboxes for fields that have no preloaded list.
5793            // Blank/empty is excluded — the UI always adds a "(Vacío)" option.
5794            if (! empty($data['distinct_fields']) && is_array($data['distinct_fields'])) {
5795                $distinctColMap = [
5796                    'accepted_by' => 'a.accepted_by',
5797                    'g3w_warning_fields' => 'a.g3w_warning_fields',
5798                    'reason_for_rejection' => 'h.name',
5799                    'reason_for_not_following_up' => 'g.name',
5800                    'likehood' => 'a.likehood',
5801                    'x_status' => 'a.x_status',
5802                ];
5803                $distinct = [];
5804                foreach ($data['distinct_fields'] as $field) {
5805                    if (! isset($distinctColMap[$field])) {
5806                        continue;
5807                    }
5808                    $col = $distinctColMap[$field];
5809                    $rows = DB::select("SELECT DISTINCT {$col} v {$fromJoins} WHERE 1=1 {$scopeWhere} AND {$col} IS NOT NULL AND {$col} <> '' ORDER BY {$col} LIMIT 1000");
5810                    $distinct[$field] = array_map(fn ($r) => $r->v, $rows);
5811                }
5812
5813                return response(['message' => 'OK', 'distinct' => $distinct]);
5814            }
5815
5816            // Eligibility-count mode: given the selection ($where already carries
5817            // the company scope + the selected ids), return how many of those
5818            // rows actually qualify to be sent — so the buttons can show the
5819            // real "will be sent" count, not the raw selection size.
5820            if (! empty($data['count_eligible'])) {
5821                // Follow-up — identical to get_total_quotations_by_budget_status
5822                // (totalPendingFollowUps) and the is_send_follow_up filter above:
5823                // status Enviado (2), overdue last_follow_up_date, no "reason for
5824                // not following up", under the per-company limit, a present + valid
5825                // + non-blacklisted email not on a company-blocked domain. No
5826                // budget_type requirement.
5827                // Same rule as the is_send_follow_up bucket: this count is what
5828                // reveals the bulk follow-up button and sizes its badge.
5829                $fuWhere = self::pendingFollowUpSql();
5830                $followUp = DB::select('SELECT COUNT(a.id) c FROM tbl_quotations a JOIN tbl_companies b ON a.company_id = b.company_id WHERE 1=1 '.$where.$fuWhere)[0]->c;
5831
5832                // Send to client — same as the list_quotations totalSendToClient
5833                // count: status Listo para enviar (11), email + budget type set,
5834                // and not awaiting an approval decision. This count is what
5835                // reveals the bulk "Enviar a los clientes" button and sizes its
5836                // badge, so a budget excluded here can no longer be offered for
5837                // bulk sending even though the row stays selectable for the
5838                // other bulk actions.
5839                $stcWhere = ' AND a.budget_status_id = 11 AND a.email IS NOT NULL AND a.budget_type_id IS NOT NULL '
5840                    .' AND '.self::NOT_PENDING_APPROVAL_SQL.' ';
5841                $sendToClient = DB::select('SELECT COUNT(a.id) c FROM tbl_quotations a WHERE 1=1 '.$where.$stcWhere)[0]->c;
5842
5843                return response([
5844                    'message' => 'OK',
5845                    'send_follow_up_count' => (int) $followUp,
5846                    'send_to_client_count' => (int) $sendToClient,
5847                ]);
5848            }
5849
5850            // Lightweight id-only mode (same endpoint): returns every matching id
5851            // for the current scope so the table's "select all" can span all
5852            // pages, not just the rows scrolled into view.
5853            if (! empty($data['ids_only'])) {
5854                $idFrom = $hasJoinFilter ? $fromJoins : ' FROM tbl_quotations a ';
5855                $idQuery = 'SELECT a.id '.$idFrom.' WHERE 1=1 '.$where;
5856                $idRows = $shouldCacheList
5857                    ? ResultCache::remember('quotations', $idQuery, 600, fn () => DB::select($idQuery))
5858                    : DB::select($idQuery);
5859                $ids = array_map(fn ($r) => (int) $r->id, $idRows);
5860
5861                return response([
5862                    'message' => 'OK',
5863                    'ids' => $ids,
5864                    'totalRowCount' => count($ids),
5865                ]);
5866            }
5867
5868            $joins = $fromJoins.' WHERE 1=1 '.$where;
5869
5870            // Sorting — whitelisted column per table field; defaults to newest first.
5871            $sortMap = [
5872                'quote_id' => 'CAST(a.quote_id AS DOUBLE)',
5873                'internal_quote_id' => 'a.internal_quote_id',
5874                'company_name' => 'b.name',
5875                'client' => 'a.client',
5876                'amount' => 'CAST(a.amount AS DOUBLE)',
5877                // Margins are stored as strings: sort by their numeric value.
5878                // Not masked by budget_margin_enabled any more (same as the
5879                // SELECT): G3W imports have real margins with the flag at 0,
5880                // and hiding them left the column blank and unsortable.
5881                'invoice_margin' => 'CAST(a.invoice_margin AS DECIMAL(20,4))',
5882                'margin_for_the_company' => 'CAST(a.margin_for_the_company AS DECIMAL(20,4))',
5883                'type' => 'd.name',
5884                'status' => 'e.name',
5885                'created_by' => 'a.created_by',
5886                'commercial' => 'a.commercial',
5887                'created_at_translate' => 'a.created_at',
5888                'acceptance_date_translate' => 'a.acceptance_date',
5889                'request_date_translate' => 'a.request_date',
5890                'issue_date_translate' => 'a.issue_date',
5891                'sent_date' => 'a.sent_date',
5892                'duration' => 'CAST(a.duration AS DOUBLE)',
5893                'client_type' => 'c.name',
5894                'segment' => 's.name',
5895                'likehood' => 'a.likehood',
5896                'source' => 'f.name',
5897                'last_follow_up_date_translate' => 'a.last_follow_up_date',
5898                'reason_for_not_following_up' => 'g.name',
5899                'reason_for_rejection' => 'h.name',
5900                'email' => 'a.email',
5901                'x_status' => 'a.x_status',
5902                'phone_number' => 'a.phone_number',
5903                'order_number' => 'a.order_number',
5904                'box_work_g3w' => 'a.box_work_g3w',
5905                'for_approval' => 'a.for_approval',
5906                'approval_type' => 'a.approval_type',
5907                'has_attachment' => 'a.has_attachment',
5908                'accepted_by' => 'a.accepted_by',
5909                'accepted_at_translate' => 'a.accepted_at',
5910                'sync_import' => 'a.sync_import',
5911                'g3w_warning' => 'a.g3w_warning',
5912                'g3w_warning_fields' => 'a.g3w_warning_fields',
5913                'id' => 'a.id',
5914            ];
5915            $orderBy = ' ORDER BY a.id DESC ';
5916            $sort = $data['sortModel'] ?? [];
5917            if (is_array($sort) && count($sort) > 0 && isset($sort[0]['colId']) && isset($sortMap[$sort[0]['colId']])) {
5918                $dir = strtolower((string) ($sort[0]['sort'] ?? 'asc')) === 'desc' ? 'DESC' : 'ASC';
5919                $orderBy = ' ORDER BY '.$sortMap[$sort[0]['colId']]." {$dir} ";
5920            }
5921
5922            // Sentry perf (listQuotations / listOrdersTable slow DB): deferred
5923            // join. Page over narrow ids first, then fetch the ~90 wide columns
5924            // and 9 lookups for just this page — instead of sorting every wide
5925            // row in scope (an "All companies" IN-list can't read id order off
5926            // an index) and materialising all skipped rows on deep pages.
5927            // Only for a.id ordering (unique → identical rows and order) and
5928            // under the same "no joined column in WHERE" condition the
5929            // join-free count below already relies on.
5930            $pageFrom = $joins.$orderBy." LIMIT {$start}, {$limit}";
5931            if (! $hasJoinFilter && preg_match('/^ ORDER BY a\.id (ASC|DESC) $/', $orderBy)) {
5932                $pageFrom = str_replace(
5933                    'FROM tbl_quotations a',
5934                    "FROM (SELECT a.id FROM tbl_quotations a WHERE 1=1 {$where}{$orderBy} LIMIT {$start}, {$limit}) pg
5935                JOIN tbl_quotations a ON a.id = pg.id",
5936                    $fromJoins
5937                ).$orderBy;
5938            }
5939
5940            $query = 'SELECT
5941                        a.id,
5942                        a.quote_id,
5943                        a.internal_quote_id,
5944                        a.company_id,
5945                        b.name company_name,
5946                        a.client,
5947                        c.name client_type,
5948                        c.customer_type_id,
5949                        s.name segment,
5950                        s.segment_id,
5951                        a.request_date,
5952                        a.visit_date,
5953                        a.issue_date,
5954                        a.acceptance_date,
5955                        DATE_FORMAT(a.request_date, "%d/%m/%Y") request_date_translate,
5956                        DATE_FORMAT(a.issue_date, "%d/%m/%Y") issue_date_translate,
5957                        DATE_FORMAT(a.acceptance_date, "%d/%m/%Y") acceptance_date_translate,
5958                        DATE_FORMAT(a.last_follow_up_date, "%d/%m/%Y") last_follow_up_date_translate,
5959                        DATE_FORMAT(a.created_at, "%d/%m/%Y") created_at_translate,
5960                        DATE_FORMAT(a.accepted_at, "%d/%m/%Y") accepted_at_translate,
5961                        a.phone_number,
5962                        a.email,
5963                        a.send_channel,
5964                        a.direccion_postal,
5965                        a.sent_date,
5966                        a.duration,
5967                        a.order_number,
5968                        d.name `type`,
5969                        d.budget_type_id,
5970                        e.name `status`,
5971                        e.budget_status_id,
5972                        f.name as source,
5973                        f.source_id,
5974                        a.codigo_id,
5975                        co.name AS codigo,
5976                        a.amount,
5977                        g.name reason_for_not_following_up,
5978                        a.reason_for_not_following_up_id,
5979                        a.reason_for_rejection_id,
5980                        a.last_follow_up_date,
5981                        a.last_follow_up_comment,
5982                        CASE WHEN a.reason_for_rejection_id IS NULL THEN a.reason_for_rejection ELSE h.name END reason_for_rejection,
5983                        a.commercial,
5984                        a.user_commercial_by_g3w,
5985                        a.user_create_by_g3w,
5986                        a.created_by,
5987                        a.created_at,
5988                        a.updated_by,
5989                        a.updated_at,
5990                        a.total_sent,
5991                        a.has_attachment,
5992                        a.for_approval,
5993                        a.approval_type,
5994                        a.requires_technical_office,
5995                        a.box_work_g3w,
5996                        a.people_assigned_to_the_job,
5997                        a.duration_of_job_in_days,
5998                        a.estimated_cost_of_materials,
5999                        a.budget_margin_enabled,
6000                        a.labor_manual_override,
6001                        a.question_enabled,
6002                        a.cost_of_labor,
6003                        a.total_cost_of_job,
6004                        a.invoice_margin invoice_margin,
6005                        a.margin_for_the_company margin_for_the_company,
6006                        a.margin_on_invoice_per_day_per_worker,
6007                        a.revenue_per_date_per_worked,
6008                        a.commission_cost,
6009                        a.commission_pct,
6010                        a.gross_margin,
6011                        a.labor_percentage,
6012                        a.question_ids,
6013                        a.question_ids_no,
6014                        a.approved_at,
6015                        a.approved_by,
6016                        a.rejected_at,
6017                        a.rejected_by,
6018                        a.approved_at_v2,
6019                        a.approved_by_v2,
6020                        a.rejected_at_v2,
6021                        a.rejected_by_v2,
6022                        a.accepted_at,
6023                        a.accepted_by,
6024                        a.is_validated,
6025                        a.maintenance_potential,
6026                        a.coverage_contract_signed,
6027                        a.resource_id,
6028                        a.x_status,
6029                        a.likehood,
6030                        a.sync_import,
6031                        a.sync_import_edited,
6032                        a.sync_cofrai_import,
6033                        a.g3w_warning,
6034                        a.g3w_warning_fields,
6035                        a.id_solicitud_duplicity,
6036                        SUBSTRING_INDEX(a.email, "@", -1) domain
6037                    '.$pageFrom;
6038
6039            $result = $shouldCacheList
6040                ? ResultCache::remember('quotations', $query, 600, fn () => DB::select($query))
6041                : DB::select($query);
6042
6043            // Count is join-free (~16ms vs ~255ms) when no filter references a
6044            // joined column; otherwise it must join so the filter resolves.
6045            $countFrom = $hasJoinFilter ? $fromJoins : ' FROM tbl_quotations a ';
6046            $totalQuery = 'SELECT COUNT(a.id) totalRowCount, SUM(CAST(a.amount AS DECIMAL(10,2))) totalAmount '.$countFrom.' WHERE 1=1 '.$where;
6047            $countRow = ($shouldCacheList
6048                ? ResultCache::remember('quotations', $totalQuery, 600, fn () => DB::select($totalQuery))
6049                : DB::select($totalQuery))[0];
6050
6051            return response([
6052                'message' => 'OK',
6053                'data' => $result,
6054                'totalRowCount' => (int) $countRow->totalRowCount,
6055                'totalAmount' => $countRow->totalAmount,
6056            ]);
6057
6058        } catch (\Exception $e) {
6059            report(AppException::fromException($e, 'LIST_ORDERS_TABLE_EXCEPTION'));
6060
6061            return response(['message' => 'KO', 'error' => $e->getMessage()]);
6062        }
6063    }
6064
6065    /**
6066     * Build the WHERE fragment for the Orders advanced-filter modal.
6067     *
6068     * The frontend sends a per-field map keyed by the table field, e.g.
6069     *   { status:   { type:'set',    values:['Enviado','__BLANK__'] },
6070     *     amount:   { type:'number', min:1000, max:5000 },
6071     *     issue_date:{ type:'date',  from:'2026-01-01', to:'2026-03-31' },
6072     *     client:   { type:'text',   contains:'acme' } }
6073     *
6074     * Fields are whitelisted (unknown keys ignored) and every value is escaped,
6075     * so the model is safe to interpolate. Clauses AND together.
6076     */
6077    private function build_orders_table_filters($filterModel): string
6078    {
6079        if (! is_array($filterModel) || empty($filterModel)) {
6080            return '';
6081        }
6082
6083        // field => SQL expression (mirrors the SELECT aliases / sort map).
6084        $colMap = [
6085            'quote_id' => 'a.quote_id', 'internal_quote_id' => 'a.internal_quote_id',
6086            'client' => 'a.client', 'company_name' => 'b.name', 'region' => 'b.region', 'email' => 'a.email',
6087            'phone_number' => 'a.phone_number', 'order_number' => 'a.order_number',
6088            'x_status' => 'a.x_status', 'likehood' => 'a.likehood',
6089            'reason_for_not_following_up' => 'g.name', 'reason_for_rejection' => 'h.name',
6090            'accepted_by' => 'a.accepted_by', 'box_work_g3w' => 'a.box_work_g3w',
6091            'g3w_warning_fields' => 'a.g3w_warning_fields',
6092            'status' => 'e.name', 'type' => 'd.name', 'client_type' => 'c.name',
6093            'segment' => 's.name', 'source' => 'f.name', 'commercial' => 'a.commercial',
6094            'created_by' => 'a.created_by',
6095            'amount' => 'a.amount', 'invoice_margin' => 'a.invoice_margin',
6096            'margin_for_the_company' => 'a.margin_for_the_company',
6097            'duration' => 'a.duration', 'id' => 'a.id',
6098            'created_at' => 'a.created_at', 'acceptance_date' => 'a.acceptance_date',
6099            'request_date' => 'a.request_date', 'issue_date' => 'a.issue_date',
6100            'sent_date' => 'a.sent_date',
6101            'last_follow_up_date' => 'a.last_follow_up_date', 'accepted_at' => 'a.accepted_at',
6102        ];
6103
6104        $w = '';
6105
6106        foreach ($filterModel as $field => $f) {
6107            if (! is_array($f) || empty($f['type'])) {
6108                continue;
6109            }
6110            $type = $f['type'];
6111
6112            // --- Derived set columns (no direct column / Yes-No / label) ---
6113            if ($field === 'for_approval' && $type === 'set') {
6114                $w .= $this->orders_yes_no_clause($f['values'] ?? [], self::PENDING_APPROVAL_SQL, self::NOT_PENDING_APPROVAL_SQL);
6115
6116                continue;
6117            }
6118            if ($field === 'has_attachment' && $type === 'set') {
6119                $w .= $this->orders_yes_no_clause($f['values'] ?? [], 'a.has_attachment > 0', '(a.has_attachment = 0 OR a.has_attachment IS NULL)');
6120
6121                continue;
6122            }
6123            if ($field === 'requires_technical_office' && $type === 'set') {
6124                $w .= $this->orders_yes_no_clause($f['values'] ?? [], 'a.requires_technical_office = 1', '(a.requires_technical_office <> 1 OR a.requires_technical_office IS NULL)');
6125
6126                continue;
6127            }
6128            if ($field === 'g3w_warning' && $type === 'set') {
6129                $w .= $this->orders_yes_no_clause($f['values'] ?? [], 'a.g3w_warning = 1', '(a.g3w_warning <> 1 OR a.g3w_warning IS NULL)');
6130
6131                continue;
6132            }
6133            if ($field === 'approval_type' && $type === 'set') {
6134                // Técnica / Financiera = waiting on that approver now, whatever
6135                // the circuit (single or both). Ambas = every dual-level quote.
6136                $map = [
6137                    '1' => self::PENDING_TECHNICAL_SQL,
6138                    '2' => self::PENDING_FINANCIAL_SQL,
6139                    '3' => 'a.approval_type = 3',
6140                    '__BLANK__' => '(a.approval_type IS NULL OR a.approval_type = 0)',
6141                ];
6142                $clauses = [];
6143                foreach ((array) ($f['values'] ?? []) as $v) {
6144                    $key = (string) $v;
6145                    if (isset($map[$key])) {
6146                        $clauses[] = $map[$key];
6147                    }
6148                }
6149                if ($clauses) {
6150                    $w .= ' AND ('.implode(' OR ', array_unique($clauses)).')';
6151                }
6152
6153                continue;
6154            }
6155            if ($field === 'sync_import' && $type === 'set') {
6156                $map = [
6157                    'flu' => "LOWER(a.user_create_by_g3w) = 'flu'",
6158                    'dig' => "LOWER(a.user_create_by_g3w) = 'dig'",
6159                    'g3w' => "(a.sync_import = 1 AND (a.user_create_by_g3w IS NULL OR LOWER(a.user_create_by_g3w) NOT IN ('flu','dig')))",
6160                    'manual' => "((a.sync_import <> 1 OR a.sync_import IS NULL) AND (a.user_create_by_g3w IS NULL OR LOWER(a.user_create_by_g3w) NOT IN ('flu','dig')))",
6161                ];
6162                $clauses = [];
6163                foreach ((array) ($f['values'] ?? []) as $v) {
6164                    $key = strtolower(trim((string) $v));
6165                    if (isset($map[$key])) {
6166                        $clauses[] = $map[$key];
6167                    }
6168                }
6169                if ($clauses) {
6170                    $w .= ' AND ('.implode(' OR ', array_unique($clauses)).')';
6171                }
6172
6173                continue;
6174            }
6175
6176            if (! isset($colMap[$field])) {
6177                continue;
6178            }
6179            $col = $colMap[$field];
6180
6181            if ($type === 'set') {
6182                $nonBlank = [];
6183                $hasBlank = false;
6184                foreach ((array) ($f['values'] ?? []) as $v) {
6185                    if ($v === null || $v === '' || $v === '__BLANK__') {
6186                        $hasBlank = true;
6187                    } else {
6188                        $nonBlank[] = addslashes((string) $v);
6189                    }
6190                }
6191                $clauses = [];
6192                if ($nonBlank) {
6193                    $clauses[] = "{$col} IN ('".implode("','", $nonBlank)."')";
6194                }
6195                if ($hasBlank) {
6196                    $clauses[] = "({$col} IS NULL OR {$col} = '')";
6197                }
6198                if ($clauses) {
6199                    $w .= ' AND ('.implode(' OR ', $clauses).')';
6200                }
6201            } elseif ($type === 'text') {
6202                $w .= $this->text_filter_clause($col, $f);
6203            } elseif ($type === 'number') {
6204                if (isset($f['min']) && $f['min'] !== '' && is_numeric($f['min'])) {
6205                    $w .= " AND CAST({$col} AS DECIMAL(20,4)) >= ".(float) $f['min'];
6206                }
6207                if (isset($f['max']) && $f['max'] !== '' && is_numeric($f['max'])) {
6208                    $w .= " AND CAST({$col} AS DECIMAL(20,4)) <= ".(float) $f['max'];
6209                }
6210            } elseif ($type === 'date') {
6211                // Range picker → start (from) / end (to) day, inclusive.
6212                $from = trim((string) ($f['from'] ?? ''));
6213                $to = trim((string) ($f['to'] ?? ''));
6214                if ($from !== '') {
6215                    $w .= " AND DATE({$col}) >= '".addslashes($from)."'";
6216                }
6217                if ($to !== '') {
6218                    $w .= " AND DATE({$col}) <= '".addslashes($to)."'";
6219                }
6220            }
6221        }
6222
6223        return $w;
6224    }
6225
6226    /**
6227     * Helper for Yes/No set filters: maps the selected 'yes'/'no' tokens to the
6228     * given SQL conditions and OR-combines them.
6229     */
6230    private function orders_yes_no_clause(array $values, string $yesSql, string $noSql): string
6231    {
6232        $clauses = [];
6233        foreach ($values as $v) {
6234            $t = strtolower(trim((string) $v));
6235            if (in_array($t, ['yes', 'sí', 'si', '1', 'true'], true)) {
6236                $clauses[] = $yesSql;
6237            } else {
6238                $clauses[] = $noSql;
6239            }
6240        }
6241        $clauses = array_unique($clauses);
6242
6243        return $clauses ? ' AND ('.implode(' OR ', $clauses).')' : '';
6244    }
6245
6246    /**
6247     * Build the SQL fragment for an advanced-search text filter, dispatching on
6248     * the `operator` key. Falls back to the legacy `{ contains }` shape
6249     * (operator omitted) so previously saved filters keep working.
6250     * `blank` / `notBlank` need no value; `notContains` / `notEqual` also match
6251     * NULL rows (users expect "does not contain X" to include empty rows).
6252     */
6253    private function text_filter_clause(string $col, array $f): string
6254    {
6255        $op = (string) ($f['operator'] ?? 'contains');
6256
6257        if ($op === 'blank') {
6258            return " AND ({$col} IS NULL OR {$col} = '')";
6259        }
6260        if ($op === 'notBlank') {
6261            return " AND ({$col} IS NOT NULL AND {$col} <> '')";
6262        }
6263
6264        $val = trim((string) ($f['value'] ?? $f['contains'] ?? ''));
6265        if ($val === '') {
6266            return '';
6267        }
6268        $val = addslashes($val);
6269
6270        switch ($op) {
6271            case 'notContains':
6272                return " AND ({$col} NOT LIKE '%{$val}%' OR {$col} IS NULL)";
6273            case 'equals':
6274                return " AND {$col} = '{$val}'";
6275            case 'notEqual':
6276                return " AND ({$col} <> '{$val}' OR {$col} IS NULL)";
6277            case 'startsWith':
6278                return " AND {$col} LIKE '{$val}%'";
6279            case 'endsWith':
6280                return " AND {$col} LIKE '%{$val}'";
6281            case 'contains':
6282            default:
6283                return " AND {$col} LIKE '%{$val}%'";
6284        }
6285    }
6286
6287    public function get_dates(Request $request): ResponseFactory|HttpResponse
6288    {
6289
6290        try {
6291
6292            $data = $request->all();
6293            $companyId = addslashes((string) $data['company_id']);
6294
6295            $where = '';
6296            if ($companyId != 0) {
6297                $where = " AND a.company_id = {$companyId} ";
6298            } else {
6299                $where = " AND a.company_id IN ({$this->companyId})";
6300            }
6301
6302            $query = "SELECT
6303                        DATE_FORMAT(a.request_date, '%d/%m/%Y') request_date_translate,
6304                        DATE_FORMAT(a.issue_date, '%d/%m/%Y') issue_date_translate,
6305                        DATE_FORMAT(a.acceptance_date, '%d/%m/%Y') acceptance_date_translate,
6306                        DATE_FORMAT(a.last_follow_up_date, '%d/%m/%Y') last_follow_up_date_translate,
6307                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
6308                        DATE_FORMAT(a.accepted_at, '%d/%m/%Y') accepted_at_translate
6309                    FROM tbl_quotations a
6310                    WHERE a.for_add = 0 {$where}";
6311
6312            $result = DB::select($query);
6313
6314            return response([
6315                'message' => 'OK',
6316                'data' => $result,
6317            ]);
6318
6319        } catch (\Exception $e) {
6320            report(AppException::fromException($e, 'GET_DATES_EXCEPTION'));
6321
6322            return response(['message' => 'KO', 'error' => $e->getMessage()]);
6323        }
6324
6325    }
6326
6327    public function list_quotation_analytics_by_source(Request $request): ResponseFactory|HttpResponse
6328    {
6329
6330        try {
6331
6332            $data = $request->all();
6333            $companyId = addslashes((string) $data['company_id']);
6334
6335            $where = '';
6336            $whereYear = '';
6337
6338            $dateLflArray = [];
6339            $companyIds = $this->companyIds;
6340
6341            if ($companyId != 0) {
6342                $companyIds = [$companyId];
6343            }
6344
6345            $field = 'sent_date';
6346            $fq = 'COALESCE(q.sent_date, q.issue_date)';
6347            $fb = 'COALESCE(sent_date, issue_date)';
6348
6349            if (isset($data['years']) && $data['years'] != null) {
6350
6351                if (count($data['years']) > 0) {
6352                    foreach ($data['years'] as $year) {
6353                        if (isset($data['week']) && $data['week'] != null) {
6354                            $w = sprintf('%02d', $data['week']);
6355                            $whereYear .= " AND YEARWEEK(COALESCE(q.sent_date, q.issue_date), 1) = '{$year}{$w}'";
6356                        } else {
6357                            $whereYear .= " AND YEAR(COALESCE(q.sent_date, q.issue_date)) = {$year}";
6358                        }
6359                    }
6360                }
6361            }
6362
6363            foreach ($companyIds as $v) {
6364
6365                $lflWhere = " AND q.company_id = {$v} ";
6366
6367                $query = "SELECT
6368                            CONCAT(
6369                                DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb}),
6370                                ' - ',
6371                                DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb})
6372                            ) AS date_like,
6373                            YEAR({$fq}) 'year',
6374                            DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
6375                            DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
6376                            {$v} 'company_id'
6377                        FROM
6378                            tbl_quotations q
6379                        WHERE
6380                            {$fq} IS NOT NULL
6381                            AND q.for_add = 0
6382                            {$lflWhere}
6383                            {$whereYear}
6384                        GROUP BY YEAR({$fq})
6385                        ORDER BY YEAR({$fq}) DESC";
6386
6387                $dateLike = DB::select($query);
6388
6389                $dateLflArray[$v] = $dateLike;
6390            }
6391
6392            $whereAcceptanceDate = 'q.acceptance_date IS NOT NULL ';
6393
6394            $isFy = true;
6395
6396            if (isset($data['issue_year_ytd']) && $data['issue_year_ytd'] != null && $data['issue_year_ytd'] == true) {
6397                $isFy = false;
6398                $ytdArray = [];
6399                $ytdAcceptanceArray = [];
6400                $lflCompanyIds = [];
6401                $lflCompanyIdsAcc = [];
6402                foreach ($dateLflArray as $k => $v) {
6403                    if (empty($v)) {
6404                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
6405                    }
6406
6407                    foreach ($dateLflArray[$k] as $item) {
6408                        $year = $item->year;
6409                        $now = date('m-d');
6410                        array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}' AND YEAR(q.acceptance_date) = YEAR(COALESCE(sent_date, issue_date))");
6411                        array_push($ytdArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
6412                    }
6413
6414                    $ytdArray = implode(' OR ', $ytdArray);
6415                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
6416                    $ytdArray = [];
6417
6418                    $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
6419                    array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
6420                    $ytdAcceptanceArray = [];
6421                }
6422
6423                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
6424                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
6425
6426                $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
6427                $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
6428            }
6429
6430            if (isset($data['issue_year_lfl']) && $data['issue_year_lfl'] != null && $data['issue_year_lfl'] == true) {
6431                $isFy = false;
6432                $lflArray = [];
6433                $ytdAcceptanceArray = [];
6434                $lflCompanyIds = [];
6435                $lflCompanyIdsAcc = [];
6436                foreach ($dateLflArray as $k => $v) {
6437                    if (empty($v)) {
6438                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
6439                    }
6440
6441                    foreach ($dateLflArray[$k] as $item) {
6442                        $year = $item->year;
6443                        $min_date_like = $item->min_date_like;
6444                        $max_date_like = $item->max_date_like;
6445                        array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND YEAR(q.acceptance_date) = YEAR(COALESCE(sent_date, issue_date))");
6446                        array_push($lflArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
6447                    }
6448
6449                    $lflArray = implode(' OR ', $lflArray);
6450                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
6451                    $lflArray = [];
6452
6453                    $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
6454                    array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
6455                    $ytdAcceptanceArray = [];
6456                }
6457
6458                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
6459                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
6460
6461                $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
6462                $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
6463            }
6464
6465            if ($isFy) {
6466                if ($companyId != 0) {
6467                    $where .= " AND q.company_id = {$companyId} ";
6468                } else {
6469                    $where .= " AND q.company_id IN ({$this->companyId})";
6470                }
6471            }
6472
6473            if (isset($data['source']) && $data['source'] != null) {
6474                $where .= " AND s.name = '{$data['source']}'";
6475            }
6476
6477            if (isset($data['month']) && $data['month'] != null) {
6478                $where .= " AND MONTH(COALESCE(q.sent_date, q.issue_date)) = '{$data['month']}'";
6479            }
6480
6481            if (isset($data['commercial']) && $data['commercial'] != null) {
6482                $where .= " AND q.commercial = '{$data['commercial']}'";
6483            }
6484
6485            if (isset($data['created_by']) && $data['created_by'] != null) {
6486                $where .= " AND q.created_by = '{$data['created_by']}'";
6487            }
6488
6489            if (isset($data['budget_type']) && $data['budget_type'] != null) {
6490                $where .= " AND bt.budget_type_id = {$data['budget_type']}";
6491            }
6492
6493            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
6494                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
6495            }
6496
6497            if (isset($data['budget_status']) && $data['budget_status'] != null) {
6498                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
6499            }
6500
6501            if (isset($data['client_type']) && $data['client_type'] != null) {
6502                $where .= " AND ct.customer_type_id = {$data['client_type']}";
6503            }
6504
6505            if (isset($data['segment_id']) && $data['segment_id'] != null) {
6506                $where .= " AND q.segment_id = {$data['segment_id']}";
6507            }
6508
6509            $query = "SELECT
6510                        YEAR(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)) AS 'year',
6511                        LPAD(MONTH(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)), 2, 0) AS 'month',
6512                        LPAD(WEEK(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)), 2, 0) AS 'week',
6513                        DATE_FORMAT(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY), '%W, %M %e') issue_date,
6514                        COUNT(
6515                            CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6516                            THEN 1 END
6517                        ) AS totalIssue,
6518                        GROUP_CONCAT(
6519                            CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6520                            THEN q.id END
6521                        ) AS groupConcatIds,
6522                        SUM(
6523                            CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN q.amount END
6524                        ) AS revenueIssue,
6525                        COUNT(
6526                            CASE WHEN {$whereAcceptanceDate} AND bs.name = 'Aceptado' THEN 1 END
6527                        ) AS totalAcceptance,
6528                        SUM(
6529                            CASE WHEN {$whereAcceptanceDate} AND bs.name = 'Aceptado' THEN q.amount END
6530                        ) AS revenueAcceptance,
6531                        SUM(
6532                            CASE WHEN {$whereAcceptanceDate} AND bs.name = 'Aceptado' THEN q.amount END
6533                        ) / SUM(
6534                            CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN q.amount END
6535                        ) * 100 AS revenueAcceptanceIssuedPercentage,
6536                        COUNT(
6537                            CASE WHEN bs.name = 'Rechazado' THEN 1 END
6538                        ) AS totalRejected,
6539                        SUM(
6540                            CASE WHEN bs.name = 'Rechazado' THEN q.amount END
6541                        ) AS revenueRejected,
6542                        COUNT(
6543                            CASE WHEN bs.name = 'Rechazado - automaticamente' THEN 1 END
6544                        ) AS totalRejectedAutomatic,
6545                        SUM(
6546                            CASE WHEN bs.name = 'Rechazado - automaticamente' THEN q.amount END
6547                        ) AS revenueRejectedAutomatic
6548                    FROM
6549                        tbl_quotations q
6550                        LEFT JOIN tbl_sources s ON s.source_id = q.source_id
6551                        LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
6552                        LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
6553                        LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
6554                    WHERE
6555                        COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6556                        AND q.budget_type_id != 7
6557                        AND q.budget_type_id IS NOT NULL
6558                        AND q.for_add = 0
6559                        AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
6560                        {$where}
6561                        {$whereYear}
6562                    GROUP BY
6563                        YEAR(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)),
6564                        MONTH(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)),
6565                        WEEK(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)) WITH ROLLUP
6566                    ORDER BY
6567                        YEAR DESC,
6568                        MONTH ASC,
6569                        WEEK ASC,
6570                        DATE_FORMAT(COALESCE(q.sent_date, q.issue_date), '%e') ASC";
6571            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
6572            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
6573
6574            return response([
6575                'message' => 'OK',
6576                'data' => $result,
6577            ]);
6578
6579        } catch (\Exception $e) {
6580            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_BY_SOURCE_EXCEPTION'));
6581
6582            return response(['message' => 'KO', 'error' => $e->getMessage()]);
6583        }
6584    }
6585
6586    public function list_quotation_analytics_send_budgets(Request $request): ResponseFactory|HttpResponse
6587    {
6588
6589        try {
6590
6591            $data = $request->all();
6592            $companyId = addslashes((string) $data['company_id']);
6593
6594            $where = '';
6595            $whereYear = '';
6596
6597            if ($companyId != 0) {
6598                $where = " AND q.company_id = {$companyId} ";
6599            } else {
6600                $where = " AND q.company_id IN ({$this->companyId}) ";
6601            }
6602
6603            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
6604                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
6605            }
6606
6607            if (isset($data['budget_status']) && $data['budget_status'] != null) {
6608                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
6609            }
6610
6611            if (isset($data['years']) && $data['years'] != null) {
6612                $years = implode(',', $data['years']);
6613                if (count($data['years']) > 0) {
6614                    $whereYear = " AND YEAR(COALESCE(q.sent_date, q.issue_date)) IN ({$years})";
6615                }
6616            }
6617
6618            $query = "SELECT
6619                            YEAR(COALESCE(q.sent_date, q.issue_date)) AS 'year',
6620                            MONTH(COALESCE(q.sent_date, q.issue_date)) AS 'month',
6621                            SUM(
6622                                CASE WHEN MONTH(request_date) = MONTH(COALESCE(sent_date, issue_date)) THEN 1 ELSE 0 END
6623                            ) totalRequest,
6624                            COUNT(
6625                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN 1 END
6626                            ) AS totalIssue,
6627                            GROUP_CONCAT(
6628                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6629                                THEN q.id END
6630                            ) AS groupConcatIds,
6631                            SUM(
6632                                CASE WHEN MONTH(request_date) = MONTH(COALESCE(sent_date, issue_date)) THEN 1 ELSE 0 END
6633                            ) /
6634                            COUNT(
6635                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN 1 END
6636                            ) * 100 issuePercentage,
6637                            AVG(
6638                                COALESCE(q.duration, 0)
6639                            ) AS averageDurationIssue,
6640                            COALESCE(
6641                                AVG(
6642                                    CASE WHEN bt.name = 'Mantenimiento' THEN COALESCE(q.duration, 0) ELSE NULL END
6643                                ), 0
6644                            ) AS averageDurationMaintenance,
6645                            COALESCE(
6646                                AVG(
6647                                    CASE WHEN bt.name = 'Nuevos' THEN COALESCE(q.duration, 0) ELSE NULL END
6648                                ), 0
6649                            ) AS averageDurationNew,
6650                            COALESCE(
6651                                AVG(
6652                                    CASE WHEN bt.name = 'Correctivos' THEN COALESCE(q.duration, 0) ELSE NULL END
6653                                ), 0
6654                            ) AS averageDurationCorretive,
6655                            COALESCE(
6656                                AVG(
6657                                    CASE WHEN bt.name = 'Anomalías' THEN COALESCE(q.duration, 0) ELSE NULL END
6658                                ), 0
6659                            ) AS averageDurationAnomalies,
6660                            COALESCE(
6661                                AVG(
6662                                    CASE WHEN bt.name = 'Precios Unitarios' THEN COALESCE(q.duration, 0) ELSE NULL END
6663                                ), 0
6664                            ) AS averageDurationUnitPrice,
6665                            COALESCE(
6666                                AVG(
6667                                    CASE WHEN bt.name = 'Instalaciones' THEN COALESCE(q.duration, 0) ELSE NULL END
6668                                ), 0
6669                            ) AS averageDurationFacilities,
6670                            COALESCE(
6671                                AVG(
6672                                    CASE WHEN bt.name = 'Alquiler' THEN COALESCE(q.duration, 0) ELSE NULL END
6673                                ), 0
6674                            ) AS averageDurationRent,
6675                            COALESCE(
6676                                AVG(
6677                                    CASE WHEN bt.name = 'OCA visita' THEN COALESCE(q.duration, 0) ELSE NULL END
6678                                ), 0
6679                            ) AS averageDurationOCA,
6680                            COALESCE(
6681                                AVG(
6682                                    CASE WHEN bt.name = 'Retirada y gestion de residuos' THEN COALESCE(q.duration, 0) ELSE NULL END
6683                                ), 0
6684                            ) AS averageDurationWRM,
6685                            COALESCE(
6686                                AVG(
6687                                    CASE WHEN bt.name = 'Formación' THEN COALESCE(q.duration, 0) ELSE NULL END
6688                                ), 0
6689                            ) AS averageDurationTraining,
6690                            COALESCE(
6691                                AVG(
6692                                    CASE WHEN bt.name = 'Anomalías de facilities' THEN COALESCE(q.duration, 0) ELSE NULL END
6693                                ), 0
6694                            ) AS averageDurationFacilityAnomalies
6695                        FROM
6696                            tbl_quotations q
6697                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
6698                        WHERE
6699                            COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6700                            AND q.budget_type_id != 7
6701                            AND q.budget_type_id IS NOT NULL
6702                            AND q.for_add = 0
6703                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
6704                            {$where}
6705                            {$whereYear}
6706                        GROUP BY
6707                            YEAR(COALESCE(q.sent_date, q.issue_date)),
6708                            MONTH(COALESCE(q.sent_date, q.issue_date)) WITH ROLLUP
6709                        ORDER BY
6710                            YEAR(COALESCE(q.sent_date, q.issue_date)) DESC,
6711                            MONTH(COALESCE(q.sent_date, q.issue_date)) ASC";
6712
6713            $sendBudgets = [];
6714            $sendBudgetsTotals = [];
6715
6716            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
6717            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
6718
6719            if (count($result) > 0) {
6720                for ($i = 0; $i < count($result); $i++) {
6721
6722                    if ($result[$i]->year == null && $result[$i]->month == null) {
6723                        $result[$i]->month = 'totalGeneral';
6724                        $sendBudgetsTotals['totalGeneral'] = $result[$i];
6725
6726                        continue;
6727                    } elseif ($result[$i]->month == null && $result[$i]->year != null) {
6728                        if (count($data['years']) > 0 || $whereYear == '') {
6729                            $result[$i]->month = 'totalSub';
6730                        } else {
6731                            continue;
6732                        }
6733                    } else {
6734                        $result[$i]->month = sprintf('%02d', $result[$i]->month);
6735                    }
6736
6737                    $sendBudgets[$result[$i]->year][$result[$i]->month] = $result[$i];
6738                }
6739            }
6740
6741            return response([
6742                'message' => 'OK',
6743                'data' => $sendBudgets,
6744                'totals' => $sendBudgetsTotals,
6745            ]);
6746
6747        } catch (\Exception $e) {
6748            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_EXCEPTION'));
6749
6750            return response(['message' => 'KO', 'error' => $e->getMessage()]);
6751        }
6752    }
6753
6754    public function list_quotation_analytics_track_budgets(Request $request): ResponseFactory|HttpResponse
6755    {
6756
6757        try {
6758
6759            $data = $request->all();
6760            $companyId = addslashes((string) $data['company_id']);
6761
6762            $where = '';
6763            $whereYear = '';
6764            $isBetween = false;
6765
6766            $dateLflArray = [];
6767            $companyIds = $this->companyIds;
6768
6769            if ($companyId != 0) {
6770                $companyIds = [$companyId];
6771            }
6772
6773            if (isset($data['years']) && $data['years'] != null) {
6774                $years = implode(',', $data['years']);
6775                if (count($data['years']) > 0) {
6776                    $whereYear = " AND YEAR(COALESCE(q.sent_date, q.issue_date)) IN ({$years})";
6777                }
6778            }
6779
6780            $field = 'sent_date';
6781            $fq = 'COALESCE(q.sent_date, q.issue_date)';
6782            $fb = 'COALESCE(sent_date, issue_date)';
6783
6784            foreach ($companyIds as $v) {
6785
6786                $lflWhere = " AND q.company_id = {$v} ";
6787
6788                $query = "SELECT
6789                            CONCAT(
6790                                DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb}),
6791                                ' - ',
6792                                DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb})
6793                            ) AS date_like,
6794                            YEAR({$fq}) 'year',
6795                            DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
6796                            DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
6797                            {$v} 'company_id'
6798                        FROM
6799                            tbl_quotations q
6800                        WHERE
6801                            {$fq} IS NOT NULL
6802                            AND q.for_add = 0
6803                            {$lflWhere}
6804                            {$whereYear}
6805                        GROUP BY YEAR({$fq})
6806                        ORDER BY YEAR({$fq}) DESC";
6807
6808                $dateLike = DB::select($query);
6809
6810                $dateLflArray[$v] = $dateLike;
6811            }
6812
6813            $whereAcceptanceDate = 'q.acceptance_date IS NOT NULL ';
6814
6815            $isFy = true;
6816
6817            if (isset($data['issue_year_ytd']) && $data['issue_year_ytd'] != null && $data['issue_year_ytd'] == true) {
6818                $isFy = false;
6819                $ytdArray = [];
6820                $ytdAcceptanceArray = [];
6821                $lflCompanyIds = [];
6822                $lflCompanyIdsAcc = [];
6823                foreach ($dateLflArray as $k => $v) {
6824                    if (empty($v)) {
6825                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
6826                    }
6827
6828                    foreach ($dateLflArray[$k] as $item) {
6829                        $year = $item->year;
6830                        $now = date('m-d');
6831                        array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}' AND YEAR(q.acceptance_date) = YEAR(COALESCE(sent_date, issue_date))");
6832                        array_push($ytdArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
6833                    }
6834
6835                    $ytdArray = implode(' OR ', $ytdArray);
6836                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
6837                    $ytdArray = [];
6838
6839                    $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
6840                    array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
6841                    $ytdAcceptanceArray = [];
6842                }
6843
6844                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
6845                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
6846
6847                $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
6848                $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
6849            }
6850
6851            if (isset($data['issue_year_lfl']) && $data['issue_year_lfl'] != null && $data['issue_year_lfl'] == true) {
6852                $isFy = false;
6853                $lflArray = [];
6854                $ytdAcceptanceArray = [];
6855                $lflCompanyIds = [];
6856                $lflCompanyIdsAcc = [];
6857                foreach ($dateLflArray as $k => $v) {
6858                    if (empty($v)) {
6859                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
6860                    }
6861
6862                    foreach ($dateLflArray[$k] as $item) {
6863                        $year = $item->year;
6864                        $min_date_like = $item->min_date_like;
6865                        $max_date_like = $item->max_date_like;
6866                        array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND YEAR(q.acceptance_date) = YEAR(COALESCE(sent_date, issue_date))");
6867                        array_push($lflArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
6868                    }
6869
6870                    $lflArray = implode(' OR ', $lflArray);
6871                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
6872                    $lflArray = [];
6873
6874                    $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
6875                    array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
6876                    $ytdAcceptanceArray = [];
6877                }
6878
6879                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
6880                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
6881
6882                $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
6883                $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
6884            }
6885
6886            if ($isFy) {
6887                if ($companyId != 0) {
6888                    $where .= " AND q.company_id = {$companyId} ";
6889                } else {
6890                    $where .= " AND q.company_id IN ({$this->companyId})";
6891                }
6892            }
6893
6894            if (isset($data['source']) && $data['source'] != null) {
6895                $where .= " AND s.name = '{$data['source']}'";
6896            }
6897
6898            if (isset($data['commercial']) && $data['commercial'] != null) {
6899                $where .= " AND q.commercial = '{$data['commercial']}'";
6900            }
6901
6902            if (isset($data['created_by']) && $data['created_by'] != null) {
6903                $where .= " AND q.created_by = '{$data['created_by']}'";
6904            }
6905
6906            if (isset($data['budget_type']) && $data['budget_type'] != null) {
6907                $where .= " AND bt.budget_type_id = {$data['budget_type']}";
6908            }
6909
6910            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
6911                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
6912            }
6913
6914            if (isset($data['budget_status']) && $data['budget_status'] != null) {
6915                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
6916            }
6917
6918            if (isset($data['client_type']) && $data['client_type'] != null) {
6919                $where .= " AND ct.customer_type_id = {$data['client_type']}";
6920            }
6921
6922            if (isset($data['segment_id']) && $data['segment_id'] != null) {
6923                $where .= " AND q.segment_id = {$data['segment_id']}";
6924            }
6925
6926            $query = "SELECT
6927                            YEAR(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)) AS 'year',
6928                            LPAD(MONTH(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)), 2, 0) AS 'month',
6929                            LPAD(WEEK(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)), 2, 0) AS 'week',
6930                            DATE_FORMAT(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY), '%W, %M %e') issue_date,
6931                            COUNT(
6932                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6933                                THEN 1 END
6934                            ) AS totalIssue,
6935                            GROUP_CONCAT(
6936                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6937                                THEN q.id END
6938                            ) AS groupConcatIds,
6939                            COUNT(
6940                                CASE WHEN {$whereAcceptanceDate}
6941                                AND bs.name = 'Aceptado' THEN 1 END) totalAccept,
6942                            COUNT(
6943                                CASE WHEN q.acceptance_date IS NOT NULL
6944                                AND {$whereAcceptanceDate}
6945                                AND bs.name = 'Aceptado'
6946                                AND DATEDIFF(q.acceptance_date, q.issue_date) <= 10 THEN 1 END
6947                            ) / COUNT(
6948                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6949                                THEN 1 END
6950                            ) * 100 AS percentageOfacceptanceLessThan10,
6951                            COUNT(
6952                                CASE WHEN q.acceptance_date IS NOT NULL
6953                                AND {$whereAcceptanceDate}
6954                                AND bs.name = 'Aceptado'
6955                                AND DATEDIFF(q.acceptance_date, q.issue_date) > 10
6956                                AND DATEDIFF(q.acceptance_date, q.issue_date) < 30 THEN 1 END
6957                            ) / COUNT(
6958                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6959                                THEN 1 END
6960                            ) * 100 AS percentageOfacceptanceLessThan30,
6961                            COUNT(
6962                                CASE WHEN q.acceptance_date IS NOT NULL
6963                                AND {$whereAcceptanceDate}
6964                                AND bs.name = 'Aceptado'
6965                                AND DATEDIFF(q.acceptance_date, q.issue_date) >= 30 THEN 1 END
6966                            ) / COUNT(
6967                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6968                                THEN 1 END
6969                            ) * 100 AS percentageOfacceptanceMoreThan30,
6970                            COUNT(CASE WHEN
6971                                {$whereAcceptanceDate} THEN 1 END
6972                            ) / COUNT(
6973                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
6974                                THEN 1 END
6975                            ) * 100 acceptedPercentage,
6976                            COALESCE(
6977                                AVG(
6978                                    CASE WHEN q.issue_date IS NOT NULL
6979                                    AND q.acceptance_date IS NOT NULL
6980                                    AND {$whereAcceptanceDate}
6981                                    AND bs.name = 'Aceptado'
6982                                    THEN DATEDIFF(q.acceptance_date, q.issue_date) ELSE NULL END
6983                                ), 0
6984                            )
6985                            AS averageAcceptedDuration,
6986                            COALESCE(
6987                                AVG(
6988                                    CASE WHEN q.issue_date IS NOT NULL
6989                                    AND q.request_date IS NOT NULL
6990                                    THEN DATEDIFF(q.issue_date, q.request_date) ELSE NULL END
6991                                ), 0
6992                            )
6993                            AS averageRequestedDays
6994                        FROM
6995                            tbl_quotations q
6996                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
6997                            LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
6998                            LEFT JOIN tbl_sources s ON s.source_id = q.source_id
6999                            LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
7000                        WHERE
7001                            COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7002                            AND q.budget_type_id != 7
7003                            AND q.budget_type_id IS NOT NULL
7004                            AND q.for_add = 0
7005                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
7006                            {$where}
7007                            {$whereYear}
7008                        GROUP BY
7009                            YEAR(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)),
7010                            MONTH(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)),
7011                            WEEK(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY)) WITH ROLLUP
7012                        ORDER BY
7013                            YEAR DESC,
7014                            MONTH ASC,
7015                            WEEK ASC,
7016                            DATE_FORMAT(COALESCE(q.sent_date, q.issue_date), '%e') ASC";
7017
7018            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
7019            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
7020
7021            return response([
7022                'message' => 'OK',
7023                'data' => $result,
7024            ]);
7025
7026        } catch (\Exception $e) {
7027            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_TRACK_BUDGETS_EXCEPTION'));
7028
7029            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7030        }
7031    }
7032
7033    public function list_quotation_analytics_types_budgets(Request $request): ResponseFactory|HttpResponse
7034    {
7035
7036        try {
7037
7038            $data = $request->all();
7039            $companyId = addslashes((string) $data['company_id']);
7040
7041            $where = '';
7042            $whereYear = '';
7043            $isBetween = false;
7044
7045            $dateLflArray = [];
7046            $companyIds = $this->companyIds;
7047
7048            if ($companyId != 0) {
7049                $companyIds = [$companyId];
7050            }
7051
7052            if (isset($data['years']) && $data['years'] != null) {
7053                $years = implode(',', $data['years']);
7054                if (count($data['years']) > 0) {
7055                    $whereYear = " AND YEAR(COALESCE(q.sent_date, q.issue_date)) IN ({$years})";
7056                }
7057            }
7058
7059            $field = 'sent_date';
7060            $fq = 'COALESCE(q.sent_date, q.issue_date)';
7061            $fb = 'COALESCE(sent_date, issue_date)';
7062
7063            foreach ($companyIds as $v) {
7064
7065                $lflWhere = " AND q.company_id = {$v} ";
7066
7067                $query = "SELECT
7068                            CONCAT(
7069                                DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb}),
7070                                ' - ',
7071                                DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb})
7072                            ) AS date_like,
7073                            YEAR({$fq}) 'year',
7074                            DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
7075                            DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
7076                            {$v} 'company_id'
7077                        FROM
7078                            tbl_quotations q
7079                        WHERE
7080                            {$fq} IS NOT NULL
7081                            AND q.for_add = 0
7082                            {$lflWhere}
7083                            {$whereYear}
7084                        GROUP BY YEAR({$fq})
7085                        ORDER BY YEAR({$fq}) DESC";
7086
7087                $dateLike = DB::select($query);
7088
7089                $dateLflArray[$v] = $dateLike;
7090            }
7091
7092            $whereAcceptanceDate = 'q.acceptance_date IS NOT NULL ';
7093
7094            $isFy = true;
7095
7096            if (isset($data['issue_year_ytd']) && $data['issue_year_ytd'] != null && $data['issue_year_ytd'] == true) {
7097                $isFy = false;
7098                $ytdArray = [];
7099                $ytdAcceptanceArray = [];
7100                $lflCompanyIds = [];
7101                $lflCompanyIdsAcc = [];
7102                foreach ($dateLflArray as $k => $v) {
7103                    if (empty($v)) {
7104                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
7105                    }
7106
7107                    foreach ($dateLflArray[$k] as $item) {
7108                        $year = $item->year;
7109                        $now = date('m-d');
7110                        array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}' AND YEAR(q.acceptance_date) = YEAR(COALESCE(sent_date, issue_date))");
7111                        array_push($ytdArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
7112                    }
7113
7114                    $ytdArray = implode(' OR ', $ytdArray);
7115                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
7116                    $ytdArray = [];
7117
7118                    $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
7119                    array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
7120                    $ytdAcceptanceArray = [];
7121                }
7122
7123                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
7124                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
7125
7126                $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
7127                $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
7128            }
7129
7130            if (isset($data['issue_year_lfl']) && $data['issue_year_lfl'] != null && $data['issue_year_lfl'] == true) {
7131                $isFy = false;
7132                $lflArray = [];
7133                $ytdAcceptanceArray = [];
7134                $lflCompanyIds = [];
7135                $lflCompanyIdsAcc = [];
7136                foreach ($dateLflArray as $k => $v) {
7137                    if (empty($v)) {
7138                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
7139                    }
7140
7141                    foreach ($dateLflArray[$k] as $item) {
7142                        $year = $item->year;
7143                        $min_date_like = $item->min_date_like;
7144                        $max_date_like = $item->max_date_like;
7145                        array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND YEAR(q.acceptance_date) = YEAR(COALESCE(sent_date, issue_date))");
7146                        array_push($lflArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
7147                    }
7148
7149                    $lflArray = implode(' OR ', $lflArray);
7150                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
7151                    $lflArray = [];
7152
7153                    $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
7154                    array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
7155                    $ytdAcceptanceArray = [];
7156                }
7157
7158                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
7159                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
7160
7161                $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
7162                $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
7163            }
7164
7165            if ($isFy) {
7166                if ($companyId != 0) {
7167                    $where .= " AND q.company_id = {$companyId} ";
7168                } else {
7169                    $where .= " AND q.company_id IN ({$this->companyId})";
7170                }
7171            }
7172
7173            if (isset($data['budget_status']) && $data['budget_status'] != null) {
7174                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
7175            }
7176
7177            if (isset($data['segment_id']) && $data['segment_id'] != null) {
7178                $where .= " AND q.segment_id = {$data['segment_id']}";
7179            }
7180
7181            $query = "SELECT
7182                            YEAR(COALESCE(q.sent_date, q.issue_date)) AS 'year',
7183                            bt.name,
7184                            COUNT(
7185                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7186                                THEN 1 END
7187                            ) AS totalIssue,
7188                            GROUP_CONCAT(
7189                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7190                                THEN q.id END
7191                            ) AS groupConcatIds,
7192                            COUNT(CASE WHEN {$whereAcceptanceDate} AND bs.name = 'Aceptado' THEN 1 END) totalAccept,
7193                            COUNT(
7194                                CASE WHEN q.acceptance_date IS NOT NULL
7195                                AND {$whereAcceptanceDate}
7196                                AND bs.name = 'Aceptado'
7197                                AND DATEDIFF(q.acceptance_date, q.issue_date) < 10 THEN 1 END
7198                            ) / COUNT(
7199                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7200                                THEN 1 END
7201                            ) * 100 AS percentageOfacceptanceLessThan10,
7202                            COUNT(
7203                                CASE WHEN q.acceptance_date IS NOT NULL
7204                                AND {$whereAcceptanceDate}
7205                                AND bs.name = 'Aceptado'
7206                                AND DATEDIFF(q.acceptance_date, q.issue_date) > 10
7207                                AND DATEDIFF(q.acceptance_date, q.issue_date) < 30 THEN 1 END
7208                            ) / COUNT(
7209                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7210                                THEN 1 END
7211                            ) * 100 AS percentageOfacceptanceLessThan30,
7212                            COUNT(
7213                                CASE WHEN q.acceptance_date IS NOT NULL
7214                                AND {$whereAcceptanceDate}
7215                                AND bs.name = 'Aceptado'
7216                                AND DATEDIFF(q.acceptance_date, q.issue_date) > 30 THEN 1 END
7217                            ) / COUNT(
7218                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7219                                THEN 1 END
7220                            ) * 100 AS percentageOfacceptanceMoreThan30,
7221                            COUNT(CASE WHEN {$whereAcceptanceDate} THEN 1 END) / COUNT(
7222                                CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7223                                THEN 1 END
7224                            ) * 100 acceptedPercentage,
7225                            COALESCE(
7226                                AVG(
7227                                    CASE WHEN q.issue_date IS NOT NULL
7228                                    AND q.acceptance_date IS NOT NULL
7229                                    AND {$whereAcceptanceDate}
7230                                    AND bs.name = 'Aceptado'
7231                                    THEN DATEDIFF(q.acceptance_date, q.issue_date) ELSE NULL END
7232                                ), 0
7233                            )
7234                            AS averageAcceptedDuration,
7235                            COALESCE(
7236                                AVG(
7237                                    CASE WHEN q.issue_date IS NOT NULL
7238                                    AND q.request_date IS NOT NULL
7239                                    AND q.issue_date > q.request_date
7240                                    THEN DATEDIFF(q.issue_date, q.request_date) ELSE NULL END
7241                                ), 0
7242                            )
7243                            AS averageRequestedDays
7244                        FROM
7245                            tbl_quotations q
7246                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
7247                            LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
7248                        WHERE
7249                            COALESCE(q.sent_date, q.issue_date) IS NOT NULL
7250                            AND q.budget_type_id != 7
7251                            AND q.budget_type_id IS NOT NULL
7252                            AND q.for_add = 0
7253                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
7254                            {$where}
7255                            {$whereYear}
7256                        GROUP BY
7257                            YEAR(COALESCE(q.sent_date, q.issue_date)),
7258                            bt.name WITH ROLLUP";
7259
7260            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
7261            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
7262
7263            $typesBudgets = [];
7264            $typesBudgetsTotals = [];
7265
7266            if (count($result) > 0) {
7267                for ($i = 0; $i < count($result); $i++) {
7268
7269                    if ($result[$i]->year == null && $result[$i]->name == null) {
7270                        $result[$i]->name = 'totalGeneral';
7271                        $typesBudgetsTotals['totalGeneral'] = $result[$i];
7272
7273                        continue;
7274                    } elseif ($result[$i]->name == null && $result[$i]->year != null) {
7275                        if (count($data['years']) > 0 || $whereYear == '') {
7276                            $result[$i]->name = 'totalSub';
7277                        } else {
7278                            continue;
7279                        }
7280                    }
7281
7282                    $typesBudgets[$result[$i]->year][$result[$i]->name] = $result[$i];
7283                }
7284            }
7285
7286            return response([
7287                'message' => 'OK',
7288                'data' => $typesBudgets,
7289                'totals' => $typesBudgetsTotals,
7290            ]);
7291
7292        } catch (\Exception $e) {
7293            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_TYPES_BUDGETS_EXCEPTION'));
7294
7295            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7296        }
7297    }
7298
7299    public function download_quotations(Request $request): ResponseFactory|HttpResponse
7300    {
7301        // FIRE-1259: pre-fix this method forged a single Request with
7302        // end=999999999 and called list_orders_table once. list_orders_table
7303        // has an unconditional `min($limit, 1000)` clamp at line 3765 (the
7304        // safety cap that bounds the infinite-scroll table's page size); the
7305        // clamp also collapsed the download's "give me all rows" intent to
7306        // exactly 1.000 rows, silently. Operators downloaded incomplete Excels
7307        // for any filter that matched >1k quotations.
7308        //
7309        // Mirroring the FIRE-1149 chunked pattern in OngoingJobs::download_ongoing_jobs,
7310        // we now page through list_orders_table 500 rows at a time and
7311        // concatenate. The clamp itself is left in place (still protects the
7312        // table-view path against forged `end` values); the download just
7313        // stays under it and iterates until the last page is short.
7314        ini_set('max_execution_time', 123456);
7315        $data = $request->all();
7316        $userId = addslashes((string) $data['user_id']);
7317
7318        // Kept from the pre-fix shape — some downstream code or audit relies
7319        // on this role lookup running. Behaviour is unchanged.
7320        $query = "SELECT
7321                b.name
7322            FROM tbl_users a
7323            LEFT JOIN tbl_roles b
7324                ON a.role_id = b.role_id
7325            WHERE a.id = {$userId}";
7326        $role = DB::select($query);
7327
7328        $pageSize = 500;
7329        $start = 0;
7330        $allRows = [];
7331
7332        do {
7333            $r = new Request([
7334                'filterModel' => $data['filterModel'] ?? [],
7335                'sortModel' => $data['sortModel'] ?? [],
7336                'start' => $start,
7337                'end' => $start + $pageSize,
7338                'company_id' => $data['company_id'],
7339                'user_id' => $data['user_id'],
7340                'ids' => $data['ids'],
7341                'searchText' => $data['searchText'] ?? '',
7342                'ids_not_in' => $data['ids_not_in'],
7343            ]);
7344
7345            $page = $this->list_orders_table($r)->original['data'] ?? [];
7346            $pageCount = count($page);
7347
7348            if ($pageCount > 0) {
7349                $allRows = array_merge($allRows, $page);
7350            }
7351
7352            $start += $pageSize;
7353        } while ($pageCount === $pageSize);
7354
7355        return response(['data' => $allRows]);
7356    }
7357
7358    public function download_quotations_csv($filename, $data) {}
7359
7360    public function bulk_upload(Request $request): ResponseFactory|HttpResponse
7361    {
7362
7363        try {
7364
7365            $data = $request->all();
7366            $file = $request->file('file');
7367            $exte = 'Xlsx';
7368            $companyId = $data['company_id'];
7369
7370            if ($file->getMimeType() == 'application/vnd.ms-excel') {
7371                $exte = 'Xls';
7372            }
7373
7374            $destination_path = config('app.bulk_upload_file_destination');
7375            $filename = $file->getClientOriginalName();
7376
7377            if (file_exists($destination_path.$filename)) {
7378                $filename = pathinfo($filename, PATHINFO_FILENAME).'-'.uniqid().'.'.pathinfo($filename, PATHINFO_EXTENSION);
7379            }
7380
7381            $file->move($destination_path, $filename);
7382
7383            TblBulkUpload::create(
7384                [
7385                    'company_id' => $companyId,
7386                    'filename' => $filename,
7387                    'status' => 'Uploading...',
7388                    'is_running' => 1,
7389                    'uploaded_by' => $data['created_by'],
7390                ]
7391            );
7392
7393            $command = "php BulkUploadQuotations.php '{$data['created_by']}' '{$exte}' '{$destination_path}' '{$filename}' {$companyId}";
7394            exec($command.' > /dev/null &');
7395
7396            $query = '';
7397            $isRunning = 0;
7398
7399            if ($companyId == 0) {
7400                $query = 'SELECT * FROM tbl_bulk_upload ORDER BY started_at DESC';
7401                $isRunning = TblBulkUpload::where('is_running', 1)->count();
7402            } else {
7403                $query = "SELECT * FROM tbl_bulk_upload WHERE company_id = {$companyId} ORDER BY started_at DESC";
7404                $isRunning = TblBulkUpload::where('is_running', 1)->where('company_id', $companyId)->count();
7405            }
7406
7407            $result = DB::select($query);
7408
7409            return response(['message' => 'OK', 'data' => $result, 'is_running' => $isRunning]);
7410
7411        } catch (\Exception $e) {
7412            report(AppException::fromException($e, 'BULK_UPLOAD_QUOTATIONS_EXCEPTION'));
7413
7414            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7415        }
7416    }
7417
7418    public function list_bulk_upload($companyId): ResponseFactory|HttpResponse
7419    {
7420
7421        try {
7422
7423            $companyId = addslashes((string) $companyId);
7424            $query = '';
7425            $isRunning = 0;
7426
7427            if ($companyId == 0) {
7428                $query = 'SELECT * FROM tbl_bulk_upload ORDER BY started_at DESC';
7429                $isRunning = TblBulkUpload::where('is_running', 1)->count();
7430            } else {
7431                $query = "SELECT * FROM tbl_bulk_upload WHERE company_id = {$companyId} ORDER BY started_at DESC";
7432                $isRunning = TblBulkUpload::where('is_running', 1)->where('company_id', $companyId)->count();
7433            }
7434
7435            $result = DB::select($query);
7436
7437            return response(['message' => 'OK', 'data' => $result, 'is_running' => $isRunning]);
7438
7439        } catch (\Exception $e) {
7440            report(AppException::fromException($e, 'LIST_BULK_UPLOAD_EXCEPTION'));
7441
7442            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7443        }
7444
7445    }
7446
7447    public function delete_number(Request $request, $id): ResponseFactory|HttpResponse
7448    {
7449
7450        try {
7451
7452            $id = addslashes((string) $id);
7453            $data = $request->all();
7454
7455            $r = TblQuotations::where('id', $id)->first();
7456            $updatedAt = date('Y-m-d H:i:s');
7457            $query = "INSERT INTO tbl_quotations_deleted (id, quote_id, company_id, for_add, created_by, updated_by, updated_at)
7458                        SELECT id, quote_id, company_id, 1, created_by, '{$data['updated_by']}', '{$updatedAt}' FROM tbl_quotations WHERE id = {$id}";
7459
7460            DB::select($query);
7461
7462            TblQuotations::where('id', $id)->delete();
7463
7464            $latestBudget = TblQuotations::where('company_id', $r->company_id)->orderByRaw('id DESC')->value('quote_id');
7465
7466            $query = "UPDATE tbl_companies SET last_id = '{$latestBudget}' WHERE company_id = {$r->company_id}";
7467            DB::select($query);
7468
7469            return response(['message' => 'OK']);
7470
7471        } catch (\Exception $e) {
7472            report(AppException::fromException($e, 'DELETE_QUOTATION_EXCEPTION'));
7473
7474            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7475        }
7476
7477    }
7478
7479    public function get_number(Request $request, $companyId, $n = null): ResponseFactory|HttpResponse
7480    {
7481
7482        try {
7483
7484            $companyId = addslashes((string) $companyId);
7485            $data = $request->all();
7486            $latestBudget = [];
7487            $number = 0;
7488            $beforeLastId = null;
7489
7490            $x = true;
7491
7492            if ($companyId == 0) {
7493                $latestBudget = TblQuotations::orderByRaw('CAST(quote_id AS DOUBLE) DESC')->value('quote_id');
7494            } else {
7495                $latestBudget = TblCompanies::where('company_id', $companyId)->value('last_id');
7496
7497                if ($latestBudget == null) {
7498                    $latestBudget = TblQuotations::where('company_id', $companyId)->orderByRaw('id DESC')->value('quote_id');
7499                    $beforeLastId = $latestBudget;
7500                }
7501            }
7502
7503            $number = $latestBudget;
7504
7505            while ($x) {
7506
7507                if (is_numeric(substr((string) $number, -1))) {
7508                    $number++;
7509                } else {
7510                    $number .= '1';
7511                }
7512
7513                $check = 0;
7514
7515                if ($companyId == 0) {
7516                    $check = TblQuotations::where('quote_id', (string) $number)->count();
7517                } else {
7518                    $check = TblQuotations::where('company_id', $companyId)->where('quote_id', (string) $number)->count();
7519                }
7520
7521                if ($check == 0) {
7522                    $x = false;
7523                }
7524            }
7525
7526            $result = null;
7527
7528            if ($n == null) {
7529                $result = TblQuotations::create(['quote_id' => $number, 'company_id' => $companyId, 'for_add' => 1, 'created_by' => $data['created_by']]);
7530            }
7531
7532            if ($beforeLastId == null) {
7533                $beforeLastId = $number;
7534            }
7535
7536            $query = "UPDATE tbl_companies SET last_id = '{$number}', before_last_id = CASE WHEN before_last_id IS NULL THEN '{$beforeLastId}' ELSE before_last_id END WHERE company_id = {$companyId}";
7537            DB::select($query);
7538
7539            return response([
7540                'message' => 'OK',
7541                'number' => $number,
7542                'id' => ($result != null) ? $result->id : null,
7543            ]);
7544
7545        } catch (\Exception $e) {
7546            report(AppException::fromException($e, 'GET_NUMBER_EXCEPTION'));
7547
7548            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7549        }
7550
7551    }
7552
7553    public function get_years(Request $request): ResponseFactory|HttpResponse
7554    {
7555
7556        try {
7557
7558            $data = $request->all();
7559            $companyId = addslashes((string) $data['company_id']);
7560            $where = '';
7561
7562            if ($companyId != 0) {
7563                $where = " AND company_id = {$companyId} ";
7564            } else {
7565                $where = " AND company_id IN ({$this->companyId}) ";
7566            }
7567
7568            $query = "SELECT
7569                        CONCAT(
7570                            DATE_FORMAT((SELECT MIN(COALESCE(sent_date, issue_date)) FROM tbl_quotations WHERE COALESCE(sent_date, issue_date) IS NOT NULL {$where}), '%c/%e/'), YEAR(COALESCE(sent_date, issue_date)),
7571                            ' - ',
7572                            DATE_FORMAT((SELECT MAX(COALESCE(sent_date, issue_date)) FROM tbl_quotations WHERE COALESCE(sent_date, issue_date) IS NOT NULL {$where}), '%c/%e/'), YEAR(COALESCE(sent_date, issue_date))
7573                        ) AS date_like,
7574                        YEAR(COALESCE(sent_date, issue_date)) 'year'
7575                        FROM tbl_quotations
7576                        WHERE COALESCE(sent_date, issue_date) IS NOT NULL {$where}
7577                        GROUP BY YEAR(COALESCE(sent_date, issue_date))
7578                        ORDER BY YEAR(COALESCE(sent_date, issue_date)) DESC";
7579
7580            $issueDate = DB::select($query);
7581
7582            $query = "SELECT
7583                        CONCAT(
7584                            DATE_FORMAT((SELECT MIN(created_at) FROM tbl_quotations WHERE created_at IS NOT NULL {$where}), '%c/%e/'), YEAR(created_at),
7585                            ' - ',
7586                            DATE_FORMAT((SELECT MAX(created_at) FROM tbl_quotations WHERE created_at IS NOT NULL {$where}), '%c/%e/'), YEAR(created_at)
7587                        ) AS date_like,
7588                        YEAR(created_at) 'year'
7589                        FROM tbl_quotations
7590                        WHERE created_at IS NOT NULL {$where}
7591                        GROUP BY YEAR(created_at)
7592                        ORDER BY YEAR(created_at) DESC";
7593
7594            $createdAt = DB::select($query);
7595
7596            $query = "SELECT
7597                        CONCAT(
7598                            DATE_FORMAT((SELECT MIN(acceptance_date) FROM tbl_quotations WHERE acceptance_date IS NOT NULL {$where}), '%c/%e/'), YEAR(acceptance_date),
7599                            ' - ',
7600                            DATE_FORMAT((SELECT MAX(acceptance_date) FROM tbl_quotations WHERE acceptance_date IS NOT NULL {$where}), '%c/%e/'), YEAR(acceptance_date)
7601                        ) AS date_like,
7602                        YEAR(acceptance_date) 'year'
7603                        FROM tbl_quotations
7604                        WHERE acceptance_date IS NOT NULL {$where}
7605                        GROUP BY YEAR(acceptance_date)
7606                        ORDER BY YEAR(acceptance_date) DESC";
7607
7608            $acceptanceDate = DB::select($query);
7609
7610            return response([
7611                'message' => 'OK',
7612                'data' => $issueDate,
7613                'created_at' => $createdAt,
7614                'acceptance_date' => $acceptanceDate,
7615            ]);
7616
7617        } catch (\Exception $e) {
7618            report(AppException::fromException($e, 'GET_YEARS_EXCEPTION'));
7619
7620            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7621        }
7622
7623    }
7624
7625    public function human_filesize($bytes, $decimals = 2): string
7626    {
7627        $size = ['B', 'KB', 'MB'];
7628
7629        $factor = floor((strlen($bytes) - 1) / 3);
7630
7631        return number_format($bytes / 1024 ** $factor, 2, ',', '.').$size[$factor];
7632    }
7633
7634    public function get_files($quoteId): ResponseFactory|HttpResponse
7635    {
7636
7637        try {
7638
7639            // Titan → Zeus bridge (read) — see get_quotation above.
7640            $zeus = app(ZeusBridge::class);
7641            $forward = $zeus->getFiles(request(), $quoteId);
7642
7643            if ($zeus->shouldReturnZeusResponse($forward)) {
7644                return $forward->toTitanResponse();
7645            }
7646
7647            $quoteId = addslashes((string) $quoteId);
7648
7649            $quoteId = (int) $quoteId;
7650            $query = '
7651            SELECT
7652                file_id,
7653                quotation_id,
7654                quote_id,
7655                original_name,
7656                filename,
7657                uploaded_by,
7658                uploaded_at,
7659                is_internal,
7660                is_coverage_contract,
7661                is_signed,
7662                parent_file_id,
7663                file_size,
7664                file_hash,
7665                mime_type
7666            FROM tbl_files
7667            WHERE quotation_id = ?
7668            AND is_internal IS NULL';
7669
7670            $result = DB::select($query, [$quoteId]);
7671
7672            foreach ($result as $file) {
7673                if ($file->file_size > 0) {
7674                    $file->filesize = $this->human_filesize($file->file_size);
7675                } else {
7676                    $path = 'uploads/'.$file->filename;
7677
7678                    if (Storage::disk('s3')->exists($path)) {
7679                        $fileSizeBytes = Storage::disk('s3')->size($path);
7680                    } else {
7681                        $fileSizeBytes = 0;
7682                    }
7683
7684                    $file->filesize = $this->human_filesize($fileSizeBytes);
7685                }
7686
7687                $file->original_name = $file->original_name." ({$file->filesize})";
7688            }
7689
7690            $query = '
7691            SELECT
7692                file_id,
7693                quotation_id,
7694                quote_id,
7695                original_name,
7696                filename,
7697                uploaded_by,
7698                uploaded_at,
7699                is_internal,
7700                is_coverage_contract,
7701                is_signed,
7702                parent_file_id,
7703                file_size,
7704                file_hash,
7705                mime_type
7706            FROM tbl_files
7707            WHERE quotation_id = ?
7708            AND is_internal = 1';
7709
7710            $internal = DB::select($query, [$quoteId]);
7711
7712            foreach ($internal as $file) {
7713                if ($file->file_size > 0) {
7714                    $file->filesize = $this->human_filesize($file->file_size);
7715                } else {
7716                    $path = 'uploads/'.$file->filename;
7717
7718                    if (Storage::disk('s3')->exists($path)) {
7719                        $fileSizeBytes = Storage::disk('s3')->size($path);
7720                    } else {
7721                        $fileSizeBytes = 0;
7722                    }
7723
7724                    $file->filesize = $this->human_filesize($fileSizeBytes);
7725                }
7726
7727                $file->original_name = $file->original_name." ({$file->filesize})";
7728            }
7729
7730            $job = TblOngoingJobs::where('quotation_id', $quoteId)->first();
7731            $order = TblQuotations::where('id', $quoteId)->first();
7732
7733            $z = 0;
7734            $status = 2;
7735            $xStatus = 'processed';
7736            $uniqueEvents = [];
7737            $currentEvents = [];
7738            $followUpLogs = [];
7739            $sendgridFollowUpLogs = [];
7740            $projectTypes = [];
7741
7742            if ($order) {
7743                $emails = explode(',', str_replace(' ', '', $order->email));
7744
7745                // FIRE-864 (30/04): pre-fix this used the composite WHERE
7746                // `quotation_id = ? AND x_message_id = ?`. That returned
7747                // null whenever:
7748                //   - tbl_quotations.x_message_id was NULL (status 22 rows
7749                //     where SendGrid never even attempted a send), or
7750                //   - the webhook row's quotation_id was NULL or didn't
7751                //     match (legacy webhook rows from before we started
7752                //     stamping quotation_id consistently).
7753                // The "Titan intentó enviarlo y SendGrid falló" modal then
7754                // showed empty even though webhook events existed. Match
7755                // on quotation_id only, newest first — we still get the
7756                // latest SendGrid event for that quote.
7757                $sendGrid = TblSendgridWebhook::where('quotation_id', $quoteId)
7758                    ->orderByDesc('id')
7759                    ->first();
7760
7761                if ($sendGrid) {
7762                    $emailErrors = ['deferred', 'bounce', 'dropped', 'spamreport', 'invalid'];
7763                    $events = json_decode($sendGrid->json_body, true);
7764                    $xMessageId = $sendGrid->x_message_id;
7765                    $isDelivered = 0;
7766                    $isProcessed = 0;
7767                    $isError = 0;
7768
7769                    foreach ($emails as $email) {
7770
7771                        $emailEvents = array_filter($events, fn (array $event): bool => strtolower((string) $event['email']) === strtolower($email));
7772
7773                        $statuses = array_unique(array_column($emailEvents, 'event'));
7774                        $eventCount = count($statuses);
7775
7776                        if ($eventCount === 1 && in_array('processed', $statuses)) {
7777                            $xStatus = 'processed';
7778                        }
7779
7780                        if ($eventCount == 2) {
7781                            if (in_array('processed', $statuses) && in_array('delivered', $statuses)) {
7782                                $xStatus = 'delivered';
7783                            }
7784
7785                            foreach ($emailErrors as $e) {
7786                                if (in_array('processed', $statuses) && in_array($e, $statuses)) {
7787                                    $xStatus = $e;
7788                                }
7789                            }
7790
7791                        } elseif ($eventCount > 2) {
7792                            if (in_array('processed', $statuses) && in_array('delivered', $statuses)) {
7793                                $xStatus = 'delivered';
7794                            }
7795
7796                            if ($xStatus != 'delivered') {
7797                                foreach ($emailErrors as $e) {
7798                                    if (in_array('processed', $statuses) && in_array($e, $statuses)) {
7799                                        $xStatus = $e;
7800                                    }
7801                                }
7802                            }
7803                        }
7804
7805                        if ($xStatus == 'processed') {
7806                            $isProcessed++;
7807                        } elseif ($xStatus == 'delivered') {
7808                            $isDelivered++;
7809                        } else {
7810                            $isError++;
7811                        }
7812
7813                        foreach ($emailEvents as $event) {
7814                            $key = strtolower($event['email']).'|'.$event['event'];
7815                            if (! isset($uniqueEvents[$key])) {
7816                                $uniqueEvents[$key] = $event;
7817                            }
7818                        }
7819                    }
7820
7821                    if ($uniqueEvents) {
7822                        foreach (array_values($uniqueEvents) as $d) {
7823                            $d['created_at'] = date('Y-m-d H:i:s', $d['timestamp']);
7824
7825                            if (isset($d['response'])) {
7826                                $d['error'] = $d['response'];
7827                            }
7828
7829                            if (isset($d['reason'])) {
7830                                $d['error'] = $d['reason'];
7831                            }
7832
7833                            array_push($currentEvents, $d);
7834                        }
7835                    }
7836
7837                    if (count($emails) == $isDelivered) {
7838                        $status = 1;
7839                        $xStatus = 'Completed';
7840                    } elseif ($isProcessed > 0) {
7841                        $status = 2;
7842                        $xStatus = 'Processing';
7843                    } elseif ($isError > 0) {
7844                        $status = 3;
7845
7846                        if ($xStatus == 'bounce') {
7847                            $xStatus = 'Error - Bounce';
7848                        } else {
7849                            $xStatus = 'Error';
7850                        }
7851                    }
7852                }
7853
7854                if ($order->x_status != $xStatus) {
7855                    TblQuotations::where('id', $order->id)->update(
7856                        [
7857                            'x_status' => $xStatus,
7858                        ]
7859                    );
7860                    $z = 1;
7861                    // FIRE-1145: was Cache::flush() — narrowed to quotations domain
7862                    // (this branch updates x_status, so list_quotations caches are
7863                    // genuinely affected, but no other domain is).
7864                    ResultCache::forgetDomain('quotations');
7865                }
7866
7867                if (empty($currentEvents)) {
7868                    $status = 0;
7869                }
7870
7871                $followUpLogs = TblFollowUpLogs::where('quotation_id', $quoteId)->orderBy('created_at', 'desc')->get();
7872
7873                $projectTypes = TblProjectTypes::where('company_id', $order->company_id)->get();
7874
7875                if ($order->y_message_id) {
7876                    $sendgridFollowUpLogs = TblSendgridWebhook::where('x_message_id', $order->y_message_id)->first();
7877
7878                    if ($sendgridFollowUpLogs) {
7879                        $sendgridFollowUpLogs = json_decode($sendgridFollowUpLogs->json_body, true);
7880                        foreach ($sendgridFollowUpLogs as &$item) {
7881                            $item['created_at'] = date('Y-m-d H:i:s', $item['timestamp']);
7882                        }
7883                    }
7884                }
7885            }
7886
7887            return response([
7888                'message' => 'OK',
7889                'data' => $result,
7890                'followUpLogs' => $followUpLogs,
7891                'sendgridFollowUpLogs' => $sendgridFollowUpLogs,
7892                'internal' => $internal,
7893                'projectTypes' => $projectTypes,
7894                'currentEvents' => [
7895                    'status' => $status,
7896                    'email' => $currentEvents,
7897                    $uniqueEvents,
7898                    $xStatus,
7899                ],
7900                'job' => $job,
7901                'isUpdated' => $z,
7902            ]);
7903
7904        } catch (\Exception $e) {
7905            report(AppException::fromException($e, 'GET_FILES_EXCEPTION'));
7906
7907            return response(['message' => 'KO', 'error' => $e->getMessage()]);
7908        }
7909
7910    }
7911
7912    public function download_file($fileId)
7913    {
7914        try {
7915            // Titan → Zeus bridge (read). Zeus streams the bytes; the response
7916            // is relayed with Content-Type/Disposition/Length intact so the
7917            // download is indistinguishable from Titan's own.
7918            $zeus = app(ZeusBridge::class);
7919            $forward = $zeus->downloadFile(request(), $fileId);
7920
7921            if ($zeus->shouldReturnZeusResponse($forward)) {
7922                return $forward->toTitanResponse();
7923            }
7924
7925            $fileId = addslashes((string) $fileId);
7926            $file = TblFiles::where('file_id', $fileId)->first();
7927
7928            if (! $file) {
7929                return response()->json([
7930                    'message' => 'KO',
7931                    'error' => 'Archivo no encontrado',
7932                ], 404);
7933            }
7934
7935            if (! is_null($file->file_hash) && ! empty($file->file)) {
7936                $fileContent = $file->file;
7937                $mimeType = $file->mime_type ?? 'application/octet-stream';
7938                $filename = $file->original_name ?? $file->filename ?? 'download';
7939
7940                return response($fileContent)
7941                    ->header('Content-Type', $mimeType)
7942                    ->header('Content-Disposition', 'attachment; filename="'.$filename.'"')
7943                    ->header('Content-Length', strlen((string) $fileContent))
7944                    ->header('Cache-Control', 'no-cache, no-store, must-revalidate');
7945
7946            } else {
7947                if (! Storage::disk('s3')->exists('uploads/'.$file->filename)) {
7948                    return response()->json([
7949                        'message' => 'KO',
7950                        'error' => 'Archivo físico no encontrado: '.$file->filename,
7951                    ], 404);
7952                }
7953
7954                // Storage::disk('s3')->get() returns the file CONTENTS, not a
7955                // path. The old code stored that binary string in $filePath and
7956                // then passed it to filesize()/mime_content_type()/
7957                // file_get_contents() as if it were a filename — any binary
7958                // payload (PDF, image, etc.) contains a null byte, so filesize()
7959                // aborted with "Filename contains null byte." Use the contents
7960                // directly and size them with strlen().
7961                $fileContent = Storage::disk('s3')->get('uploads/'.$file->filename);
7962                $fileSize = strlen((string) $fileContent);
7963                $mimeType = $file->mime_type
7964                    ?: (Storage::disk('s3')->mimeType('uploads/'.$file->filename) ?: 'application/octet-stream');
7965                $filename = $file->original_name ?? $file->filename;
7966
7967                return response($fileContent)
7968                    ->header('Content-Type', $mimeType)
7969                    ->header('Content-Disposition', 'attachment; filename="'.$filename.'"')
7970                    ->header('Content-Length', $fileSize)
7971                    ->header('Cache-Control', 'no-cache, no-store, must-revalidate');
7972            }
7973
7974        } catch (\Exception $e) {
7975            report(AppException::fromException($e, 'DOWNLOAD_FILE_EXCEPTION'));
7976            Log::error('Error downloading file: '.$e->getMessage());
7977
7978            return response()->json([
7979                'message' => 'KO',
7980                'error' => 'Error interno del servidor: '.$e->getMessage(),
7981            ], 500);
7982        }
7983    }
7984
7985    public function delete_file($fileId): ResponseFactory|HttpResponse
7986    {
7987
7988        try {
7989
7990            $fileId = addslashes((string) $fileId);
7991            $file = TblFiles::where('file_id', $fileId)->first();
7992
7993            // PHP-LARAVEL-1S: the row can already be gone - a double-click on
7994            // delete, or a stale file list - and every use of $file below
7995            // dereferences it. Answer 404 instead of throwing on null.
7996            if (! $file) {
7997                return response(['message' => 'KO', 'error' => 'file_not_found'], 404);
7998            }
7999
8000            // FST New Features (2026-06-26) point 3: the coverage contract that
8001            // must go out with the budget is non-deletable. The UI swaps its
8002            // delete button for an "upload signed version" action; this is the
8003            // server-side backstop in case the request is issued directly.
8004            if ((int) $file->is_coverage_contract === 1) {
8005                return response([
8006                    'message' => 'KO',
8007                    'error' => 'El contrato de cobertura no se puede eliminar. Use el botón para subir la versión firmada.',
8008                ], 422);
8009            }
8010
8011            TblFiles::where('file_id', $fileId)->delete();
8012            Storage::disk('public')->delete('uploads/'.$file->filename);
8013
8014            if (! config('services.sendgrid.staging')) {
8015                Storage::disk('s3')->delete('uploads/'.$file->filename);
8016            }
8017
8018            // PHP-LARAVEL-1R: this read $file->quote_id, which is NULL on ~96%
8019            // of tbl_files rows, so the log insert below sent NULL into the NOT
8020            // NULL tbl_quotations_log.quotation_id and threw. The populated
8021            // column is quotation_id, and it holds tbl_quotations.id - which is
8022            // also why the has_attachment update matched on the wrong key and
8023            // silently updated nothing, leaving the flag stale after a delete.
8024            $quotationId = $file->quotation_id;
8025
8026            // A small number of rows really do have no parent (19 of 138,877 in
8027            // the local dataset). Their file is still removed above; there is
8028            // simply no quotation to re-flag or write a history entry against.
8029            if ($quotationId !== null) {
8030                $fileCount = TblFiles::where('quotation_id', $quotationId)->count();
8031
8032                TblQuotations::where('id', $quotationId)->update([
8033                    'has_attachment' => $fileCount > 0 ? 1 : 0,
8034                ]);
8035
8036                $this->addUpdateLog($quotationId, 'user', 'delete_attachment', $file->filename, null, 4);
8037            }
8038
8039            return response(['message' => 'OK']);
8040
8041        } catch (\Exception $e) {
8042            report(AppException::fromException($e, 'DELETE_FILE_EXCEPTION'));
8043
8044            return response(['message' => 'KO', 'error' => $e->getMessage()]);
8045        }
8046    }
8047
8048    /**
8049     * FST New Features (2026-06-26) point 3 — upload the (unsigned) coverage
8050     * contract for an Instalaciones/Correctivos budget >= 10.000 €. Stored as
8051     * a CLIENT file (is_internal NULL) so send_email_to_client automatically
8052     * attaches it to the outgoing budget email, and flagged
8053     * is_coverage_contract = 1 so it cannot be deleted (see delete_file) — the
8054     * comercial can only replace it by uploading the signed version.
8055     */
8056    public function upload_coverage_contract(Request $request, $quoteId): ResponseFactory|HttpResponse
8057    {
8058        try {
8059            $quoteId = addslashes((string) $quoteId);
8060            $quotation = TblQuotations::where('id', $quoteId)->first();
8061
8062            if (! $quotation) {
8063                return response(['message' => 'KO', 'error' => 'quotation_not_found'], 404);
8064            }
8065
8066            $file = $request->file('file');
8067            if (! $file) {
8068                return response(['message' => 'KO', 'error' => 'No se ha recibido ningún archivo.'], 422);
8069            }
8070
8071            $uploadedBy = $request->input('updated_by')
8072                ?? TblUsers::where('id', $request->input('user_id'))->value('name');
8073
8074            // One coverage contract per budget (the signed version is uploaded
8075            // separately via upload_signed_coverage_contract and linked by
8076            // parent_file_id, so exclude signed rows from this guard).
8077            if (TblFiles::where('quotation_id', $quoteId)
8078                ->where('is_coverage_contract', 1)
8079                ->whereNull('parent_file_id')
8080                ->exists()) {
8081                return response(['message' => 'KO', 'error' => 'Ya existe un contrato de cobertura para este pedido.'], 422);
8082            }
8083
8084            $origFilename = $file->getClientOriginalName();
8085            $filename = $quotation->id.'-'.$quotation->company_id.'-CC'.time().'-'.$origFilename;
8086
8087            Storage::disk('s3')->putFileAs('uploads', $file, $filename, ['ContentType' => $file->getMimeType()]);
8088
8089            $created = TblFiles::create([
8090                'quotation_id' => $quoteId,
8091                'original_name' => $origFilename,
8092                'filename' => $filename,
8093                'uploaded_by' => $uploadedBy,
8094                'file_size' => $file->getSize(),
8095                'mime_type' => $file->getMimeType(),
8096                'uploaded_at' => now(),
8097                'is_internal' => null,
8098                'is_coverage_contract' => 1,
8099            ]);
8100
8101            TblQuotations::where('id', $quoteId)->update(['has_attachment' => 1]);
8102            $this->addUpdateLog($quoteId, $uploadedBy ?? 'user', 'upload_coverage_contract', null, $filename, 4);
8103
8104            return response(['message' => 'OK', 'file_id' => $created->file_id]);
8105        } catch (\Exception $e) {
8106            report(AppException::fromException($e, 'UPLOAD_COVERAGE_CONTRACT_EXCEPTION'));
8107
8108            return response(['message' => 'KO', 'error' => $e->getMessage()]);
8109        }
8110    }
8111
8112    /**
8113     * FST New Features (2026-06-26) point 3 — upload the client-SIGNED version
8114     * of the coverage contract after acceptance. Stored as a NEW file linked to
8115     * the original (parent_file_id) and flagged is_signed = 1; the original is
8116     * kept for traceability (both remain visible). Also sets the budget's
8117     * `coverage_contract_signed` flag to 1 (Sí). This is traceability only and
8118     * never blocks progression.
8119     */
8120    public function upload_signed_coverage_contract(Request $request, $fileId): ResponseFactory|HttpResponse
8121    {
8122        try {
8123            $fileId = addslashes((string) $fileId);
8124            $original = TblFiles::where('file_id', $fileId)->first();
8125
8126            if (! $original || (int) $original->is_coverage_contract !== 1) {
8127                return response(['message' => 'KO', 'error' => 'No se ha encontrado el contrato de cobertura.'], 404);
8128            }
8129
8130            $file = $request->file('file');
8131            if (! $file) {
8132                return response(['message' => 'KO', 'error' => 'No se ha recibido ningún archivo.'], 422);
8133            }
8134
8135            $uploadedBy = $request->input('updated_by')
8136                ?? TblUsers::where('id', $request->input('user_id'))->value('name');
8137
8138            $quotation = TblQuotations::where('id', $original->quotation_id)->first();
8139            $companyId = $quotation->company_id ?? 0;
8140
8141            $origFilename = $file->getClientOriginalName();
8142            $filename = $original->quotation_id.'-'.$companyId.'-CCS'.time().'-'.$origFilename;
8143
8144            Storage::disk('s3')->putFileAs('uploads', $file, $filename, ['ContentType' => $file->getMimeType()]);
8145
8146            $created = TblFiles::create([
8147                'quotation_id' => $original->quotation_id,
8148                'original_name' => $origFilename,
8149                'filename' => $filename,
8150                'uploaded_by' => $uploadedBy,
8151                'file_size' => $file->getSize(),
8152                'mime_type' => $file->getMimeType(),
8153                'uploaded_at' => now(),
8154                'is_internal' => $original->is_internal,
8155                'is_coverage_contract' => 1,
8156                'is_signed' => 1,
8157                'parent_file_id' => $original->file_id,
8158            ]);
8159
8160            TblQuotations::where('id', $original->quotation_id)->update([
8161                'coverage_contract_signed' => 1,
8162                'has_attachment' => 1,
8163            ]);
8164            $this->addUpdateLog($original->quotation_id, $uploadedBy ?? 'user', 'upload_signed_coverage_contract', null, $filename, 4);
8165
8166            return response(['message' => 'OK', 'file_id' => $created->file_id]);
8167        } catch (\Exception $e) {
8168            report(AppException::fromException($e, 'UPLOAD_SIGNED_COVERAGE_CONTRACT_EXCEPTION'));
8169
8170            return response(['message' => 'KO', 'error' => $e->getMessage()]);
8171        }
8172    }
8173
8174    /**
8175     * FST New Features (2026-06-26) points 2 & 3 — send-stage SOP guardrails.
8176     * Returns a list of human-readable (Spanish) reasons the offer may NOT be
8177     * sent / moved to "Enviado"; an empty array means no blockers. Thresholds
8178     * are data-driven and per-company (admin-tunable), mirroring the
8179     * is_validated gate:
8180     *   - Point 2: tbl_maintenance_potential_settings (strict ">"). When it
8181     *     matches, the maintenance-potential question must be answered.
8182     *   - Point 3: tbl_coverage_contract_settings (">="). When it matches, a
8183     *     coverage contract (any client attachment, is_internal NULL) must be
8184     *     present so it is sent automatically with the offer.
8185     *
8186     * The point-3 SIGNED question is intentionally NOT checked here — it belongs
8187     * to the acceptance transition and is non-blocking (offer already accepted).
8188     *
8189     * @param  object  $quotation  needs ->id, ->amount, ->budget_type_id, ->company_id, ->maintenance_potential
8190     * @param  bool  $hasPendingClientFile  true when this request is uploading a client file that isn't persisted yet
8191     */
8192    private function sopBlockingRequirements(object $quotation, bool $hasPendingClientFile = false): array
8193    {
8194        $reasons = [];
8195
8196        $budgetTypeId = (int) ($quotation->budget_type_id ?? 0);
8197        if (! $budgetTypeId) {
8198            return $reasons;
8199        }
8200
8201        $amount = (float) ($quotation->amount ?? 0);
8202        $companyId = $quotation->company_id ?? null;
8203
8204        // Point 2 — maintenance potential ("above" the threshold, strict)
8205        $maintenanceSettings = TblMaintenancePotentialSettings::when(
8206            $companyId !== null,
8207            fn ($q) => $q->where('company_id', $companyId)
8208        )->get();
8209        if ($this->matchesBudgetSetting($maintenanceSettings, $budgetTypeId, $amount, false)
8210            && ($quotation->maintenance_potential ?? null) === null) {
8211            $reasons[] = 'Debe responder "¿La obra genera potencial de mantenimiento?".';
8212        }
8213
8214        // Point 3 — coverage contract attached ("above or equal to" the
8215        // threshold) so it is sent automatically with the offer.
8216        //
8217        // FIRE-1596: if the company has a default template configured in
8218        // tbl_coverage_contract_settings.default_contract_s3_path, we do NOT
8219        // block the send — send_email_to_client will auto-attach the template.
8220        $coverageSettings = TblCoverageContractSettings::when(
8221            $companyId !== null,
8222            fn ($q) => $q->where('company_id', $companyId)
8223        )->get();
8224        if ($this->matchesBudgetSetting($coverageSettings, $budgetTypeId, $amount, true)) {
8225            $hasContract = $hasPendingClientFile || TblFiles::where('quotation_id', $quotation->id)
8226                ->whereNull('is_internal')
8227                ->exists();
8228            $hasTemplate = $coverageSettings->contains(
8229                fn ($s) => ! empty($s->default_contract_s3_path)
8230            );
8231            if (! $hasContract && ! $hasTemplate) {
8232                $reasons[] = 'Debe adjuntar el contrato de cobertura para enviarlo con la oferta.';
8233            }
8234        }
8235
8236        return $reasons;
8237    }
8238
8239    /**
8240     * PHP mirror of the frontend BudgetMarginService.matchesBudgetSetting:
8241     * true when any setting's budget_type_id CSV list contains $budgetTypeId
8242     * and $amount crosses the row's minimum_budget_amount. $inclusive selects
8243     * ">=" (point 3) vs strict ">" (point 2, matching the JS helper).
8244     */
8245    private function matchesBudgetSetting($settings, int $budgetTypeId, float $amount, bool $inclusive = false): bool
8246    {
8247        foreach ($settings as $setting) {
8248            $ids = [];
8249            if (! empty($setting->budget_type_id)) {
8250                $ids = array_map(
8251                    'intval',
8252                    array_filter(explode(',', (string) $setting->budget_type_id), fn ($v) => trim($v) !== '')
8253                );
8254            }
8255
8256            $min = (float) ($setting->minimum_budget_amount ?? 0);
8257            $amountOk = $inclusive ? ($amount >= $min) : ($amount > $min);
8258
8259            if (in_array($budgetTypeId, $ids, true) && $amountOk) {
8260                return true;
8261            }
8262        }
8263
8264        return false;
8265    }
8266
8267    /**
8268     * FIRE-1901: pick the body for a send-loop iteration. Trusts FE-supplied
8269     * HTML only when the user marked it edited (is_edited === true, set by the
8270     * Quill onContentChanged / source === 'user' hook). Otherwise falls back
8271     * to the canonical DB template — preserves 9ecc21b3's guarantee that
8272     * untouched sends survive Quill's on-load sanitization (which strips
8273     * tables, base64 <img>, inline styles).
8274     */
8275    public function resolveEmailBody(?array $sentHtml, string $canonicalHtml): string
8276    {
8277        if (! empty($sentHtml['is_edited']) && ! empty($sentHtml['html'])) {
8278            return (string) $sentHtml['html'];
8279        }
8280
8281        return $canonicalHtml;
8282    }
8283
8284    /**
8285     * Whether *this budget must not go to the client yet* because its approval
8286     * is unresolved. The gate for send_email_to_client, which walks the rows
8287     * list_orders_table returned.
8288     *
8289     * Two ways a budget can be awaiting approval, and only checking the first
8290     * is what let approved-nothing budgets out:
8291     *
8292     *   1. `for_approval` in (1,2,3) — the request was raised and nobody has
8293     *      decided. This is PENDING_APPROVAL_SQL's definition, and the SQL
8294     *      constant covers it wherever a WHERE clause can run.
8295     *
8296     *   2. `for_approval` IS NULL but the matrix engine says the budget crosses
8297     *      a threshold and the approvals on file do not cover it. The engine
8298     *      path is draft-until-confirm: the save deliberately leaves the flag
8299     *      null and only `confirm_approval_request` writes it (see the comment
8300     *      there). So a budget that requires approval and whose request was
8301     *      never confirmed carries NO flag at all — the reported case, where
8302     *      simply reopening it offered "Enviar al cliente".
8303     *
8304     * Case 2 cannot be expressed in SQL (the engine matches CSV budget/customer
8305     * type lists across priority-ordered rows), which is why this is a PHP gate
8306     * rather than a reuse of the constant. It is also why the resend path needs
8307     * it: that fetches the selection with `is_send_to_client = 0`, so no
8308     * WHERE-clause gate runs for it at all.
8309     */
8310    private function isRowPendingApproval($row): bool
8311    {
8312        // A recorded rejection in either slot, or an already-rejected status,
8313        // ends the circuit — whatever a stale flag still says.
8314        if (($row->rejected_by ?? null) !== null || ($row->rejected_by_v2 ?? null) !== null) {
8315            return false;
8316        }
8317
8318        $statusId = $row->budget_status_id ?? null;
8319
8320        if ($statusId !== null
8321            && in_array((int) $statusId, array_map('intval', explode(',', self::REJECTED_STATUS_IDS)), true)) {
8322            return false;
8323        }
8324
8325        // (1) Request raised, nobody has decided.
8326        if (in_array((int) ($row->for_approval ?? 0), [1, 2, 3], true)) {
8327            return true;
8328        }
8329
8330        // (2) Requirement stands but was never confirmed into a request.
8331        return $this->budgetRequiresUnresolvedApproval($row);
8332    }
8333
8334    /** Per-request memo so a bulk send resolves each company's matrix once. */
8335    private array $approvalGateCompanies = [];
8336
8337    /**
8338     * Matrix-engine half of isRowPendingApproval: does this budget still need an
8339     * approval nobody has given?
8340     *
8341     * Mirrors what `preview_approval` reports as `pendingApproval` — the raw
8342     * threshold decision minus the approvals that still stand — so the send gate
8343     * and the warning the comercial sees under the amount field answer the same
8344     * question. Passing `[]` as the edit payload means "nothing changed", which
8345     * is right here: we are judging the stored budget, not an edit of it.
8346     *
8347     * Returns false whenever the engine is not governing (`use_matrix_engine`
8348     * off, or no matrix row matches this company/type pair) — those companies
8349     * keep the legacy flag-only behaviour, which is what evaluateApprovalForBudget
8350     * already signals via `matched`.
8351     */
8352    private function budgetRequiresUnresolvedApproval($row): bool
8353    {
8354        $companyId = $this->intOrNull($row->company_id ?? null);
8355
8356        if ($companyId === null) {
8357            return false;
8358        }
8359
8360        if (! array_key_exists($companyId, $this->approvalGateCompanies)) {
8361            $this->approvalGateCompanies[$companyId] = TblCompanies::where('company_id', $companyId)->first();
8362        }
8363
8364        $company = $this->approvalGateCompanies[$companyId];
8365
8366        if ($company === null) {
8367            return false;
8368        }
8369
8370        // list_orders_table hands us a stdClass; the single-budget gate below
8371        // passes an Eloquent model, whose (array) cast yields mangled keys.
8372        $attributes = $row instanceof TblQuotations ? $row->getAttributes() : (array) $row;
8373
8374        $eval = $this->evaluateApprovalForBudget($attributes, $company);
8375
8376        if (! $eval['matched'] || ! $eval['requiresApproval']) {
8377            return false;
8378        }
8379
8380        $pending = $this->pendingApprovalDimensions(
8381            [],
8382            $row,
8383            $eval['reqTechnical'],
8384            $eval['reqFinancial'],
8385            false,
8386            $eval['financialMinimumsApplied'],
8387        );
8388
8389        return $pending['tech'] || $pending['fin'];
8390    }
8391
8392    /**
8393     * Read-only: may this budget be sent to the client, or is an approval still
8394     * outstanding? Drives the edit modal's "Enviar al cliente" button.
8395     *
8396     * Deliberately takes only an id and reads the stored row — it is the SAME
8397     * call `send_email_to_client` makes per row, so the button and the gate can
8398     * never disagree. (previewApproval cannot fill this role: it evaluates the
8399     * values the client posts, so a formatting difference between the grid row
8400     * and the stored column would flip the answer.)
8401     */
8402    public function send_approval_gate($id): ResponseFactory|HttpResponse
8403    {
8404        try {
8405            $row = TblQuotations::where('id', addslashes((string) $id))->first();
8406
8407            return response([
8408                'message' => 'OK',
8409                'blocked' => $row !== null && $this->isRowPendingApproval($row),
8410            ]);
8411        } catch (\Exception $e) {
8412            report(AppException::fromException($e, 'SEND_APPROVAL_GATE_EXCEPTION'));
8413
8414            // Read-only probe: never block the UI on its failure. The send
8415            // endpoint re-checks and is the authority.
8416            return response(['message' => 'KO', 'blocked' => false, 'error' => $e->getMessage()]);
8417        }
8418    }
8419
8420    /**
8421     * One warning per company per request, not per quote (FIRE-1449 log
8422     * volume): a batch can hold hundreds of quotes from the same company.
8423     *
8424     * @param  array<int, true>  $warned
8425     */
8426    private function warnMissingEmailTemplate(array &$warned, int $companyId, string $source): void
8427    {
8428        if (isset($warned[$companyId])) {
8429            return;
8430        }
8431
8432        $warned[$companyId] = true;
8433        Log::channel('email_log')->warning("{$source}: no email template selected for company {$companyId}, its quotes were skipped");
8434    }
8435
8436    public function send_email_to_client(Request $request): ResponseFactory|HttpResponse
8437    {
8438
8439        ini_set('max_execution_time', 0);
8440
8441        try {
8442
8443            $data = $request->all();
8444
8445            // $id = addslashes($data['id']);
8446            $userId = addslashes((string) $data['user_id']);
8447            $companyId = addslashes((string) $data['company_id']);
8448
8449            $isResend = null;
8450
8451            if (isset($data['is_resend'])) {
8452                $isResend = 1;
8453                unset($data['is_resend']);
8454            }
8455
8456            $sendChannel = isset($data['send_channel']) && $data['send_channel'] === 'whatsapp' ? 'whatsapp' : 'email';
8457
8458            $where = '';
8459            $emailTemplateId = $data['email_template_id'];
8460            unset($data['email_template_id']);
8461
8462            $emailTemplates = [];
8463
8464            if (isset($data['html'])) {
8465                $emailTemplates = array_column($data['html'], null, 'id');
8466            }
8467
8468            $emailTemplate = TblEmailConfiguration::whereIn('id', $emailTemplateId)->get()->keyBy('company_id');
8469
8470            $emailCompany = [];
8471
8472            $result = [];
8473
8474            $result = [];
8475
8476            if ($companyId == 0) {
8477                $indexes = $emailTemplate->keys();
8478
8479                $emailCompany = TblCompanies::whereIn('company_id', $indexes)->get()->keyBy('company_id');
8480                $limit = 21;
8481
8482                foreach ($emailCompany as $item) {
8483                    $r = new Request([
8484                        'filterModel' => $data['filterModel'] ?? [],
8485                        'sortModel' => $data['sortModel'] ?? [],
8486                        'start' => 0,
8487                        'end' => 999999999,
8488                        'company_id' => $data['company_id'],
8489                        'user_id' => $data['user_id'],
8490                        'ids' => $data['ids'],
8491                        'searchText' => $data['searchText'] ?? '',
8492                        'ids_not_in' => $data['ids_not_in'],
8493                        // Pull the data from the Orders table source. When not
8494                        // resending, scope to the send-to-client bucket (status 11
8495                        // + valid email + budget type) so we only fetch eligible
8496                        // rows; on resend, fetch the selection unfiltered and let
8497                        // the loop below decide.
8498                        'is_send_to_client' => $isResend == 1 ? 0 : 1,
8499                    ]);
8500
8501                    $listQuotations = $this->list_orders_table($r);
8502                    $d = $listQuotations->original['data'];
8503
8504                    if ($item->limit_send != null) {
8505                        $limit = $item->limit_send;
8506                    }
8507                    $l = 0;
8508                    for ($i = 0; $i < count($d); $i++) {
8509                        $channelOk = $sendChannel === 'whatsapp'
8510                            ? ! empty($d[$i]->phone_number)
8511                            : ($d[$i]->email != null && ! $this->isBlacklistedEmail($d[$i]->email));
8512
8513                        if ($channelOk
8514                            && $d[$i]->budget_type_id != null
8515                            && ($d[$i]->budget_status_id == 11 || $isResend == 1)
8516                            // A budget awaiting an approval decision is never
8517                            // sendable, resend included. The is_send_to_client
8518                            // filter already drops these on the normal path, but
8519                            // a resend fetches the selection unfiltered — this is
8520                            // the gate that holds in both cases.
8521                            && ! $this->isRowPendingApproval($d[$i])
8522                            && $item->company_id == $d[$i]->company_id
8523                        ) {
8524                            if ($l == $limit) {
8525                                break;
8526                            }
8527                            array_push($result, $d[$i]);
8528                            $l++;
8529                        } elseif ($sendChannel === 'email' && $d[$i]->email != null && $this->isBlacklistedEmail($d[$i]->email)) {
8530                            TblQuotations::where('id', $d[$i]->id)->update(['budget_status_id' => 22]);
8531                        }
8532                    }
8533                }
8534            } else {
8535
8536                $emailCompany = TblCompanies::where('company_id', $companyId)->get()->keyBy('company_id');
8537
8538                $limit = 21;
8539
8540                if ($emailCompany[$companyId]->limit_send != null) {
8541                    $limit = $emailCompany[$companyId]->limit_send;
8542                }
8543
8544                $r = new Request([
8545                    'filterModel' => $data['filterModel'] ?? [],
8546                    'sortModel' => $data['sortModel'] ?? [],
8547                    'start' => 0,
8548                    'end' => 999999999,
8549                    'company_id' => $data['company_id'],
8550                    'user_id' => $data['user_id'],
8551                    'ids' => $data['ids'],
8552                    'searchText' => $data['searchText'] ?? '',
8553                    'ids_not_in' => $data['ids_not_in'],
8554                    // Orders-table data source; scope to the send-to-client
8555                    // bucket unless resending (then fetch the selection as-is).
8556                    'is_send_to_client' => $isResend == 1 ? 0 : 1,
8557                ]);
8558
8559                $listQuotations = $this->list_orders_table($r);
8560                $d = $listQuotations->original['data'];
8561                $l = 0;
8562                for ($i = 0; $i < count($d); $i++) {
8563                    $channelOk = $sendChannel === 'whatsapp'
8564                        ? ! empty($d[$i]->phone_number)
8565                        : ($d[$i]->email != null && ! $this->isBlacklistedEmail($d[$i]->email));
8566
8567                    if ($channelOk
8568                        && ($d[$i]->budget_status_id == 11 || $isResend == 1)
8569                        // See the multi-company branch above: pending approval
8570                        // blocks the send on every path, resend included.
8571                        && ! $this->isRowPendingApproval($d[$i])
8572                    ) {
8573                        if ($l == $limit) {
8574                            break;
8575                        }
8576                        array_push($result, $d[$i]);
8577                        $l++;
8578                    } elseif ($sendChannel === 'email' && $d[$i]->email != null && $this->isBlacklistedEmail($d[$i]->email)) {
8579                        // FIRE-864 follow-up (04/05): pre-fix this branch wrote
8580                        // 21 (Fallo envio - correo erroneo) for blacklisted
8581                        // emails caught BEFORE Titan ever called SendGrid. The
8582                        // bucket policy says 21 = "Titan tried, SendGrid
8583                        // rejected" — so the row's helper text claims a
8584                        // SendGrid response that never existed (no x_status,
8585                        // no x_message_id). Quote 146914 is the canonical
8586                        // example. The multi-company branch ~40 lines up
8587                        // correctly writes 22; this single-company branch was
8588                        // the typo.
8589                        TblQuotations::where('id', $d[$i]->id)->update(['budget_status_id' => 22]);
8590                    }
8591                }
8592            }
8593
8594            // FST New Features (2026-06-26) points 2 & 3: never send a budget
8595            // that fails the SOP guardrails (maintenance question unanswered /
8596            // coverage contract missing). Skip them and report back so the UI
8597            // can tell the comercial which orders were held and why.
8598            $sopBlocked = [];
8599            $result = array_values(array_filter($result, function ($row) use (&$sopBlocked) {
8600                $reasons = $this->sopBlockingRequirements($row);
8601                if (! empty($reasons)) {
8602                    $sopBlocked[] = [
8603                        'id' => $row->id,
8604                        'quote_id' => $row->quote_id ?? null,
8605                        'reasons' => $reasons,
8606                    ];
8607
8608                    return false;
8609                }
8610
8611                return true;
8612            }));
8613
8614            if (count($result) == 0) {
8615                return response(['message' => 'OK', 'data' => $d ?? [], 'sop_blocked' => $sopBlocked]);
8616            }
8617
8618            $user = TblUsers::where('id', $userId)->first();
8619            $error = false;
8620
8621            $availableParameters = [
8622                'quote_id',
8623                'company_id',
8624                'client',
8625                'client_type',
8626                'phone_number',
8627                'email',
8628                'issue_date',
8629                'request_date',
8630                'duration',
8631                'invoice_number',
8632                'type',
8633                'acceptance_date',
8634                'status',
8635                'source',
8636                'amount',
8637                'reason_for_not_following_up',
8638                'last_follow_up_date',
8639                'last_follow_up_comment',
8640                'reason_for_rejection_id',
8641                'reason_for_rejection',
8642                'commercial',
8643                'created_at',
8644                'created_by',
8645                'updated_at',
8646                'updated_by',
8647            ];
8648
8649            $dateParameters = [
8650                'issue_date',
8651                'request_date',
8652                'acceptance_date',
8653                'last_follow_up_date',
8654                'created_at',
8655                'updated_at',
8656            ];
8657
8658            if ($this->locale == 'es') {
8659                setlocale(LC_ALL, 'es_ES', 'Spanish_Spain', 'Spanish');
8660                setlocale(LC_ALL, 'es_ES', 'Spanish_Spain', 'Spanish');
8661            }
8662
8663            $sentItems = [];
8664            $missingTemplateCompanies = [];
8665
8666            for ($i = 0; $i < count($result); $i++) {
8667
8668                // No template chosen for this quote's company: skip the quote
8669                // instead of crashing the whole batch on an undefined key.
8670                if (! isset($emailTemplate[$result[$i]->company_id])) {
8671                    $this->warnMissingEmailTemplate($missingTemplateCompanies, (int) $result[$i]->company_id, 'send_email_to_client');
8672
8673                    continue;
8674                }
8675
8676                // FIRE-1901: honor the FE-edited body ONLY when the user actually
8677                // typed in the Quill editor. See resolveEmailBody() for the
8678                // full rationale (Quill on-load sanitization + 9ecc21b3 guard).
8679                $body = $this->resolveEmailBody(
8680                    $emailTemplates[$result[$i]->company_id] ?? null,
8681                    $emailTemplate[$result[$i]->company_id]->html,
8682                );
8683                $subject = $emailTemplate[$result[$i]->company_id]->subject;
8684                $commercialUser = $result[$i]->commercial;
8685
8686                if ($sendChannel === 'whatsapp') {
8687                    if (empty($result[$i]->phone_number)) {
8688                        continue;
8689                    }
8690
8691                    preg_match_all('/{{(.*?)}}/', (string) $body, $waMatches);
8692                    foreach ($waMatches[1] as $parameter) {
8693                        if (in_array($parameter, $dateParameters) && $result[$i]->{$parameter}) {
8694                            $result[$i]->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result[$i]->{$parameter})));
8695                        }
8696                        if (in_array($parameter, $availableParameters)) {
8697                            $body = str_replace('{{'.$parameter.'}}', $result[$i]->{$parameter}, $body);
8698                        }
8699                    }
8700
8701                    $wa = app(WhatsAppService::class)->send($result[$i]->phone_number, $body);
8702
8703                    $comment = 'Se ha enviado la orden por WhatsApp manualmente al cliente el '.date('Y-m-d H:i:s').' por el usuario '.$user->name;
8704                    $result[$i]->last_follow_up_comment = $result[$i]->last_follow_up_comment."\n".$comment;
8705
8706                    TblQuotations::where('id', $result[$i]->id)->update([
8707                        'last_follow_up_comment' => $result[$i]->last_follow_up_comment,
8708                        'budget_status_id' => 2,
8709                        'wa_message_id' => $wa['sid'],
8710                        // No Twilio delivery callback is wired, so a successful
8711                        // hand-off to Twilio is the terminal state. Mirrors the
8712                        // email path's post-send stamp, but on the WhatsApp-only
8713                        // columns so the email x_status pipeline is untouched.
8714                        'wa_status' => $wa['ok'] ? 'delivered' : ('Error: '.substr((string) $wa['error'], 0, 60)),
8715                        'updated_by' => $user->name,
8716                        'updated_at' => date('Y-m-d H:i:s'),
8717                    ]);
8718
8719                    if ($wa['ok']) {
8720                        $sentItems[$result[$i]->company_id][] = $result[$i]->id;
8721                        // Parity with the email send: record the activity-log
8722                        // entry so the order timeline shows the manual send.
8723                        $this->addUpdateLog($result[$i]->id, $userId, 'send_email_to_client', null, null, 5);
8724                        QuotationSendRecorder::record((int) $result[$i]->id, QuotationSendRecorder::TITAN_WHATSAPP, $user->name ?? (string) $userId);
8725                    }
8726
8727                    continue;
8728                }
8729
8730                if ($result[$i]->email != null) {
8731
8732                    // FIRE-1930: honour the per-region kill switch for
8733                    // client-facing emails before we spend any work on
8734                    // template rendering, S3 attachment reads, or the
8735                    // SendGrid client instantiation. A gated region means
8736                    // the whole loop iteration is a no-op.
8737                    if (! SendgridDispatcher::isAllowed(
8738                        SendgridDispatcher::BUCKET_CLIENT,
8739                        (int) $result[$i]->company_id,
8740                    )) {
8741                        continue;
8742                    }
8743
8744                    if (config('services.sendgrid.staging')) {
8745                        $toEmail = $user->email;
8746                    } else {
8747                        $toEmail = $result[$i]->email;
8748                    }
8749
8750                    preg_match_all('/{{(.*?)}}/', (string) $body, $matches);
8751
8752                    $parameters = $matches[1];
8753
8754                    foreach ($parameters as $parameter) {
8755
8756                        if (in_array($parameter, $dateParameters)) {
8757                            if ($result[$i]->{$parameter}) {
8758                                $result[$i]->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result[$i]->{$parameter})));
8759                            }
8760                        }
8761
8762                        if (in_array($parameter, $availableParameters)) {
8763                            $body = str_replace('{{'.$parameter.'}}', $result[$i]->{$parameter}, $body);
8764                        }
8765                    }
8766
8767                    preg_match_all('/{{(.*?)}}/', (string) $subject, $matches);
8768
8769                    $parameters = $matches[1];
8770
8771                    foreach ($parameters as $parameter) {
8772
8773                        if (in_array($parameter, $dateParameters)) {
8774                            if ($result[$i]->{$parameter}) {
8775                                $result[$i]->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result[$i]->{$parameter})));
8776                            }
8777                        }
8778
8779                        if (in_array($parameter, $availableParameters)) {
8780                            $subject = str_replace('{{'.$parameter.'}}', $result[$i]->{$parameter}, $subject);
8781                        }
8782                    }
8783
8784                    $email = new Mail;
8785                    $templateFiles = TblEmailFiles::where('email_template_id', $emailTemplate[$result[$i]->company_id]->id)->orderBy('order', 'asc')->get();
8786
8787                    foreach ($templateFiles as $item) {
8788                        $f = storage_path('app/public/uploads/'.$item->filename);
8789
8790                        if (file_exists($f)) {
8791                            $imgpath = file_get_contents($f);
8792                            $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
8793                            $mimeType = mime_content_type($f);
8794
8795                            $email->addAttachment(
8796                                $imgpath,
8797                                $mimeType,
8798                                str_replace(' ', '', $item->original_name),
8799                                'inline',
8800                                str_replace(' ', '', $item->original_name),
8801                            );
8802
8803                            // An image the template already places itself (src="cid:<name>") is not
8804                            // repeated in the logo strip under the body.
8805                            if (! str_contains($body, 'cid:'.$item->original_name)) {
8806                                $body .= "<img src='cid:{$item->original_name}' style='height: 45px; padding-right: 6px' />";
8807                            }
8808                        } else {
8809                            Log::channel('email_failed_log')->error('File not found: '.$f);
8810                        }
8811                    }
8812
8813                    $html = '<!DOCTYPE html>';
8814                    $html .= '<html>';
8815                    $html .= '<head>';
8816                    $html .= '<meta charset="UTF-8">';
8817                    $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
8818                    $html .= '</head>';
8819                    $html .= '<body>';
8820                    $html .= $body;
8821                    $html .= '</body>';
8822                    $html .= '</html>';
8823
8824                    if ($toEmail != null) {
8825
8826                        $toEmail = explode(',', (string) $toEmail);
8827                        $toEmail = array_map(trim(...), $toEmail);
8828
8829                        $companyEmail = null;
8830
8831                        $queryUsers = "SELECT sender_email AS from_email, `name` AS from_name FROM tbl_users WHERE sender_enabled = 1 AND response_id IS NOT NULL AND verified = 1 AND `name` = '{$commercialUser}'";
8832                        $commercialEmail = DB::select($queryUsers);
8833
8834                        if (count($commercialEmail) > 0) {
8835                            $companyEmail = $commercialEmail[0];
8836                        } else {
8837                            if ($emailTemplate[$result[$i]->company_id]->from_id != null) {
8838                                $companyEmail = TblCompanyEmails::where('id', $emailTemplate[$result[$i]->company_id]->from_id)->first();
8839                            } else {
8840                                $companyEmail = TblCompanyEmails::where('is_active', 1)->where('verified', 1)->where('company_id', $result[$i]->company_id)->first();
8841                            }
8842                        }
8843
8844                        if (! $companyEmail) {
8845                            return response(['message' => 'KO', 'error' => __('language.no_active_verified_sender')]);
8846                        }
8847
8848                        $ccBcc = TblCcBcc::where('company_id', $result[$i]->company_id)->get();
8849
8850                        $email->setFrom($companyEmail->from_email, $companyEmail->from_name);
8851                        $email->setSubject($subject);
8852
8853                        foreach ($toEmail as $clientEmail) {
8854                            $isValid = $this->isEmailValid($clientEmail);
8855                            if ($isValid) {
8856                                $email->addTo($clientEmail);
8857                            }
8858                        }
8859
8860                        if (! config('services.sendgrid.staging')) {
8861                            if (! in_array($user->email, $toEmail)) {
8862                                $email->addCc($user->email);
8863                            }
8864                            if (count($ccBcc) > 0) {
8865                                foreach ($ccBcc as $data) {
8866                                    if (! in_array($data->email, $toEmail) && $user->email != $data->email) {
8867                                        $email->addBcc($data->email);
8868                                    }
8869                                }
8870                            }
8871                        }
8872
8873                        $email->addContent('text/html', $html);
8874                        $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
8875
8876                        $files = TblFiles::where('quotation_id', $result[$i]->id)->where('is_internal', null)->get();
8877                        $requestSize = $this->calculateEmailRequestSize($email);
8878
8879                        $hasCoverageContractFile = false;
8880
8881                        foreach ($files as $key => $value) {
8882                            $fileContent = null;
8883                            $fileSize = 0;
8884                            $fileName = null;
8885
8886                            if (Storage::disk('s3')->exists('uploads/'.$files[$key]->filename)) {
8887                                $fileContent = Storage::disk('s3')->get('uploads/'.$files[$key]->filename);
8888                                $fileSize = (int) ceil(strlen((string) $fileContent) / 1048576);
8889                                $fileName = $files[$key]->original_name;
8890                            } elseif ($files[$key]->file) {
8891                                $fileContent = $files[$key]->file;
8892
8893                                if (is_string($fileContent) && base64_decode($fileContent, true)) {
8894                                    $fileContent = base64_decode($fileContent);
8895                                }
8896
8897                                $fileSize = strlen((string) $fileContent) / 1048576;
8898                                $fileSize = (int) ceil($fileSize);
8899                                $fileName = $files[$key]->original_name ?: $files[$key]->getAttribute('file_name') ?: 'file';
8900                            }
8901
8902                            if ($fileContent && $fileSize > 0) {
8903                                if ($requestSize + $fileSize < 25) {
8904                                    $attachment = new Attachment;
8905                                    $attachment->setFilename($fileName);
8906                                    $attachment->setDisposition('attachment');
8907
8908                                    $attachment->setContent(base64_encode((string) $fileContent));
8909
8910                                    $email->addAttachment($attachment);
8911                                    $requestSize = $this->calculateEmailRequestSize($email);
8912
8913                                    if ((int) ($files[$key]->is_coverage_contract ?? 0) === 1) {
8914                                        $hasCoverageContractFile = true;
8915                                    }
8916                                }
8917                            }
8918                        }
8919
8920                        // FIRE-1596: if no per-quotation coverage contract was
8921                        // attached and the quotation crosses the company's
8922                        // threshold, auto-attach the company-wide template
8923                        // from tbl_coverage_contract_settings.default_contract_s3_path.
8924                        if (! $hasCoverageContractFile) {
8925                            $coverageSettings = TblCoverageContractSettings::where('company_id', $result[$i]->company_id)->get();
8926                            if ($this->matchesBudgetSetting(
8927                                $coverageSettings,
8928                                (int) ($result[$i]->budget_type_id ?? 0),
8929                                (float) ($result[$i]->amount ?? 0),
8930                                true,
8931                            )) {
8932                                $template = $coverageSettings->first(
8933                                    fn ($s) => ! empty($s->default_contract_s3_path)
8934                                );
8935                                if ($template && Storage::disk('s3')->exists($template->default_contract_s3_path)) {
8936                                    $tplContent = Storage::disk('s3')->get($template->default_contract_s3_path);
8937                                    $tplSize = (int) ceil(strlen((string) $tplContent) / 1048576);
8938
8939                                    if ($tplContent && $tplSize > 0 && $requestSize + $tplSize < 25) {
8940                                        $tplAttachment = new Attachment;
8941                                        $tplAttachment->setFilename($template->default_contract_filename ?: 'Contrato_de_cobertura.pdf');
8942                                        $tplAttachment->setDisposition('attachment');
8943                                        $tplAttachment->setContent(base64_encode((string) $tplContent));
8944
8945                                        $email->addAttachment($tplAttachment);
8946                                        $requestSize = $this->calculateEmailRequestSize($email);
8947                                    }
8948                                }
8949                            }
8950                        }
8951
8952                        $sentWithBackup = false;
8953
8954                        try {
8955                            $response = $sendgrid->send($email);
8956                            SendgridLogger::log($email, $response);
8957                        } catch (\Throwable $sendException) {
8958                            SendgridLogger::logException($email, $sendException);
8959                            throw $sendException;
8960                        }
8961
8962                        if (config('services.sendgrid.block') === true) {
8963
8964                            Log::warning("SendGrid failed with status {$response->statusCode()}. Initiating Failover...");
8965                            try {
8966                                \Illuminate\Support\Facades\Mail::mailer('resend')->send([], [], function ($message) use ($html, $companyEmail, $toEmail, $subject, $files, $user, $ccBcc): void {
8967                                    $message->from($companyEmail->from_email, $companyEmail->from_name)
8968                                        ->to($toEmail)
8969                                        ->subject($subject);
8970
8971                                    $message->html($html);
8972
8973                                    $message->cc($user->email);
8974
8975                                    foreach ($ccBcc as $bcc) {
8976                                        $message->bcc($bcc->email);
8977                                    }
8978
8979                                    foreach ($files as $file) {
8980                                        if (Storage::disk('s3')->exists('uploads/'.$file->filename)) {
8981                                            $content = Storage::disk('s3')->get('uploads/'.$file->filename);
8982                                            $message->attachData($content, $file->original_name);
8983                                        } elseif ($file->file) {
8984                                            $content = $file->file;
8985                                            if (is_string($content) && base64_decode($content, true)) {
8986                                                $content = base64_decode($content);
8987                                            }
8988                                            $message->attachData($content, $file->original_name ?: 'archivo.pdf');
8989                                        }
8990                                    }
8991                                });
8992
8993                                $sentWithBackup = true;
8994                            } catch (\Exception $backupException) {
8995                                $sentWithBackup = false;
8996                                Log::error('Backup server also failed: '.$backupException->getMessage());
8997                            }
8998
8999                            if (! $sentWithBackup) {
9000                                throw new \Exception("SendGrid failed with status {$response->statusCode()}. Backup server also failed: ".$backupException->getMessage());
9001                            }
9002
9003                        }
9004
9005                        if (($response->statusCode() == 202 || $sentWithBackup) && ! config('services.sendgrid.block')) {
9006                            $messageId = null;
9007
9008                            if ($response->headers()) {
9009                                foreach ($response->headers() as $header) {
9010                                    if (str_starts_with(strtolower((string) $header), 'x-message-id:')) {
9011                                        $messageId = trim(substr((string) $header, strpos((string) $header, ':') + 1));
9012                                        break;
9013                                    }
9014                                }
9015                            }
9016
9017                            $sentItems[$result[$i]->company_id][] = $result[$i]->id;
9018
9019                            $comment = 'Se ha enviado la orden por correo electrónico manualmente al cliente el '.date('Y-m-d H:i:s').' por el usuario '.$user->name;
9020                            $result[$i]->last_follow_up_comment = $result[$i]->last_follow_up_comment."\n".$comment;
9021
9022                            TblQuotations::where('id', $result[$i]->id)->update(
9023                                [
9024                                    'last_follow_up_comment' => $result[$i]->last_follow_up_comment,
9025                                    'budget_status_id' => 2,
9026                                    'x_message_id' => $messageId,
9027                                    'x_status' => 'Processing',
9028                                    'updated_by' => $user->name,
9029                                    'updated_at' => date('Y-m-d H:i:s'),
9030                                ]
9031                            );
9032
9033                            $jsonBody = [];
9034
9035                            foreach ($toEmail as $clientEmail) {
9036                                $isValid = $this->isEmailValid($clientEmail);
9037                                $eventStatus = 'processed';
9038                                $eventResponse = '';
9039                                if (! $isValid) {
9040                                    $eventStatus = 'invalid';
9041                                    $eventResponse = 'Invalid email address';
9042                                }
9043
9044                                array_push(
9045                                    $jsonBody,
9046                                    [
9047                                        'email' => $clientEmail,
9048                                        'event' => $eventStatus,
9049                                        'sg_message_id' => $messageId,
9050                                        'smtp-id' => $messageId,
9051                                        'timestamp' => strtotime(date('Y-m-d H:i:s')),
9052                                        'response' => $eventResponse,
9053                                    ]
9054                                );
9055                            }
9056
9057                            TblSendgridWebhook::create(
9058                                [
9059                                    'quotation_id' => $result[$i]->id,
9060                                    'type' => 'sendToClient',
9061                                    'json_body' => json_encode($jsonBody),
9062                                    'x_message_id' => $messageId,
9063                                ]
9064                            );
9065
9066                            Log::channel('email_log')->info("[RS-{$requestSize}] ID:".$result[$i]->id.' - EMAIL MANUALLY SENT');
9067                            $this->addUpdateLog($result[$i]->id, $userId, 'send_email_to_client', null, null, 5);
9068                            QuotationSendRecorder::record((int) $result[$i]->id, QuotationSendRecorder::TITAN_EMAIL, $user->name ?? (string) $userId);
9069                        } else {
9070                            $error = true;
9071                            Log::channel('email_failed_log')->error("[RS-{$requestSize}] ID:".$result[$i]->id.' - '.$response->body());
9072                        }
9073                    }
9074                }
9075            }
9076
9077            // FIRE-1488: persist per-user template overrides for every
9078            // (user, canonical template) where the FE-supplied body differs
9079            // from canonical AND at least one send succeeded for that
9080            // company (sentItems tracks post-SendGrid-202 rows). Runs once
9081            // per company per batch to avoid N duplicate writes. Skipped
9082            // entirely when $data['html'] wasn't sent (cron path never
9083            // supplies it, so $emailTemplates is empty).
9084            //
9085            // FIRE-XXXX (2026-09-04): DISABLED. The FE's Angular Quill editor
9086            // sanitizes the canonical HTML on load (strips tables, base64 <img>,
9087            // inline styles). What it re-sends back is always a stripped copy,
9088            // so saving that as an override silently corrupts the user's
9089            // next-open state — they'd see the sanitized version prefilled.
9090            // Re-enable ONLY after the FE editor stops sanitizing.
9091            if (false && ! empty($emailTemplates)) {
9092                foreach ($sentItems as $companyIdKey => $_) {
9093                    if (! isset($emailTemplates[$companyIdKey]['html'], $emailTemplate[$companyIdKey])) {
9094                        continue;
9095                    }
9096                    if ($emailTemplates[$companyIdKey]['html'] === $emailTemplate[$companyIdKey]->html) {
9097                        continue;
9098                    }
9099                    TblEmailTemplateUserOverride::updateOrCreate(
9100                        [
9101                            'user_id' => (int) $userId,
9102                            'template_id' => (int) $emailTemplate[$companyIdKey]->id,
9103                        ],
9104                        [
9105                            'html' => $emailTemplates[$companyIdKey]['html'],
9106                            'updated_at' => date('Y-m-d H:i:s'),
9107                            'updated_by' => $user->name,
9108                        ]
9109                    );
9110                }
9111            }
9112
9113            $this->update_commercial_numbers($companyId);
9114
9115            // FIRE-1145: was Cache::flush() — send_email_to_client affects quotations list (email status).
9116            ResultCache::forgetDomain('quotations');
9117
9118            foreach ($sentItems as $k => $v) {
9119                $sentItems[$k] = [
9120                    'total' => count($sentItems[$k]),
9121                    'company' => $emailCompany[$k]->name,
9122                    'limit' => $emailCompany[$k]->limit_send,
9123                ];
9124            }
9125
9126            $totalSent = array_values($sentItems);
9127
9128            return response(['message' => 'OK', 'data' => $totalSent]);
9129
9130        } catch (\Exception $e) {
9131            report(AppException::fromException($e, 'SEND_EMAIL_TO_CLIENT_EXCEPTION'));
9132            Log::channel('email_failed_log')->error($e->getMessage());
9133
9134            return response(['message' => 'KO', 'error' => $e->getMessage()]);
9135        }
9136
9137    }
9138
9139    /**
9140     * FIRE-1377: manual follow-up reminder for correo ordinario / WhatsApp
9141     * budgets. These channels have no provider send — the rep chases the client
9142     * by hand and records it here. Mirrors the email follow-up bookkeeping so
9143     * the budget leaves "Requiere seguimiento": pushes last_follow_up_date
9144     * forward N working days and counts toward the per-company reminder limit
9145     * (after which follow-ups stop, exactly as with email). Setting the date to
9146     * "now" would not work — every follow-up filter gates on
9147     * last_follow_up_date < NOW(), so the row would re-appear immediately.
9148     */
9149    public function mark_manual_follow_up(Request $request): ResponseFactory|HttpResponse
9150    {
9151        try {
9152            $data = $request->all();
9153            $id = addslashes((string) ($data['id'] ?? ''));
9154            $sentBy = $data['user'] ?? $data['updated_by'] ?? 'sistema';
9155            $userId = $data['user_id'] ?? null;
9156
9157            $quotation = TblQuotations::where('id', $id)->first();
9158            if (! $quotation) {
9159                return response(['message' => 'KO', 'error' => 'Quotation not found'], 404);
9160            }
9161
9162            // Manual reminders only make sense for the manual channels. Email
9163            // reminders still go through send_email_follow_ups (SendGrid).
9164            if (! in_array($quotation->send_channel, ['correo', 'whatsapp'], true)) {
9165                return response([
9166                    'message' => 'KO',
9167                    'error' => 'El recordatorio manual solo aplica a los canales correo ordinario o WhatsApp',
9168                ], 422);
9169            }
9170            $channel = $quotation->send_channel;
9171
9172            $company = TblCompanies::where('company_id', $quotation->company_id)->first();
9173            $limitReminderEmails = $company->limit_reminder_emails ?? 3;
9174
9175            // Working-days precedence mirrors the email path: per company+budget
9176            // type config first, then the company default, then 10.
9177            $workingDaysN = $company->last_follow_up_date ?? 10;
9178            $lastFollowUp = TblLastFollowUpDate::where('company_id', $quotation->company_id)
9179                ->where('budget_type_id', $quotation->budget_type_id)
9180                ->first();
9181            if ($lastFollowUp != null && $lastFollowUp->last_follow_up_date) {
9182                $workingDaysN = $lastFollowUp->last_follow_up_date;
9183            }
9184
9185            $channelLabel = $channel === 'whatsapp' ? 'WhatsApp' : 'correo ordinario';
9186            $now = date('Y-m-d H:i:s');
9187            $comment = "Recordatorio por {$channelLabel} marcado como enviado el {$now} por usuario {$sentBy}";
9188            $newComment = trim(($quotation->last_follow_up_comment ?? '')."\n".$comment);
9189
9190            $nextDate = date('Y-m-d H:i:s', strtotime("{$workingDaysN} weekdays"));
9191            $totalSentQ = $quotation->total_sent + 1;
9192            $reasonId = $quotation->reason_for_not_following_up_id;
9193            if ($totalSentQ >= $limitReminderEmails) {
9194                $reasonId = 3;
9195                $nextDate = null;
9196            }
9197
9198            TblQuotations::where('id', $id)->update([
9199                'last_follow_up_comment' => $newComment,
9200                'last_follow_up_date' => $nextDate,
9201                'total_sent' => $totalSentQ,
9202                'reason_for_not_following_up_id' => $reasonId,
9203                'updated_by' => $sentBy,
9204                'updated_at' => $now,
9205            ]);
9206
9207            // Per-recipient history — reuse the WhatsApp convention of storing
9208            // the destination (phone / postal address) in the email column.
9209            TblFollowUpLogs::create([
9210                'quotation_id' => $quotation->id,
9211                'email' => $channel === 'whatsapp' ? $quotation->phone_number : $quotation->direccion_postal,
9212                'sent_by' => $sentBy,
9213                'status' => 'OK',
9214            ]);
9215
9216            $this->addUpdateLog($quotation->id, $userId, 'send_email_follow_up', null, null, 5);
9217
9218            ResultCache::forgetDomain('quotations');
9219
9220            return response([
9221                'message' => 'OK',
9222                'last_follow_up_date' => $nextDate,
9223                'total_sent' => $totalSentQ,
9224            ]);
9225        } catch (\Exception $e) {
9226            report(AppException::fromException($e, 'MARK_MANUAL_FOLLOW_UP_EXCEPTION'));
9227
9228            return response(['message' => 'KO', 'error' => $e->getMessage()]);
9229        }
9230    }
9231
9232    public function send_email_follow_ups(Request $request, $automaticSendLimit = null): ResponseFactory|HttpResponse
9233    {
9234
9235        $currentQuotationId = null;
9236        ini_set('max_execution_time', 0);
9237
9238        try {
9239
9240            $data = $request->all();
9241
9242            $startedAt = date('Y-m-d H:i:s');
9243            $toEmail = '';
9244            $userId = addslashes((string) $data['user_id']);
9245            $companyId = addslashes((string) $data['company_id']);
9246            $emailTemplateId = $data['email_template_id'];
9247            unset($data['email_template_id']);
9248
9249            $sendChannel = isset($data['send_channel']) && $data['send_channel'] === 'whatsapp' ? 'whatsapp' : 'email';
9250
9251            $emailTemplates = [];
9252
9253            if (isset($data['html']) && ! empty($data['html'])) {
9254                $emailTemplates = array_column($data['html'], null, 'id');
9255            }
9256
9257            $emailTemplate = TblEmailConfiguration::whereIn('id', $emailTemplateId)->get()->keyBy('company_id');
9258
9259            $limit = 0;
9260
9261            $blockedDomains = [];
9262            $workingDays = 10;
9263            $limitReminderEmails = 3;
9264            $emailCompany = [];
9265
9266            $result = [];
9267
9268            if ($companyId == 0) {
9269                $indexes = $emailTemplate->keys();
9270
9271                $emailCompany = TblCompanies::whereIn('company_id', $indexes)->get()->keyBy('company_id');
9272
9273                foreach ($emailCompany as $item) {
9274                    $limit = 20;
9275
9276                    $r = new Request([
9277                        'filterModel' => $data['filterModel'] ?? [],
9278                        'sortModel' => $data['sortModel'] ?? [],
9279                        'start' => 0,
9280                        'end' => 999999999,
9281                        'company_id' => $data['company_id'],
9282                        'user_id' => $data['user_id'],
9283                        'ids' => $data['ids'],
9284                        'searchText' => $data['searchText'] ?? '',
9285                        'ids_not_in' => $data['ids_not_in'],
9286                        // Orders-table data source, scoped to the follow-up
9287                        // bucket (replaces list_quotations' last_follow_up_date=1).
9288                        'is_send_follow_up' => 1,
9289                    ]);
9290
9291                    if ($item->limit_send != null) {
9292                        $limit = $item->limit_send;
9293                    }
9294
9295                    $listQuotations = $this->list_orders_table($r);
9296                    $d = $listQuotations->original['data'];
9297                    if ($automaticSendLimit != null) {
9298                        $limit = $automaticSendLimit;
9299                    }
9300
9301                    $l = 0;
9302                    for ($i = 0; $i < count($d); $i++) {
9303                        $channelOk = $sendChannel === 'whatsapp'
9304                            // Keep rows with a missing/empty phone so they're
9305                            // counted as invalid-phone errors in the send loop
9306                            // instead of being silently filtered out here.
9307                            ? true
9308                            : $d[$i]->email != null;
9309
9310                        if ($channelOk
9311                            && $d[$i]->budget_type_id != null
9312                            && $d[$i]->budget_status_id == 2
9313                            && $d[$i]->reason_for_not_following_up_id == null
9314                            && $d[$i]->total_sent < $limitReminderEmails
9315                            && $d[$i]->last_follow_up_date != null
9316                            && $d[$i]->last_follow_up_date < date('Y-m-d H:i:s')
9317                            && $d[$i]->last_follow_up_date > 0
9318                            // A follow-up chases a budget the client already
9319                            // has; if its approval is unresolved it should not
9320                            // have gone out at all, so do not chase it either.
9321                            && ! $this->isRowPendingApproval($d[$i])
9322                            && $item->company_id == $d[$i]->company_id
9323                        ) {
9324
9325                            if ($l == $limit) {
9326                                break;
9327                            }
9328                            array_push($result, $d[$i]);
9329                            $l++;
9330                        }
9331                    }
9332
9333                }
9334            } else {
9335
9336                $emailCompany = TblCompanies::where('company_id', $companyId)->get()->keyBy('company_id');
9337                $workingDays = $emailCompany[$companyId]->last_follow_up_date ?? 10;
9338                $limitReminderEmails = $emailCompany[$companyId]->limit_reminder_emails ?? 3;
9339
9340                if ($emailCompany[$companyId]->limit_send != null) {
9341                    $limit = $emailCompany[$companyId]->limit_send;
9342                }
9343
9344                $r = new Request([
9345                    'filterModel' => $data['filterModel'] ?? [],
9346                    'sortModel' => $data['sortModel'] ?? [],
9347                    'start' => 0,
9348                    'end' => 999999999,
9349                    'company_id' => $data['company_id'],
9350                    'user_id' => $data['user_id'],
9351                    'ids' => $data['ids'],
9352                    'searchText' => $data['searchText'] ?? '',
9353                    'ids_not_in' => $data['ids_not_in'],
9354                    // Orders-table data source, scoped to the follow-up bucket
9355                    // (replaces list_quotations' last_follow_up_date=1).
9356                    'is_send_follow_up' => 1,
9357                ]);
9358
9359                $listQuotations = $this->list_orders_table($r);
9360                $d = $listQuotations->original['data'];
9361
9362                if ($automaticSendLimit != null) {
9363                    $limit = $automaticSendLimit;
9364                }
9365
9366                $l = 0;
9367                for ($i = 0; $i < count($d); $i++) {
9368                    $channelOk = $sendChannel === 'whatsapp'
9369                        // Keep rows with a missing/empty phone so they're
9370                        // counted as invalid-phone errors in the send loop
9371                        // instead of being silently filtered out here.
9372                        ? true
9373                        : $d[$i]->email != null;
9374
9375                    if ($channelOk
9376                        && $d[$i]->budget_status_id == 2
9377                        && $d[$i]->reason_for_not_following_up_id == null
9378                        && $d[$i]->total_sent < $limitReminderEmails
9379                        && $d[$i]->last_follow_up_date != null
9380                        && $d[$i]->last_follow_up_date < date('Y-m-d H:i:s')
9381                        && $d[$i]->last_follow_up_date > 0
9382                        // See the multi-company branch above: an unresolved
9383                        // approval blocks the chase as well as the send.
9384                        && ! $this->isRowPendingApproval($d[$i])
9385                    ) {
9386                        if ($l == $limit) {
9387                            break;
9388                        }
9389                        array_push($result, $d[$i]);
9390                        $l++;
9391                    }
9392                }
9393            }
9394
9395            if (count($result) == 0) {
9396                if ($sendChannel === 'whatsapp') {
9397                    return response([
9398                        'message' => 'OK',
9399                        'channel' => 'whatsapp',
9400                        'wa_total_sent' => 0,
9401                        'wa_total_invalid_phone' => 0,
9402                        'wa_invalid_phone_ids' => [],
9403                        'wa_total_error' => 0,
9404                    ]);
9405                }
9406
9407                // Always include `data` so the client's forEach never hits
9408                // undefined (this empty-result OK was the original crash source).
9409                return response(['message' => 'OK', 'data' => []]);
9410            }
9411
9412            $user = TblUsers::where('id', $userId)->first();
9413            $error = false;
9414
9415            $sentBy = $user->name;
9416
9417            $availableParameters = [
9418                'quote_id',
9419                'company_id',
9420                'client',
9421                'client_type',
9422                'phone_number',
9423                'email',
9424                'issue_date',
9425                'request_date',
9426                'duration',
9427                'invoice_number',
9428                'type',
9429                'acceptance_date',
9430                'status',
9431                'source',
9432                'amount',
9433                'reason_for_not_following_up',
9434                'last_follow_up_date',
9435                'last_follow_up_comment',
9436                'reason_for_rejection_id',
9437                'reason_for_rejection',
9438                'commercial',
9439                'created_at',
9440                'created_by',
9441                'updated_at',
9442                'updated_by',
9443            ];
9444
9445            $dateParameters = [
9446                'issue_date',
9447                'request_date',
9448                'acceptance_date',
9449                'last_follow_up_date',
9450                'created_at',
9451                'updated_at',
9452            ];
9453
9454            if ($this->locale == 'es') {
9455                setlocale(LC_ALL, 'es_ES', 'Spanish_Spain', 'Spanish');
9456            }
9457
9458            $totalSent = 0;
9459            $totalSentIds = [];
9460            $totalFailedIds = [];
9461            $totalErrorIds = [];
9462            // WhatsApp only: quotations skipped/failed because the phone number
9463            // was missing or rejected as invalid. Surfaced in the response so
9464            // the user sees "X sent, Y failed (invalid phone)".
9465            $totalInvalidPhoneIds = [];
9466            $currentQuotationId = null;
9467
9468            $sentItems = [];
9469            $missingTemplateCompanies = [];
9470
9471            for ($i = 0; $i < count($result); $i++) {
9472                // FIRE-1930: skip the whole iteration if the region's
9473                // client_emails switch is off. Same reasoning as in
9474                // send_email_to_client — we do not spend template work
9475                // or S3 attachment reads for gated regions.
9476                if (! SendgridDispatcher::isAllowed(
9477                    SendgridDispatcher::BUCKET_CLIENT,
9478                    (int) $result[$i]->company_id,
9479                )) {
9480                    continue;
9481                }
9482
9483                // PHP-LARAVEL-5G "Undefined array key 18": no template chosen
9484                // for this quote's company. Skip it instead of aborting the
9485                // rest of the batch.
9486                if (! isset($emailTemplate[$result[$i]->company_id])) {
9487                    $this->warnMissingEmailTemplate($missingTemplateCompanies, (int) $result[$i]->company_id, 'send_email_follow_ups');
9488
9489                    continue;
9490                }
9491
9492                $budgetTypeId = $result[$i]->budget_type_id;
9493                $currentQuotationId = $result[$i]->quote_id;
9494                // FIRE-1901: mirrors send_email_to_client — see resolveEmailBody().
9495                $body = $this->resolveEmailBody(
9496                    $emailTemplates[$result[$i]->company_id] ?? null,
9497                    $emailTemplate[$result[$i]->company_id]->html,
9498                );
9499                $subject = $emailTemplate[$result[$i]->company_id]->subject;
9500                // FIRE-1539: for follow-ups on quotations whose original commercial
9501                // has been inactivated (statuses 2/17 in the reassignment split),
9502                // follow_up_commercial holds the replacement. The original
9503                // `commercial` column is preserved as sender-of-record for
9504                // history.
9505                $commercialUser = $result[$i]->follow_up_commercial ?? $result[$i]->commercial;
9506
9507                $blockedDomains = TblBlockedDomains::where('company_id', $result[$i]->company_id)->pluck('domain')->toArray();
9508
9509                if (config('services.sendgrid.staging')) {
9510                    $toEmail = $user->email;
9511                } else {
9512                    $toEmail = $result[$i]->email;
9513                }
9514
9515                preg_match_all('/{{(.*?)}}/', (string) $body, $matches);
9516
9517                $parameters = $matches[1];
9518
9519                foreach ($parameters as $parameter) {
9520
9521                    if (in_array($parameter, $dateParameters)) {
9522                        if ($result[$i]->{$parameter}) {
9523                            $result[$i]->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result[$i]->{$parameter})));
9524                        }
9525                    }
9526
9527                    if (in_array($parameter, $availableParameters)) {
9528                        $body = str_replace('{{'.$parameter.'}}', $result[$i]->{$parameter}, $body);
9529                    }
9530                }
9531
9532                preg_match_all('/{{(.*?)}}/', (string) $subject, $matches);
9533
9534                $parameters = $matches[1];
9535
9536                foreach ($parameters as $parameter) {
9537
9538                    if (in_array($parameter, $dateParameters)) {
9539                        if ($result[$i]->{$parameter}) {
9540                            $result[$i]->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result[$i]->{$parameter})));
9541                        }
9542                    }
9543
9544                    if (in_array($parameter, $availableParameters)) {
9545                        $subject = str_replace('{{'.$parameter.'}}', $result[$i]->{$parameter}, $subject);
9546                    }
9547                }
9548
9549                $email = new Mail;
9550
9551                $templateFiles = TblEmailFiles::where('email_template_id', $emailTemplate[$result[$i]->company_id]->id)->orderBy('order', 'asc')->get();
9552
9553                foreach ($templateFiles as $item) {
9554                    $f = storage_path('app/public/uploads/'.$item->filename);
9555
9556                    if (file_exists($f)) {
9557                        $imgpath = file_get_contents($f);
9558                        $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
9559                        $mimeType = mime_content_type($f);
9560
9561                        $email->addAttachment(
9562                            $imgpath,
9563                            $mimeType,
9564                            str_replace(' ', '', $item->original_name),
9565                            'inline',
9566                            str_replace(' ', '', $item->original_name),
9567                        );
9568
9569                        // An image the template already places itself (src="cid:<name>") is not
9570                        // repeated in the logo strip under the body.
9571                        if (! str_contains($body, 'cid:'.$item->original_name)) {
9572                            $body .= "<img src='cid:{$item->original_name}' style='height: 45px; padding-right: 6px' />";
9573                        }
9574                    } else {
9575                        Log::channel('email_failed_log')->error('File not found: '.$f);
9576                    }
9577                }
9578
9579                $html = '<!DOCTYPE html>';
9580                $html .= '<html>';
9581                $html .= '<head>';
9582                $html .= '<meta charset="UTF-8">';
9583                $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
9584                $html .= '</head>';
9585                $html .= '<body>';
9586                $html .= $body;
9587                $html .= '</body>';
9588                $html .= '</html>';
9589
9590                if ($automaticSendLimit != null) {
9591                    $sentBy = 'System';
9592                }
9593
9594                if ($sendChannel === 'whatsapp') {
9595                    if (empty($result[$i]->phone_number)) {
9596                        // No phone at all → count as an invalid-phone failure so
9597                        // the response can report it instead of silently skipping.
9598                        $totalInvalidPhoneIds[] = $result[$i]->id;
9599                        TblFollowUpLogs::create([
9600                            'quotation_id' => $result[$i]->id,
9601                            'email' => (string) $result[$i]->phone_number,
9602                            'sent_by' => $sentBy,
9603                            'status' => 'Teléfono no válido',
9604                        ]);
9605
9606                        continue;
9607                    }
9608
9609                    $wa = app(WhatsAppService::class)->send($result[$i]->phone_number, $body);
9610
9611                    if (! $wa['ok']) {
9612                        // Distinguish invalid-phone failures (reported back as a
9613                        // count, NOT flagging the whole batch) from genuine send
9614                        // errors. normalizePhone() returns "Invalid phone"; Twilio
9615                        // rejects bad numbers with 21211 / "not a valid phone number".
9616                        $errText = strtolower((string) $wa['error']);
9617                        $isInvalidPhone = str_contains($errText, 'invalid phone')
9618                            || str_contains($errText, 'not a valid phone')
9619                            || str_contains($errText, '21211');
9620
9621                        if ($isInvalidPhone) {
9622                            $totalInvalidPhoneIds[] = $result[$i]->id;
9623                        } else {
9624                            $error = true;
9625                            $totalErrorIds[] = $result[$i]->id;
9626                        }
9627
9628                        Log::channel('email_failed_log')->error('ID:'.$result[$i]->id.' - WhatsApp - '.$wa['error']);
9629
9630                        // Parity with the email path's failure branch: record the
9631                        // attempt against the recipient (phone in the email column).
9632                        TblFollowUpLogs::create([
9633                            'quotation_id' => $result[$i]->id,
9634                            'email' => $result[$i]->phone_number,
9635                            'sent_by' => $sentBy,
9636                            'status' => $isInvalidPhone ? 'Teléfono no válido' : $wa['error'],
9637                        ]);
9638
9639                        continue;
9640                    }
9641
9642                    $lastFollowUp = TblLastFollowUpDate::where('company_id', $companyId)
9643                        ->where('budget_type_id', $budgetTypeId)
9644                        ->first();
9645                    $workingDaysN = $workingDays;
9646                    if ($companyId == 0 && isset($emailCompany[$result[$i]->company_id])) {
9647                        $workingDaysN = $emailCompany[$result[$i]->company_id]->last_follow_up_date ?? 10;
9648                    }
9649                    if ($lastFollowUp != null && $lastFollowUp->last_follow_up_date) {
9650                        $workingDaysN = $lastFollowUp->last_follow_up_date;
9651                    }
9652
9653                    $comment = 'WhatsApp automático enviado el '.date('Y-m-d H:i:s').' por usuario '.$sentBy;
9654                    $result[$i]->last_follow_up_comment = $result[$i]->last_follow_up_comment."\n".$comment;
9655                    $result[$i]->last_follow_up_date = date('Y-m-d H:i:s', strtotime("{$workingDaysN} weekdays"));
9656                    $totalSentQ = $result[$i]->total_sent + 1;
9657
9658                    if ($totalSentQ >= $limitReminderEmails) {
9659                        $result[$i]->reason_for_not_following_up_id = 3;
9660                        $result[$i]->last_follow_up_date = null;
9661                    }
9662
9663                    TblQuotations::where('id', $result[$i]->id)->update([
9664                        'last_follow_up_comment' => $result[$i]->last_follow_up_comment,
9665                        'last_follow_up_date' => $result[$i]->last_follow_up_date,
9666                        'total_sent' => $totalSentQ,
9667                        'wa_y_message_id' => $wa['sid'],
9668                        // No delivery callback wired — a successful hand-off to
9669                        // Twilio is the terminal state (mirrors email post-send).
9670                        'wa_y_status' => 'delivered',
9671                        'reason_for_not_following_up_id' => $result[$i]->reason_for_not_following_up_id,
9672                        'updated_by' => $sentBy,
9673                        'updated_at' => date('Y-m-d H:i:s'),
9674                    ]);
9675
9676                    // Parity with the email follow-up: per-recipient history
9677                    // (phone in the email column) alongside the activity log.
9678                    TblFollowUpLogs::create([
9679                        'quotation_id' => $result[$i]->id,
9680                        'email' => $result[$i]->phone_number,
9681                        'sent_by' => $sentBy,
9682                        'status' => 'OK',
9683                    ]);
9684
9685                    $totalSent++;
9686                    $totalSentIds[] = $result[$i]->id;
9687                    $sentItems[$result[$i]->company_id][] = $result[$i]->id;
9688                    $this->addUpdateLog($result[$i]->id, $userId, 'send_email_follow_up', null, null, 5);
9689
9690                    continue;
9691                }
9692
9693                if ($toEmail != null) {
9694
9695                    $toEmail = explode(',', (string) $toEmail);
9696                    $toEmail = array_map(trim(...), $toEmail);
9697
9698                    $companyEmail = null;
9699
9700                    $queryUsers = "SELECT sender_email AS from_email, `name` AS from_name FROM tbl_users WHERE sender_enabled = 1 AND response_id IS NOT NULL AND verified = 1 AND `name` = '{$commercialUser}'";
9701                    $commercialEmail = DB::select($queryUsers);
9702
9703                    if (count($commercialEmail) > 0) {
9704                        $companyEmail = $commercialEmail[0];
9705                    } else {
9706                        if ($emailTemplate[$result[$i]->company_id]->from_id != null) {
9707                            $companyEmail = TblCompanyEmails::where('id', $emailTemplate[$result[$i]->company_id]->from_id)->first();
9708                        } else {
9709                            $companyEmail = TblCompanyEmails::where('is_active', 1)->where('verified', 1)->where('company_id', $result[$i]->company_id)->first();
9710                        }
9711                    }
9712
9713                    if (! $companyEmail) {
9714                        return response(['message' => 'KO', 'error' => __('language.no_active_verified_sender')]);
9715                    }
9716
9717                    $ccBcc = TblCcBcc::where('company_id', $result[$i]->company_id)->get();
9718
9719                    $email->setFrom($companyEmail->from_email, $companyEmail->from_name);
9720                    $email->setSubject($subject);
9721
9722                    $s = 0;
9723                    $addTo = [];
9724                    foreach ($toEmail as $clientEmail) {
9725                        $isValid = $this->isEmailValid($clientEmail);
9726                        if ($isValid) {
9727                            $domain = substr($clientEmail, strpos($clientEmail, '@') + 1);
9728
9729                            if (! in_array($domain, $blockedDomains)) {
9730                                $email->addTo($clientEmail);
9731                                array_push($addTo, $clientEmail);
9732                                $s++;
9733                            }
9734                        } else {
9735                            TblFollowUpLogs::create(
9736                                [
9737                                    'quotation_id' => $result[$i]->id,
9738                                    'email' => $clientEmail,
9739                                    'sent_by' => $sentBy,
9740                                    'status' => 'Invalid email',
9741                                ]
9742                            );
9743                        }
9744                    }
9745
9746                    if ($s == 0) {
9747                        array_push($totalFailedIds, $result[$i]->id);
9748                        Log::channel('email_failed_log')->error($s.'ID:'.$result[$i]->id.' - '.json_encode($toEmail));
9749
9750                        continue;
9751                    }
9752
9753                    if (! config('services.sendgrid.staging')) {
9754                        if (count($ccBcc) > 0) {
9755                            foreach ($ccBcc as $data) {
9756                                if (! in_array($data->email, $toEmail)) {
9757                                    $email->addBcc($data->email);
9758                                }
9759                            }
9760                        }
9761                    }
9762
9763                    $email->addContent('text/html', $html);
9764
9765                    $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
9766
9767                    $files = TblFiles::where('quotation_id', $result[$i]->id)->where('is_internal', null)->get();
9768                    $requestSize = $this->calculateEmailRequestSize($email);
9769
9770                    foreach ($files as $key => $value) {
9771                        if ($files[$key]->filename && Storage::disk('s3')->exists('uploads/'.$files[$key]->filename)) {
9772
9773                            $fileContent = Storage::disk('s3')->get('uploads/'.$files[$key]->filename);
9774                            $fileSize = strlen((string) $fileContent) / 1048576;
9775                            $fileSize = (int) ceil($fileSize);
9776
9777                            $originalName = $files[$key]->original_name ?: basename((string) $files[$key]->filename);
9778                        } elseif ($files[$key]->file) {
9779                            $fileContent = $files[$key]->file;
9780
9781                            if (is_string($fileContent) && base64_decode($fileContent, true)) {
9782                                $fileContent = base64_decode($fileContent);
9783                            }
9784
9785                            $fileSize = strlen((string) $fileContent) / 1048576;
9786                            $fileSize = (int) ceil($fileSize);
9787
9788                            $originalName = $files[$key]->original_name ?: ($files[$key]->getAttribute('file_name') ?: 'file');
9789                        } else {
9790                            continue;
9791                        }
9792
9793                        if ($fileSize > 0) {
9794                            if ($requestSize + $fileSize < 25) {
9795                                $attachment = new Attachment;
9796                                $attachment->setFilename($originalName);
9797                                $attachment->setDisposition('attachment');
9798
9799                                $attachment->setContent(base64_encode((string) $fileContent));
9800
9801                                if ($files[$key]->mime_type) {
9802                                    $attachment->setType($files[$key]->mime_type);
9803                                }
9804
9805                                $email->addAttachment($attachment);
9806                                $requestSize = $this->calculateEmailRequestSize($email);
9807                            } else {
9808                                Log::warning('File omitted due to size limit: '.$originalName);
9809                            }
9810                        }
9811                    }
9812
9813                    $sentWithBackup = false;
9814
9815                    try {
9816                        $response = $sendgrid->send($email);
9817                        SendgridLogger::log($email, $response);
9818                    } catch (\Throwable $sendException) {
9819                        SendgridLogger::logException($email, $sendException);
9820                        throw $sendException;
9821                    }
9822
9823                    if (config('services.sendgrid.block') === true) {
9824
9825                        Log::warning("SendGrid failed with status {$response->statusCode()}. Initiating Failover...");
9826                        try {
9827                            \Illuminate\Support\Facades\Mail::mailer('smtp_backup')->send([], [], function ($message) use ($html, $companyEmail, $toEmail, $subject, $files, $user, $ccBcc): void {
9828                                $message->from($companyEmail->from_email, $companyEmail->from_name)
9829                                    ->to($toEmail)
9830                                    ->subject($subject);
9831
9832                                $message->html($html);
9833
9834                                $message->cc($user->email);
9835
9836                                foreach ($ccBcc as $bcc) {
9837                                    $message->bcc($bcc->email);
9838                                }
9839
9840                                foreach ($files as $file) {
9841                                    if (Storage::disk('s3')->exists('uploads/'.$file->filename)) {
9842                                        $content = Storage::disk('s3')->get('uploads/'.$file->filename);
9843                                        $message->attachData($content, $file->original_name);
9844                                    } elseif ($file->file) {
9845                                        $content = $file->file;
9846                                        if (is_string($content) && base64_decode($content, true)) {
9847                                            $content = base64_decode($content);
9848                                        }
9849                                        $message->attachData($content, $file->original_name ?: 'archivo.pdf');
9850                                    }
9851                                }
9852                            });
9853
9854                            $sentWithBackup = true;
9855                        } catch (\Exception $backupException) {
9856                            $sentWithBackup = false;
9857                            Log::error('Backup server also failed: '.$backupException->getMessage());
9858                        }
9859
9860                        if (! $sentWithBackup) {
9861                            throw new \Exception("SendGrid failed with status {$response->statusCode()}. Backup server also failed: ".$backupException->getMessage());
9862                        }
9863
9864                    }
9865
9866                    if (($response->statusCode() == 202 || $sentWithBackup) && ! config('services.sendgrid.block')) {
9867
9868                        $messageId = null;
9869
9870                        foreach ($response->headers() as $header) {
9871                            if (str_starts_with(strtolower((string) $header), 'x-message-id:')) {
9872                                $messageId = trim(substr((string) $header, strpos((string) $header, ':') + 1));
9873                                break;
9874                            }
9875                        }
9876
9877                        $lastFollowUp = TblLastFollowUpDate::where('company_id', $companyId)->where('budget_type_id', $budgetTypeId)->first();
9878                        $workingDaysN = $workingDays;
9879
9880                        if ($companyId == 0) {
9881                            $workingDaysN = $emailCompany[$result[$i]->company_id]->last_follow_up_date ?? 10;
9882                        }
9883
9884                        if ($lastFollowUp != null) {
9885                            if ($lastFollowUp->last_follow_up_date) {
9886                                $workingDaysN = $lastFollowUp->last_follow_up_date;
9887                            }
9888                        }
9889
9890                        $comment = 'Email automático enviado el '.date('Y-m-d H:i:s').' por usuario '.$sentBy;
9891                        $result[$i]->last_follow_up_comment = $result[$i]->last_follow_up_comment."\n".$comment;
9892                        $date = strtotime("{$workingDaysN} weekdays");
9893                        $result[$i]->last_follow_up_date = date('Y-m-d H:i:s', $date);
9894                        $totalSentQ = $result[$i]->total_sent + 1;
9895
9896                        array_push($totalSentIds, $result[$i]->id);
9897                        $sentItems[$result[$i]->company_id][] = $result[$i]->id;
9898
9899                        foreach ($addTo as $addToEmail) {
9900                            TblFollowUpLogs::create(
9901                                [
9902                                    'quotation_id' => $result[$i]->id,
9903                                    'email' => $addToEmail,
9904                                    'sent_by' => $sentBy,
9905                                    'status' => 'OK',
9906                                ]
9907                            );
9908                            $this->addUpdateLog($result[$i]->id, $userId, 'send_email_follow_up', null, null, 5);
9909                        }
9910
9911                        if ($totalSentQ >= $limitReminderEmails) {
9912                            $result[$i]->reason_for_not_following_up_id = 3;
9913                            $result[$i]->last_follow_up_date = null;
9914                        }
9915
9916                        TblQuotations::where('id', $result[$i]->id)->update(
9917                            [
9918                                'last_follow_up_comment' => $result[$i]->last_follow_up_comment,
9919                                'last_follow_up_date' => $result[$i]->last_follow_up_date,
9920                                'total_sent' => $result[$i]->total_sent + 1,
9921                                'y_message_id' => $messageId,
9922                                'y_status' => 'Processing',
9923                                'reason_for_not_following_up_id' => $result[$i]->reason_for_not_following_up_id,
9924                                'updated_by' => $sentBy,
9925                                'updated_at' => date('Y-m-d H:i:s'),
9926                            ]
9927                        );
9928
9929                        $jsonBody = [];
9930
9931                        foreach ($toEmail as $clientEmail) {
9932                            $isValid = $this->isEmailValid($clientEmail);
9933                            $eventStatus = 'processed';
9934                            $eventResponse = '';
9935                            if (! $isValid) {
9936                                $eventStatus = 'invalid';
9937                                $eventResponse = 'Invalid email address';
9938                            }
9939
9940                            array_push(
9941                                $jsonBody,
9942                                [
9943                                    'email' => $clientEmail,
9944                                    'event' => $eventStatus,
9945                                    'sg_message_id' => $messageId,
9946                                    'smtp-id' => $messageId,
9947                                    'timestamp' => strtotime(date('Y-m-d H:i:s')),
9948                                    'response' => $eventResponse,
9949                                ]
9950                            );
9951                        }
9952
9953                        TblSendgridWebhook::create(
9954                            [
9955                                'quotation_id' => $result[$i]->id,
9956                                'type' => 'followUps',
9957                                'json_body' => json_encode($jsonBody),
9958                                'x_message_id' => $messageId,
9959                            ]
9960                        );
9961
9962                        Log::channel('email_log')->info("[RS-{$requestSize}] ID:".$result[$i]->id.' - EMAIL SENT');
9963                        $totalSent++;
9964                        $workingDays = 10;
9965                    } else {
9966                        $error = true;
9967                        array_push($totalErrorIds, $result[$i]->id);
9968                        Log::channel('email_failed_log')->error("[RS-{$requestSize}] ID:".$result[$i]->id.' - '.$response->body());
9969
9970                        foreach ($addTo as $addToEmail) {
9971                            TblFollowUpLogs::create(
9972                                [
9973                                    'quotation_id' => $result[$i]->id,
9974                                    'email' => $addToEmail,
9975                                    'sent_by' => $sentBy,
9976                                    'status' => $response->body(),
9977                                ]
9978                            );
9979                        }
9980                    }
9981
9982                    $body = '';
9983                    $subject = '';
9984                }
9985            }
9986
9987            // FIRE-1488: persist per-user template overrides for every
9988            // (user, canonical template) where the FE-supplied body differs
9989            // from canonical AND at least one row succeeded for that
9990            // company. Skipped when $data['html'] is absent (cron path),
9991            // so the scheduled follow-up job never triggers this write.
9992            //
9993            // FIRE-XXXX (2026-09-04): DISABLED — see rationale in
9994            // send_email_to_client (~L8464). Angular Quill sanitizes on load,
9995            // so FE-sent HTML is always a stripped copy of canonical. Saving
9996            // it silently corrupts the user's next-open state.
9997            if (false && ! empty($emailTemplates) && $automaticSendLimit === null) {
9998                foreach ($sentItems as $companyIdKey => $_) {
9999                    if (! isset($emailTemplates[$companyIdKey]['html'], $emailTemplate[$companyIdKey])) {
10000                        continue;
10001                    }
10002                    if ($emailTemplates[$companyIdKey]['html'] === $emailTemplate[$companyIdKey]->html) {
10003                        continue;
10004                    }
10005                    TblEmailTemplateUserOverride::updateOrCreate(
10006                        [
10007                            'user_id' => (int) $userId,
10008                            'template_id' => (int) $emailTemplate[$companyIdKey]->id,
10009                        ],
10010                        [
10011                            'html' => $emailTemplates[$companyIdKey]['html'],
10012                            'updated_at' => date('Y-m-d H:i:s'),
10013                            'updated_by' => $user->name,
10014                        ]
10015                    );
10016                }
10017            }
10018
10019            // FIRE-1145: was Cache::flush() — send_email_follow_ups updates email status visible in list_quotations.
10020            ResultCache::forgetDomain('quotations');
10021
10022            Log::channel('send_email_follow_ups')->info(
10023                json_encode(
10024                    [
10025                        'success' => $totalSentIds,
10026                        'failed' => $totalFailedIds,
10027                        'error' => $totalErrorIds,
10028                    ]
10029                )
10030            );
10031
10032            $this->update_commercial_numbers($companyId);
10033
10034            // WhatsApp follow-up: report per-batch totals (sent + invalid-phone
10035            // failures) instead of the per-company email totals. Invalid phones
10036            // do NOT make the whole batch fail — partial success is reported.
10037            if ($sendChannel === 'whatsapp') {
10038                return response([
10039                    'message' => 'OK',
10040                    'channel' => 'whatsapp',
10041                    'wa_total_sent' => $totalSent,
10042                    'wa_total_invalid_phone' => count($totalInvalidPhoneIds),
10043                    'wa_invalid_phone_ids' => array_values($totalInvalidPhoneIds),
10044                    'wa_total_error' => count($totalErrorIds),
10045                ]);
10046            }
10047
10048            if ($error) {
10049                return response(['message' => 'KO']);
10050            } else {
10051
10052                if ($automaticSendLimit != null) {
10053                    TblOrdersUpdateLogs::create(
10054                        [
10055                            'company_id' => $companyId,
10056                            'to_process' => 'Orders',
10057                            'status' => 'success',
10058                            'follow_ups_affected_rows' => $totalSent,
10059                            'processed_by' => $sentBy,
10060                            'started_at' => $startedAt,
10061                            'ended_at' => date('Y-m-d H:i:s'),
10062                        ]
10063                    );
10064                }
10065
10066                foreach ($sentItems as $k => $v) {
10067                    $sentItems[$k] = [
10068                        'total' => count($sentItems[$k]),
10069                        'company' => $emailCompany[$k]->name,
10070                        'limit' => $emailCompany[$k]->limit_send,
10071                    ];
10072                }
10073
10074                $totalSent = array_values($sentItems);
10075
10076                return response(['message' => 'OK', 'data' => $totalSent]);
10077            }
10078
10079        } catch (\Throwable $e) {
10080            report(AppException::fromException($e, 'SEND_EMAIL_FOLLOW_UPS_EXCEPTION'));
10081            Log::channel('email_failed_log')->error($e->getMessage());
10082
10083            return response(['message' => 'KO', 'error' => $e->getMessage(), 'quotation_id' => $currentQuotationId]);
10084        }
10085    }
10086
10087    public function create_sender_identity(Request $request): ResponseFactory|HttpResponse
10088    {
10089
10090        $data = $request->all();
10091        try {
10092
10093            $sData = $data;
10094            $companyId = $data['company_id'];
10095            $createdBy = $data['created_by'];
10096            unset($data['company_id']);
10097            unset($data['created_by']);
10098
10099            $sender = TblCompanyEmails::where('from_email', $data['from_email'])->where('verified', 1)->count();
10100
10101            if ($sender > 0) {
10102                TblCompanyEmails::create($sData);
10103
10104                return response(['message' => 'OK', 'data' => $data, 'is_verified' => 'yes']);
10105            }
10106
10107            $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
10108            $data['reply_to'] = $data['from_email'];
10109            $data['reply_to_name'] = $data['from_name'];
10110            $requestBody = $data;
10111            $error = false;
10112
10113            // @phpstan-ignore-next-line
10114            $response = $sendgrid->client->verified_senders()->post($requestBody);
10115
10116            if ($response->statusCode() == 201) {
10117                $x = json_decode((string) $response->body());
10118
10119                $data['company_id'] = $companyId;
10120                $data['created_by'] = $createdBy;
10121                $data['response_id'] = $x->id;
10122                TblCompanyEmails::create($data);
10123                Log::channel('email_log')->info('EMAIL: '.$data['from_email'].' - VERIFICATION SENT');
10124            } else {
10125                $error = true;
10126                Log::channel('email_log')->error('REQUEST BODY: - '.$response->body());
10127            }
10128
10129            $response = json_decode((string) $response->body());
10130
10131            if ($error) {
10132                if ($response->errors[0]->message == 'already exists' && $response->errors[0]->field == 'from_email') {
10133                    TblCompanyEmails::create($sData);
10134
10135                    return response(['message' => 'OK', 'data' => $data, 'is_verified' => 'yes']);
10136                }
10137
10138                $errMessage = $response->errors[0]->field.': '.$response->errors[0]->message;
10139
10140                return response(['message' => 'KO', 'error' => $errMessage]);
10141            } else {
10142                return response(['message' => 'OK', 'data' => $response, 'is_verified' => 'no']);
10143            }
10144
10145        } catch (\Exception $e) {
10146            report(AppException::fromException($e, 'CREATE_SENDER_IDENTITY_EXCEPTION'));
10147            Log::channel('email_log')->error('EMAIL:'.$data['from_email'].' - '.$e->getMessage());
10148
10149            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10150        }
10151    }
10152
10153    public function get_sender_identity($companyId): ResponseFactory|HttpResponse
10154    {
10155
10156        try {
10157
10158            $companyId = addslashes((string) $companyId);
10159
10160            $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
10161
10162            // @phpstan-ignore-next-line
10163            $response = $sendgrid->client->verified_senders()->get();
10164
10165            if ($response->statusCode() == 200) {
10166                $x = json_decode((string) $response->body())->results;
10167
10168                foreach ($x as $item) {
10169                    TblCompanyEmails::where('from_email', $item->from_email)->update([
10170                        'verified' => $item->verified,
10171                        'reply_to' => $item->reply_to,
10172                        'response_id' => $item->id,
10173                    ]);
10174                }
10175            }
10176
10177            $companyEmails = TblCompanyEmails::where('company_id', $companyId)->get();
10178
10179            return response(['message' => 'OK', 'data' => $companyEmails]);
10180
10181        } catch (\Exception $e) {
10182            report(AppException::fromException($e, 'GET_SENDER_IDENTITY_EXCEPTION'));
10183
10184            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10185        }
10186    }
10187
10188    public function get_all_sender_identity($companyId): ResponseFactory|HttpResponse
10189    {
10190
10191        try {
10192
10193            $companyId = addslashes((string) $companyId);
10194
10195            $query = "SELECT
10196                        id,
10197                        response_id,
10198                        nickname,
10199                        CONCAT(nickname, ' - ', from_email) from_email,
10200                        from_name,
10201                        reply_to,
10202                        reply_to_name,
10203                        address,
10204                        address2,
10205                        state,
10206                        city,
10207                        country,
10208                        zip,
10209                        verified,
10210                        locked,
10211                        is_active,
10212                        created_by,
10213                        created_at,
10214                        updated_by,
10215                        updated_at
10216                    FROM
10217                        tbl_company_emails
10218                    WHERE
10219                        company_id != {$companyId}
10220                        AND from_email NOT IN (
10221                        SELECT
10222                            from_email
10223                        FROM
10224                            tbl_company_emails
10225                        WHERE
10226                            company_id = {$companyId}
10227                        )
10228                    ";
10229
10230            $companyEmails = DB::select($query);
10231
10232            return response(['message' => 'OK', 'data' => $companyEmails]);
10233
10234        } catch (\Exception $e) {
10235            report(AppException::fromException($e, 'GET_ALL_SENDER_IDENTITY_EXCEPTION'));
10236
10237            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10238        }
10239    }
10240
10241    public function delete_sender_identity(Request $request): ResponseFactory|HttpResponse
10242    {
10243
10244        try {
10245
10246            $data = $request->all();
10247            $responseId = addslashes((string) $data['response_id']);
10248            $id = addslashes((string) $data['id']);
10249
10250            $sender = TblCompanyEmails::where('response_id', $responseId)->count();
10251
10252            if ($sender > 1) {
10253                TblCompanyEmails::where('id', $id)->delete();
10254            } else {
10255                $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
10256
10257                $response = $sendgrid->client->verified_senders()->_($responseId)->delete();
10258
10259                if ($response->statusCode() == 204) {
10260                    TblCompanyEmails::where('response_id', $responseId)->delete();
10261                }
10262            }
10263
10264            return response(['message' => 'OK']);
10265
10266        } catch (\Exception $e) {
10267            report(AppException::fromException($e, 'DELETE_SENDER_IDENTITY_EXCEPTION'));
10268
10269            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10270        }
10271    }
10272
10273    public function create_template(Request $request): ResponseFactory|HttpResponse
10274    {
10275
10276        try {
10277
10278            $data = $request->all();
10279
10280            $files = $request->file('files');
10281            unset($data['files']);
10282
10283            if ($files) {
10284                $totalFileCount = count($files);
10285                if ($totalFileCount > 2) {
10286                    return response(['message' => 'KO', 'error' => __('language.file_count_exceeded')]);
10287                }
10288            }
10289
10290            $result = TblEmailConfiguration::create($data);
10291            $id = $result->id;
10292
10293            $directory = 'public/uploads';
10294            $origFilename = 'fireservicetitan.png';
10295            $file = 'public/uploads/fireservicetitan.png';
10296
10297            $sourcePath = public_path($origFilename);
10298            $destinationPath = 'public/uploads/'.$origFilename;
10299
10300            $filename = $id.'-EI'.time().'-'.$origFilename;
10301
10302            Storage::putFileAs($directory, new \Illuminate\Http\File($sourcePath), $filename);
10303            Storage::disk('google')->put($filename, file_get_contents(storage_path().'/app/public/uploads/'.$filename));
10304
10305            TblEmailFiles::create(
10306                [
10307                    'email_template_id' => $id,
10308                    'original_name' => $origFilename,
10309                    'filename' => $filename,
10310                    'uploaded_by' => $data['created_by'],
10311                ]
10312            );
10313
10314            if ($files) {
10315
10316                $uploadedFiles = [];
10317                $i = 0;
10318
10319                $combinedFilesSize = 0;
10320
10321                foreach ($files as $file) {
10322                    $i++;
10323
10324                    $origFilename = str_replace(' ', '', $file->getClientOriginalName());
10325
10326                    $filename = $id.'-EI'.time().'-'.$origFilename;
10327
10328                    $combinedFilesSize = $combinedFilesSize + $file->getSize();
10329
10330                    if ($combinedFilesSize > 25000000) {
10331                        return response(['message' => 'KO', 'error' => __('language.file_size_exceeded')]);
10332                    }
10333
10334                    Storage::putFileAs($directory, $file, $filename);
10335                    Storage::disk('google')->put($filename, file_get_contents(storage_path().'/app/public/uploads/'.$filename));
10336
10337                    if (in_array($origFilename, $uploadedFiles)) {
10338                        $origFilename = $origFilename.$i;
10339                    }
10340
10341                    TblEmailFiles::create(
10342                        [
10343                            'email_template_id' => $id,
10344                            'original_name' => $origFilename,
10345                            'filename' => $filename,
10346                            'uploaded_by' => $data['created_by'],
10347                        ]
10348                    );
10349
10350                    $uploadedFiles[] = $file->getClientOriginalName();
10351                }
10352            }
10353
10354            return response(['message' => 'OK']);
10355
10356        } catch (\Exception $e) {
10357            report(AppException::fromException($e, 'CREATE_TEMPLATE_EXCEPTION'));
10358
10359            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10360        }
10361    }
10362
10363    public function get_email_files($emailTemplateId): ResponseFactory|HttpResponse
10364    {
10365
10366        try {
10367
10368            $emailTemplateId = addslashes((string) $emailTemplateId);
10369
10370            $result = TblEmailFiles::where('email_template_id', $emailTemplateId)->orderBy('order', 'asc')->get();
10371
10372            foreach ($result as $key => $value) {
10373                $path = storage_path('app/public/uploads/'.$result[$key]->filename);
10374
10375                if (File::exists($path)) {
10376                    $fileSizeBytes = File::size($path);
10377                    $result[$key]->setAttribute('filesize', $this->human_filesize($fileSizeBytes));
10378                    $result[$key]->original_name = $result[$key]->original_name." ({$result[$key]->getAttribute('filesize')})";
10379                    $result[$key]->setAttribute('img', 'data:image/png;base64,'.base64_encode(file_get_contents($path)));
10380                }
10381            }
10382
10383            return response(['message' => 'OK', 'data' => $result]);
10384
10385        } catch (\Exception $e) {
10386            report(AppException::fromException($e, 'GET_EMAIL_FILES_EXCEPTION'));
10387
10388            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10389        }
10390    }
10391
10392    public function download_email_template_file($fileId): ResponseFactory|HttpResponse
10393    {
10394
10395        try {
10396
10397            $fileId = addslashes((string) $fileId);
10398
10399            $result = TblEmailFiles::where('file_id', $fileId)->first();
10400
10401            if ($result) {
10402                $path = storage_path('app/public/uploads/'.$result->filename);
10403
10404                if (! Storage::disk('public')->exists('uploads/'.$result->filename)) {
10405                    return response(['message' => 'KO']);
10406                }
10407
10408                return response()->download($path);
10409            }
10410
10411            return response(['message' => 'KO']);
10412
10413        } catch (\Exception $e) {
10414            report(AppException::fromException($e, 'DOWNLOAD_EMAIL_TEMPLATE_FILE_EXCEPTION'));
10415
10416            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10417        }
10418
10419    }
10420
10421    public function delete_email_template_file($fileId): ResponseFactory|HttpResponse
10422    {
10423
10424        try {
10425
10426            $fileId = addslashes((string) $fileId);
10427            $file = TblEmailFiles::where('file_id', $fileId)->first();
10428            $result = TblEmailFiles::where('file_id', $fileId)->first();
10429
10430            if ($result) {
10431                TblEmailFiles::where('file_id', $fileId)->delete();
10432                $path = storage_path('app/public/uploads/'.$result->filename);
10433                Storage::disk('public')->delete('uploads/'.$result->filename);
10434            }
10435
10436            return response(['message' => 'OK']);
10437
10438        } catch (\Exception $e) {
10439            report(AppException::fromException($e, 'DELETE_EMAIL_TEMPLATE_FILE_EXCEPTION'));
10440
10441            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10442        }
10443    }
10444
10445    public function update_email_template_order(Request $request, $id)
10446    {
10447
10448        try {
10449
10450            $id = addslashes((string) $id);
10451            $data = $request->all();
10452
10453            foreach ($data as $item) {
10454                TblEmailFiles::where('file_id', $item['file_id'])->update(['order' => $item['order']]);
10455            }
10456
10457        } catch (\Exception $e) {
10458            report(AppException::fromException($e, 'UPDATE_EMAIL_TEMPLATE_ORDER_EXCEPTION'));
10459
10460            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10461        }
10462
10463    }
10464
10465    public function update_email_template(Request $request, $id): ResponseFactory|HttpResponse
10466    {
10467
10468        try {
10469
10470            $data = $request->all();
10471
10472            $id = addslashes((string) $id);
10473
10474            $files = $request->file('files');
10475            unset($data['files']);
10476
10477            $fileCount = TblEmailFiles::where('email_template_id', $id)->count();
10478
10479            if ($files) {
10480                $totalFileCount = $fileCount + count($files);
10481                if ($totalFileCount > 3) {
10482                    return response(['message' => 'KO', 'error' => __('language.file_count_exceeded')]);
10483                }
10484            }
10485
10486            if (isset($data['cron_default'])) {
10487                TblEmailConfiguration::where('company_id', $data['company_id'])->where('cron_default', 1)->update(['cron_default' => 0]);
10488            }
10489
10490            $data['updated_at'] = date('Y-m-d H:i:s');
10491            TblEmailConfiguration::where('id', $id)->update($data);
10492
10493            if ($files) {
10494
10495                $directory = 'public/uploads';
10496                $uploadedFiles = [];
10497                $i = 0;
10498
10499                $combinedFilesSize = 0;
10500                foreach ($files as $file) {
10501                    $i++;
10502                    $origFilename = str_replace(' ', '', $file->getClientOriginalName());
10503                    $filename = $id.'-EI'.time().'-'.$origFilename;
10504
10505                    $combinedFilesSize = $combinedFilesSize + $file->getSize();
10506
10507                    if ($combinedFilesSize > 25000000) {
10508                        return response(['message' => 'KO', 'error' => __('language.file_size_exceeded')]);
10509                    }
10510
10511                    Storage::putFileAs($directory, $file, $filename);
10512                    Storage::disk('google')->put($filename, file_get_contents(storage_path().'/app/public/uploads/'.$filename));
10513
10514                    if (in_array($origFilename, $uploadedFiles)) {
10515                        $origFilename = $origFilename.$i;
10516                    }
10517
10518                    TblEmailFiles::create(
10519                        [
10520                            'email_template_id' => $id,
10521                            'original_name' => $origFilename,
10522                            'filename' => $filename,
10523                            'uploaded_by' => $data['updated_by'],
10524                        ]
10525                    );
10526
10527                    $uploadedFiles[] = $file->getClientOriginalName();
10528                }
10529            }
10530
10531            return response(['message' => 'OK']);
10532
10533        } catch (\Exception $e) {
10534            report(AppException::fromException($e, 'UPDATE_EMAIL_TEMPLATE_EXCEPTION'));
10535
10536            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10537        }
10538
10539    }
10540
10541    public function delete_template($id): ResponseFactory|HttpResponse
10542    {
10543
10544        try {
10545
10546            $id = addslashes((string) $id);
10547
10548            TblEmailConfiguration::where('id', $id)->delete();
10549
10550            return response(['message' => 'OK']);
10551
10552        } catch (\Exception $e) {
10553            report(AppException::fromException($e, 'DELETE_TEMPLATE_EXCEPTION'));
10554
10555            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10556        }
10557
10558    }
10559
10560    /**
10561     * FIRE-1488 — remove the calling user's per-template override so the
10562     * next open of the "Editar plantilla" modal shows the canonical
10563     * regional template again. Returns the canonical html so the FE can
10564     * re-hydrate the Quill editor in place without a second round-trip.
10565     */
10566    public function delete_email_template_user_override($templateId): ResponseFactory|HttpResponse
10567    {
10568        try {
10569            $userId = (int) $this->userId;
10570            $templateId = (int) $templateId;
10571
10572            TblEmailTemplateUserOverride::where('user_id', $userId)
10573                ->where('template_id', $templateId)
10574                ->delete();
10575
10576            $canonical = TblEmailConfiguration::where('id', $templateId)->first();
10577
10578            return response([
10579                'message' => 'OK',
10580                'data' => [
10581                    'template_id' => $templateId,
10582                    'html' => $canonical?->html,
10583                ],
10584            ]);
10585        } catch (\Exception $e) {
10586            report(AppException::fromException($e, 'DELETE_EMAIL_TEMPLATE_USER_OVERRIDE_EXCEPTION'));
10587
10588            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10589        }
10590    }
10591
10592    public function get_email_template($companyId): ResponseFactory|HttpResponse
10593    {
10594
10595        try {
10596
10597            $companyId = addslashes((string) $companyId);
10598
10599            $where = '';
10600            if ($companyId != 0) {
10601                $where = " a.company_id = {$companyId} ";
10602            } else {
10603                $where = " a.company_id IN ({$this->companyId}) ";
10604            }
10605
10606            // FIRE-1488: LEFT JOIN tbl_email_template_user_overrides so a
10607            // comercial who has previously edited a template sees THEIR
10608            // personalized body on next open (with COALESCE falling back to
10609            // the canonical html). `has_user_override` lets the FE flag it
10610            // in the UI ("🧑 Tu versión") without a second round-trip.
10611            $userIdInt = (int) $this->userId;
10612
10613            $query = "SELECT
10614                        a.id,
10615                        a.from_id,
10616                        CASE
10617                            WHEN a.type = 'followUps' THEN 'Follow-ups'
10618                            WHEN a.type = 'sendToClient' THEN 'Send to client'
10619                        END types,
10620                        (SELECT from_email FROM tbl_company_emails WHERE id = a.from_id) from_email,
10621                        a.name,
10622                        b.name company_name,
10623                        b.company_id,
10624                        a.subject,
10625                        COALESCE(o.html, a.html) html,
10626                        a.is_active,
10627                        a.type,
10628                        a.created_by,
10629                        a.created_at,
10630                        a.updated_by,
10631                        a.updated_at,
10632                        a.cron_default,
10633                        CASE WHEN o.id IS NULL THEN 0 ELSE 1 END has_user_override
10634                    FROM tbl_email_configuration a
10635                    LEFT JOIN tbl_companies b
10636                        ON b.company_id = a.company_id
10637                    LEFT JOIN tbl_email_template_user_overrides o
10638                        ON o.template_id = a.id AND o.user_id = {$userIdInt}
10639                    WHERE {$where}
10640                    ORDER BY a.id DESC";
10641
10642            $result = DB::select($query);
10643
10644            return response(['message' => 'OK', 'data' => $result]);
10645
10646        } catch (\Exception $e) {
10647            report(AppException::fromException($e, 'GET_EMAIL_TEMPLATE_EXCEPTION'));
10648
10649            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10650        }
10651
10652    }
10653
10654    public function update_sender_identity(Request $request, $responseId): ResponseFactory|HttpResponse
10655    {
10656
10657        try {
10658
10659            $data = $request->all();
10660            $companyId = $data['company_id'];
10661            $updatedBy = $data['updated_by'];
10662            $active = $data['is_active'];
10663            $id = addslashes((string) $data['id']);
10664            unset($data['id']);
10665            unset($data['company_id']);
10666            unset($data['updated_by']);
10667            unset($data['is_active']);
10668
10669            $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
10670            $data['reply_to'] = $data['from_email'];
10671            $data['reply_to_name'] = $data['from_name'];
10672            $requestBody = $data;
10673            $error = false;
10674
10675            $response = $sendgrid->client->verified_senders()->_($responseId)->patch($requestBody);
10676
10677            if ($response->statusCode() == 200) {
10678                $x = json_decode((string) $response->body());
10679
10680                $data['updated_by'] = $updatedBy;
10681                $data['updated_at'] = date('Y-m-d H:i:s');
10682                $data['is_active'] = $active;
10683
10684                TblCompanyEmails::where('company_id', $companyId)->update(['is_active' => 0]);
10685                TblCompanyEmails::where('id', $id)->update($data);
10686
10687                Log::channel('email_log')->info('EMAIL: '.$data['from_email'].' - UPDATED');
10688            } else {
10689                $error = true;
10690                Log::channel('email_log')->error('REQUEST BODY: - '.$response->body());
10691            }
10692
10693            $response = json_decode((string) $response->body());
10694
10695            if ($error) {
10696                $errMessage = @$response->errors[0]->field.': '.@$response->errors[0]->message;
10697
10698                return response(['message' => 'KO', 'error' => $errMessage]);
10699            } else {
10700                return response(['message' => 'OK', 'data' => $response]);
10701            }
10702
10703        } catch (\Exception $e) {
10704            report(AppException::fromException($e, 'UPDATE_SENDER_IDENTITY_EXCEPTION'));
10705
10706            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10707        }
10708
10709    }
10710
10711    public function resend_verification($id): ResponseFactory|HttpResponse
10712    {
10713
10714        try {
10715
10716            $id = addslashes((string) $id);
10717
10718            $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
10719
10720            $response = $sendgrid->client->verified_senders()->resend()->_($id)->post();
10721
10722            if ($response->statusCode() == 204) {
10723                return response(['message' => 'OK']);
10724            } else {
10725                $response = json_decode((string) $response->body());
10726                $errMessage = $response->errors[0]->error_id.': '.$response->errors[0]->message;
10727
10728                return response(['message' => 'KO', 'error' => $errMessage]);
10729            }
10730
10731        } catch (\Exception $e) {
10732            report(AppException::fromException($e, 'RESEND_VERIFICATION_EXCEPTION'));
10733
10734            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10735        }
10736    }
10737
10738    public function list_quotation_analytics_by_performance(Request $request): ResponseFactory|HttpResponse
10739    {
10740
10741        try {
10742
10743            $data = $request->all();
10744            $companyId = addslashes((string) $data['company_id']);
10745            $where = '';
10746
10747            if ($companyId != 0) {
10748                $where .= " AND company_id = {$companyId} AND for_add = 0 ";
10749            } else {
10750                $where .= " AND company_id IN ({$this->companyId}) AND for_add = 0 ";
10751            }
10752
10753            if (isset($data['budget_status']) && $data['budget_status'] != null) {
10754                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
10755            }
10756
10757            $latestYear = TblQuotations::max(DB::raw('YEAR(COALESCE(sent_date, issue_date))'));
10758            $md = date('m-d');
10759
10760            $query = "SELECT
10761                        q.years,
10762                        q.totalIssue,
10763                        (q.total_acceptance_percentage - q.totalAcceptancePercentage) / q.totalAcceptancePercentage * 100 totalAcceptancePercentage,
10764                        q.totalAccept
10765                    FROM
10766                        (
10767                        SELECT
10768                            YEAR(COALESCE(a.sent_date, a.issue_date)) years,
10769                            (b.total_issued - COUNT(COALESCE(a.sent_date, a.issue_date))) / COUNT(COALESCE(a.sent_date, a.issue_date)) * 100 totalIssue,
10770                            COUNT(
10771                                CASE WHEN a.acceptance_date IS NOT NULL
10772                                AND DATE_FORMAT(a.acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(a.acceptance_date), '-01-01')
10773                                AND CONCAT(YEAR(a.acceptance_date), '-{$md}')
10774                                AND YEAR(a.acceptance_date) = YEAR(COALESCE(a.sent_date, a.issue_date))
10775                                AND a.budget_status_id = 3 THEN 1 END
10776                            ) / COUNT(COALESCE(a.sent_date, a.issue_date)) * 100 totalAcceptancePercentage,
10777                            b.total_acceptance_percentage,
10778                            (b.total_acceptance -
10779                                COUNT(
10780                                    CASE WHEN a.acceptance_date IS NOT NULL
10781                                    AND DATE_FORMAT(a.acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(a.acceptance_date), '-01-01')
10782                                    AND CONCAT(YEAR(a.acceptance_date), '-{$md}')
10783                                    AND YEAR(a.acceptance_date) = YEAR(COALESCE(a.sent_date, a.issue_date))
10784                                    AND a.budget_status_id = 3 THEN 1 END)
10785                                    ) / COUNT(
10786                                            CASE WHEN a.acceptance_date IS NOT NULL
10787                                            AND DATE_FORMAT(a.acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(a.acceptance_date), '-01-01')
10788                                            AND CONCAT(YEAR(a.acceptance_date), '-{$md}')
10789                                            AND YEAR(a.acceptance_date) = YEAR(COALESCE(a.sent_date, a.issue_date))
10790                                            AND a.budget_status_id = 3 THEN 1 END
10791                            ) * 100 totalAccept
10792                        FROM
10793                            tbl_quotations a
10794                            JOIN (
10795                            SELECT
10796                                YEAR(COALESCE(sent_date, issue_date)) current_year,
10797                                COUNT(COALESCE(sent_date, issue_date)) total_issued,
10798                                COUNT(
10799                                    CASE WHEN acceptance_date IS NOT NULL
10800                                    AND DATE_FORMAT(acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(acceptance_date), '-01-01')
10801                                    AND CONCAT(YEAR(acceptance_date), '-{$md}')
10802                                    AND YEAR(acceptance_date) = YEAR(COALESCE(sent_date, issue_date))
10803                                    AND budget_status_id = 3 THEN 1 END
10804                                ) total_acceptance,
10805                                COUNT(
10806                                    CASE WHEN acceptance_date IS NOT NULL
10807                                    AND DATE_FORMAT(acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(acceptance_date), '-01-01')
10808                                    AND CONCAT(YEAR(acceptance_date), '-{$md}')
10809                                    AND YEAR(acceptance_date) = YEAR(COALESCE(sent_date, issue_date))
10810                                    AND budget_status_id = 3 THEN 1 END
10811                                ) / COUNT(COALESCE(sent_date, issue_date)) * 100 total_acceptance_percentage
10812                            FROM
10813                                tbl_quotations
10814                            WHERE
10815                                COALESCE(sent_date, issue_date) IS NOT NULL
10816                                AND YEAR(COALESCE(sent_date, issue_date)) = {$latestYear}
10817                                AND DATE_FORMAT(COALESCE(sent_date, issue_date), '%Y-%m-%d') BETWEEN CONCAT(YEAR(COALESCE(sent_date, issue_date)), '-01-01')
10818                                AND CONCAT(YEAR(COALESCE(sent_date, issue_date)), '-{$md}')
10819                                {$where}
10820                            GROUP by
10821                                1
10822                            ) b
10823                        WHERE
10824                            COALESCE(a.sent_date, a.issue_date) IS NOT NULL
10825                            AND a.budget_type_id != 7
10826                            AND a.budget_type_id IS NOT NULL
10827                            AND {$latestYear} > YEAR(COALESCE(a.sent_date, a.issue_date))
10828                            AND DATE_FORMAT(COALESCE(a.sent_date, a.issue_date), '%Y-%m-%d') BETWEEN CONCAT(YEAR(COALESCE(a.sent_date, a.issue_date)), '-01-01')
10829                            AND CONCAT(YEAR(COALESCE(a.sent_date, a.issue_date)), '-{$md}')
10830                        GROUP BY
10831                            1
10832                        ORDER BY
10833                            YEAR(COALESCE(sent_date, issue_date)) DESC
10834                        ) q
10835                    ";
10836
10837            $resultYtd = DB::select($query);
10838
10839            $query = "SELECT
10840                        YEAR(COALESCE(sent_date, issue_date)) years,
10841                        COUNT(COALESCE(sent_date, issue_date)) totalIssue,
10842                        COUNT(
10843                            CASE WHEN acceptance_date IS NOT NULL
10844                            AND DATE_FORMAT(acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(acceptance_date), '-01-01')
10845                            AND CONCAT(YEAR(acceptance_date), '-{$md}')
10846                            AND YEAR(acceptance_date) = YEAR(COALESCE(sent_date, issue_date))
10847                            AND budget_status_id = 3 THEN 1 END
10848                        ) totalAccept,
10849                        COUNT(
10850                            CASE WHEN acceptance_date IS NOT NULL
10851                            AND DATE_FORMAT(acceptance_date, '%Y-%m-%d') BETWEEN CONCAT(YEAR(acceptance_date), '-01-01')
10852                            AND CONCAT(YEAR(acceptance_date), '-{$md}')
10853                            AND YEAR(acceptance_date) = YEAR(COALESCE(sent_date, issue_date))
10854                            AND budget_status_id = 3 THEN 1 END
10855                        ) / COUNT(COALESCE(sent_date, issue_date)) * 100 totalAcceptancePercentage
10856                    FROM
10857                        tbl_quotations
10858                    WHERE
10859                        COALESCE(sent_date, issue_date) IS NOT NULL
10860                        AND budget_type_id != 7
10861                        AND budget_type_id IS NOT NULL
10862                        AND DATE_FORMAT(COALESCE(sent_date, issue_date), '%Y-%m-%d') BETWEEN CONCAT(YEAR(COALESCE(sent_date, issue_date)), '-01-01')
10863                        AND CONCAT(YEAR(COALESCE(sent_date, issue_date)), '-{$md}')
10864                        {$where}
10865                    GROUP BY
10866                        1
10867                    ORDER BY
10868                        YEAR(COALESCE(sent_date, issue_date)) DESC
10869                    ";
10870
10871            $resultYears = DB::select($query);
10872
10873            return response(['message' => 'OK', 'ytdData' => $resultYtd, 'yearsData' => $resultYears]);
10874
10875        } catch (\Exception $e) {
10876            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_BY_PERFORMANCE_EXCEPTION'));
10877
10878            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10879        }
10880    }
10881
10882    public function list_orders_update_logs($companyId): ResponseFactory|HttpResponse
10883    {
10884
10885        try {
10886
10887            $where = '';
10888
10889            if ($companyId != 0) {
10890                $where .= " a.company_id = {$companyId}";
10891            } else {
10892                $where .= " a.company_id IN ({$this->companyId})";
10893            }
10894
10895            $query = "SELECT
10896                        a.id,
10897                        b.name company,
10898                        a.to_process,
10899                        a.rejected_affected_rows,
10900                        a.for_add_deleted_affected_rows,
10901                        a.month_change_affected_rows,
10902                        a.follow_ups_affected_rows,
10903                        a.sync_succesfull,
10904                        a.sync_error,
10905                        a.sync_error_message,
10906                        a.sync_success_ids,
10907                        a.cleared_email_errors,
10908                        a.remaining_email_errors,
10909                        CASE
10910                            WHEN a.rejected_affected_rows IS NOT NULL THEN a.rejected_affected_rows
10911                            WHEN a.for_add_deleted_affected_rows IS NOT NULL THEN a.for_add_deleted_affected_rows
10912                            WHEN a.month_change_affected_rows IS NOT NULL THEN a.month_change_affected_rows
10913                            WHEN a.follow_ups_affected_rows IS NOT NULL THEN a.follow_ups_affected_rows
10914                        END totals,
10915                        a.status,
10916                        a.processed_by,
10917                        a.started_at,
10918                        a.ended_at,
10919                        a.rejected_automatically_ids
10920                    FROM `tbl_orders_update_logs` a
10921                    LEFT JOIN tbl_companies b
10922                        ON a.company_id = b.company_id
10923                    WHERE {$where}
10924                    ORDER BY started_at DESC";
10925
10926            $result = DB::select($query);
10927
10928            return response(['message' => 'OK', 'data' => $result]);
10929
10930        } catch (\Exception $e) {
10931            report(AppException::fromException($e, 'LIST_ORDERS_UPDATE_LOGS_EXCEPTION'));
10932
10933            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10934        }
10935
10936    }
10937
10938    public function list_g3w_orders_update_logs($companyId): ResponseFactory|HttpResponse
10939    {
10940
10941        try {
10942            $result = TblG3WOrdersUpdateLogs::where('company_id', $companyId)
10943                ->where('processed_by', 'System')
10944                ->get();
10945
10946            return response(['message' => 'OK', 'data' => $result]);
10947
10948        } catch (\Exception $e) {
10949            report(AppException::fromException($e, 'LIST_G3W_ORDERS_UPDATE_LOGS_EXCEPTION'));
10950
10951            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10952        }
10953
10954    }
10955
10956    public function list_g3w_orders_failed($companyId): ResponseFactory|HttpResponse
10957    {
10958        try {
10959            $logs = TblG3WOrdersUpdateLogs::where('company_id', $companyId)
10960                ->where('sync_error', '>', 0)
10961                ->get();
10962
10963            $individualErrors = [];
10964
10965            foreach ($logs as $log) {
10966                $errorIds = json_decode((string) $log->sync_error_ids);
10967                $errorMessages = preg_split('/(?=Error (sincronizando|actualizando) el presupuesto)/', (string) $log->sync_error_message, -1, PREG_SPLIT_NO_EMPTY);
10968
10969                if (is_array($errorIds)) {
10970                    foreach ($errorIds as $index => $id) {
10971                        $rawMsg = $errorMessages[$index] ?? 'Error desconocido';
10972                        $cleanMsg = trim((string) preg_replace('/.*?el presupuesto \d+:/i', '', $rawMsg));
10973                        $cleanMsg = rtrim($cleanMsg, ',');
10974
10975                        $individualErrors[] = [
10976                            'quote_id' => $id,
10977                            'status' => 'Failed',
10978                            'started_at' => $log->started_at,
10979                            'ended_at' => $log->ended_at,
10980                            'reason' => $cleanMsg,
10981                            'log_id' => $log->id,
10982                        ];
10983                    }
10984                }
10985            }
10986
10987            return response(['message' => 'OK', 'data' => $individualErrors]);
10988
10989        } catch (\Exception $e) {
10990            report($e);
10991
10992            return response(['message' => 'KO', 'error' => $e->getMessage()]);
10993        }
10994    }
10995
10996    /**
10997     * FIRE-1077: Cofrai parallel to list_g3w_orders_update_logs.
10998     * Reads from tbl_cofrai_orders_update_logs instead of tbl_g3w_orders_update_logs.
10999     */
11000    public function list_cofrai_orders_update_logs($companyId): ResponseFactory|HttpResponse
11001    {
11002        try {
11003            $result = TblCofraiOrdersUpdateLogs::where('company_id', $companyId)
11004                ->where('processed_by', 'System')
11005                ->get();
11006
11007            return response(['message' => 'OK', 'data' => $result]);
11008        } catch (\Exception $e) {
11009            report(AppException::fromException($e, 'LIST_COFRAI_ORDERS_UPDATE_LOGS_EXCEPTION'));
11010
11011            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11012        }
11013    }
11014
11015    /**
11016     * FIRE-1077: Cofrai parallel to list_g3w_orders_failed.
11017     * Same shape — flattens sync_error_ids to per-id error rows for the
11018     * cofrai-error-sync page table.
11019     */
11020    public function list_cofrai_orders_failed($companyId): ResponseFactory|HttpResponse
11021    {
11022        try {
11023            $logs = TblCofraiOrdersUpdateLogs::where('company_id', $companyId)
11024                ->where('sync_error', '>', 0)
11025                ->get();
11026
11027            $individualErrors = [];
11028
11029            foreach ($logs as $log) {
11030                $errorIds = json_decode((string) $log->sync_error_ids);
11031                $errorMessages = preg_split('/(?=Error (sincronizando|actualizando) el presupuesto)/', (string) $log->sync_error_message, -1, PREG_SPLIT_NO_EMPTY);
11032
11033                if (is_array($errorIds)) {
11034                    foreach ($errorIds as $index => $id) {
11035                        $rawMsg = $errorMessages[$index] ?? 'Error desconocido';
11036                        $cleanMsg = trim((string) preg_replace('/.*?el presupuesto \d+:/i', '', $rawMsg));
11037                        $cleanMsg = rtrim($cleanMsg, ',');
11038
11039                        $individualErrors[] = [
11040                            'quote_id' => $id,
11041                            'status' => 'Failed',
11042                            'started_at' => $log->started_at,
11043                            'ended_at' => $log->ended_at,
11044                            'reason' => $cleanMsg,
11045                            'log_id' => $log->id,
11046                        ];
11047                    }
11048                }
11049            }
11050
11051            return response(['message' => 'OK', 'data' => $individualErrors]);
11052        } catch (\Exception $e) {
11053            report($e);
11054
11055            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11056        }
11057    }
11058
11059    public function update_budget_status_rejected_manual(Request $request): ResponseFactory|HttpResponse
11060    {
11061
11062        try {
11063
11064            $data = $request->all();
11065
11066            $update = $this->update_budget_status_rejected($data['company_id'], $data['processed_by']);
11067
11068            if ($update) {
11069                return response(['message' => 'OK']);
11070            } else {
11071                return response(['message' => 'KO']);
11072            }
11073
11074        } catch (\Exception $e) {
11075            report(AppException::fromException($e, 'UPDATE_BUDGET_STATUS_REJECTED_MANUAL_EXCEPTION'));
11076
11077            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11078        }
11079    }
11080
11081    public function update_budget_status_rejected($companyId = null, $processedBy = 'System'): ResponseFactory|HttpResponse
11082    {
11083
11084        $startedAt = date('Y-m-d H:i:s');
11085        try {
11086
11087            $startedAt = date('Y-m-d H:i:s');
11088            $companyId = addslashes((string) $companyId);
11089            $where = '';
11090
11091            $budgetTypes = TblBudgetTypes::get();
11092
11093            if (count($budgetTypes) > 0) {
11094
11095                $companies = [];
11096
11097                if ($companyId != 0) {
11098                    $companies = TblCompanies::where('company_id', $companyId)->get();
11099                    $where = "AND company_id = {$companyId}";
11100                } else {
11101                    $companies = TblCompanies::get();
11102                }
11103
11104                for ($i = 0; $i < count($budgetTypes); $i++) {
11105
11106                    $days = $budgetTypes[$i]->duration;
11107                    $id = $budgetTypes[$i]->budget_type_id;
11108
11109                    if (! $days) {
11110                        continue;
11111                    }
11112
11113                    for ($c = 0; $c < count($companies); $c++) {
11114                        $companyId = $companies[$c]->company_id;
11115
11116                        $query = "SELECT
11117                                    GROUP_CONCAT(id) ids
11118                                FROM
11119                                    tbl_quotations
11120                                WHERE
11121                                    budget_type_id = {$id}
11122                                AND budget_status_id IN (1, 2, 11)
11123                                AND DATEDIFF(NOW(), issue_date) >= {$days}
11124                                AND for_add = 0
11125                                {$where}";
11126
11127                        $result = DB::select($query);
11128
11129                        if (count($result) > 0) {
11130
11131                            $ids = $result[0]->ids;
11132
11133                            if ($ids != null || $ids != '') {
11134                                $query = "UPDATE
11135                                            tbl_quotations
11136                                        SET
11137                                            budget_status_id = 7
11138                                        WHERE
11139                                            id IN ({$ids})";
11140
11141                                DB::select($query);
11142
11143                                TblOrdersUpdateLogs::create(
11144                                    [
11145                                        'company_id' => $companyId,
11146                                        'to_process' => 'Orders',
11147                                        'status' => 'success',
11148                                        'rejected_automatically_ids' => $ids,
11149                                        'processed_by' => $processedBy,
11150                                        'started_at' => $startedAt,
11151                                        'ended_at' => date('Y-m-d H:i:s'),
11152                                    ]
11153                                );
11154                            }
11155                        }
11156                    }
11157                }
11158            }
11159
11160            // FIRE-1145: was Cache::flush() — status rejection affects list_quotations + commercial counters.
11161            ResultCache::forgetDomain(['quotations', 'users']);
11162
11163            return response(['message' => 'OK']);
11164
11165        } catch (\Exception $e) {
11166            report(AppException::fromException($e, 'UPDATE_BUDGET_STATUS_REJECTED_MANUAL_EXCEPTION'));
11167
11168            TblOrdersUpdateLogs::create(
11169                [
11170                    'company_id' => $companyId,
11171                    'to_process' => 'Orders',
11172                    'status' => $e->getMessage(),
11173                    'processed_by' => $processedBy,
11174                    'started_at' => $startedAt,
11175                    'ended_at' => date('Y-m-d H:i:s'),
11176                ]
11177            );
11178
11179            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11180        }
11181
11182    }
11183
11184    public function bulk_update_quotation(Request $request): ResponseFactory|HttpResponse
11185    {
11186
11187        // try {
11188
11189        $data = $request->all();
11190
11191        if ($invalid = $this->invalidAmountResponse($data)) {
11192            return $invalid;
11193        }
11194        if (($data['amount'] ?? null) === 'null') {
11195            $data['amount'] = null;
11196        }
11197
11198        $r = new Request([
11199            'filterModel' => $data['filterModel'] ?? [],
11200            'sortModel' => $data['sortModel'] ?? [],
11201            'start' => 0,
11202            'end' => 999999999,
11203            'company_id' => $data['company_id'],
11204            'user_id' => $data['user_id'],
11205            'ids' => $data['ids'],
11206            'searchText' => $data['searchText'] ?? '',
11207            'ids_not_in' => $data['ids_not_in'],
11208        ]);
11209
11210        $listQuotations = $this->list_orders_table($r);
11211        $d = $listQuotations->original['data'];
11212
11213        if (count($d) > 0) {
11214            if (isset($data['last_follow_up_date']) && $data['last_follow_up_date'] == 1) {
11215                unset($data['last_follow_up_date']);
11216            }
11217            // unset($data['last_follow_up_date']);
11218            unset($data['filterModel']);
11219            unset($data['sortModel']);
11220            unset($data['start']);
11221            unset($data['end']);
11222            unset($data['company_id']);
11223            unset($data['user_id']);
11224            unset($data['ids']);
11225            unset($data['searchText']);
11226            unset($data['ids_not_in']);
11227            // Sent by the data-table bulk plumbing but not a real column — would
11228            // otherwise blow up with "Unknown column 'selectAll'".
11229            unset($data['selectAll']);
11230
11231            $result = [];
11232            for ($i = 0; $i < count($d); $i++) {
11233                array_push($result, $d[$i]->id);
11234            }
11235
11236            // Read the statuses before the update: a bulk move to Enviado is a
11237            // send for every row that was not already sent.
11238            $oldStatus = isset($data['budget_status_id'])
11239                ? TblQuotations::whereIn('id', $result)->pluck('budget_status_id', 'id')->all()
11240                : [];
11241
11242            TblQuotations::whereIn('id', $result)->update($data);
11243
11244            foreach ($oldStatus as $qid => $old) {
11245                if (QuotationSendRecorder::isSentTransition($old, $data['budget_status_id'])) {
11246                    QuotationSendRecorder::record((int) $qid, QuotationSendRecorder::MANUAL_STATUS,
11247                        $data['updated_by'] ?? null);
11248                }
11249            }
11250
11251            // FIRE-1145: was Cache::flush() — bulk update affects list_quotations + commercial counters.
11252            ResultCache::forgetDomain(['quotations', 'users']);
11253        }
11254
11255        return response(['message' => 'OK', $data]);
11256
11257        // } catch (\Exception $e) {
11258        //     return response(['message' => 'KO', 'error' => $e->getMessage()]);
11259        // }
11260
11261    }
11262
11263    public function move_budget_and_job(Request $request): ResponseFactory|HttpResponse
11264    {
11265
11266        try {
11267
11268            $data = $request->all();
11269            $id = addslashes((string) $data['id']);
11270            $companyId = addslashes((string) $data['company_id']);
11271
11272            unset($data['id']);
11273            unset($data['company_id']);
11274
11275            $budget = TblQuotations::where('id', $id)->first();
11276
11277            $quotationId = $budget->id;
11278            $companyIdJob = $budget->company_id;
11279
11280            $query = "SELECT
11281                        COUNT(1) total
11282                    FROM tbl_company_users a
11283                    LEFT JOIN tbl_users b
11284                        ON a.user_id = b.id
11285                    WHERE a.company_id = {$companyId}
11286                    AND b.name = '{$budget->commercial}'
11287                    ORDER BY b.name ASC";
11288
11289            $result = DB::select($query);
11290
11291            $commercial = $budget->commercial;
11292
11293            if ($result[0]->total == 0) {
11294                $commercial = $data['created_by'];
11295            }
11296
11297            $r = new Request([
11298                'created_by' => $commercial,
11299            ]);
11300
11301            $result = $this->get_number($r, $companyId, 1);
11302            $newNumber = $result->original['number'];
11303
11304            TblQuotations::where('id', $id)->update(
11305                [
11306                    'quote_id' => $newNumber,
11307                    'company_id' => $companyId,
11308                    'from_company_id' => $budget->company_id,
11309                    'commercial' => $commercial,
11310                ]
11311            );
11312
11313            // FIRE-1253: keep legacy quote_id-shaped pointers alive across the
11314            // renumber. Rows that stored the internal id need no fix (id is
11315            // immutable). Rows that stored the *old* quote_id (Lambda's other
11316            // historical shape) would otherwise orphan into "no encontrado".
11317            $oldQuoteId = $budget->quote_id;
11318            if ($oldQuoteId !== null && $oldQuoteId !== $newNumber) {
11319                TblQuotations::where('id_solicitud_duplicity', $oldQuoteId)
11320                    ->update(['id_solicitud_duplicity' => $newNumber]);
11321
11322                TblQuotations::where('id_solicitud_duplicity', 'R'.$oldQuoteId)
11323                    ->update(['id_solicitud_duplicity' => 'R'.$newNumber]);
11324            }
11325
11326            $job = TblOngoingJobs::where('quotation_id', $quotationId)->first();
11327
11328            $jobId = null;
11329
11330            if ($job) {
11331                $jobId = $job->id;
11332
11333                $query = "SELECT
11334                            COUNT(1) total
11335                        FROM tbl_company_users a
11336                        LEFT JOIN tbl_users b
11337                            ON a.user_id = b.id
11338                        WHERE a.company_id = {$companyId}
11339                        AND b.name = '{$job->responsible_for_work}'
11340                        ORDER BY b.name ASC";
11341
11342                $result = DB::select($query);
11343
11344                $responsibleForWork = $job->responsible_for_work;
11345
11346                if ($result[0]->total == 0) {
11347                    $responsibleForWork = $data['created_by'];
11348                }
11349
11350                TblOngoingJobs::where('quotation_id', $id)->update(
11351                    [
11352                        'quote_id' => $newNumber,
11353                        'company_id' => $companyId,
11354                        'responsible_for_work' => $responsibleForWork,
11355                    ]
11356                );
11357            }
11358
11359            // FIRE-1145: was Cache::flush() — move_budget_and_job touches both quotations and ongoing_jobs lists.
11360            ResultCache::forgetDomain(['quotations', 'ongoing_jobs']);
11361
11362            return response([
11363                'message' => 'OK',
11364                'quotation_id' => $quotationId,
11365                'job_id' => $jobId,
11366            ]);
11367
11368        } catch (\Exception $e) {
11369            report(AppException::fromException($e, 'MOVE_BUDGET_AND_JOB_EXCEPTION'));
11370
11371            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11372        }
11373    }
11374
11375    public function list_quotation_analytics_by_types_of_budgets_created_per_week(Request $request): ResponseFactory|HttpResponse
11376    {
11377
11378        try {
11379
11380            $data = $request->all();
11381            $companyId = addslashes((string) $data['company_id']);
11382            $field = $data['field'];
11383
11384            $where = '';
11385            $whereYear = '';
11386            $dateLflArray = [];
11387            $companyIds = $this->companyIds;
11388
11389            if ($companyId != 0) {
11390                $companyIds = [$companyId];
11391            }
11392
11393            $acc = '';
11394            if ($field == 'acceptance_date') {
11395                $acc = ' AND q.acceptance_date IS NOT NULL ';
11396                // $field = 'created_at';
11397
11398                if (@$data['data_to_display'] == 4) {
11399                    $field = 'created_at';
11400                    $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
11401                }
11402            } else {
11403                $field = 'created_at';
11404                $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
11405            }
11406
11407            if (isset($data['years']) && $data['years'] != null) {
11408
11409                if (count($data['years']) > 0) {
11410                    foreach ($data['years'] as $year) {
11411                        if (isset($data['week']) && $data['week'] != null) {
11412                            $w = sprintf('%02d', $data['week']);
11413                            $whereYear .= " AND YEARWEEK(q.{$field}, 1) = '{$year}{$w}'";
11414                        } else {
11415                            $whereYear .= " AND YEAR(q.{$field}) = {$year}";
11416                        }
11417                    }
11418                }
11419            }
11420
11421            foreach ($companyIds as $v) {
11422
11423                $lflWhere = " AND q.company_id = {$v} ";
11424
11425                $query = "SELECT
11426                            CONCAT(
11427                                DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field}),
11428                                ' - ',
11429                                DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field})
11430                            ) AS date_like,
11431                            YEAR(q.{$field}) 'year',
11432                            DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
11433                            DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
11434                            {$v} 'company_id'
11435                        FROM
11436                            tbl_quotations q
11437                        WHERE
11438                            q.{$field} IS NOT NULL
11439                            AND q.for_add = 0
11440                            {$lflWhere}
11441                            {$whereYear}
11442                        GROUP BY YEAR(q.{$field})
11443                        ORDER BY YEAR(q.{$field}) DESC";
11444
11445                $dateLike = DB::select($query);
11446
11447                $dateLflArray[$v] = $dateLike;
11448            }
11449
11450            $isFy = true;
11451
11452            if (isset($data['ytd']) && $data['ytd'] != null && $data['ytd'] == true) {
11453                $isFy = false;
11454                $ytdArray = [];
11455                $ytdAcceptanceArray = [];
11456                $lflCompanyIds = [];
11457                foreach ($dateLflArray as $k => $v) {
11458                    if (empty($v)) {
11459                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
11460                    }
11461
11462                    foreach ($dateLflArray[$k] as $item) {
11463                        $year = $item->year;
11464                        $now = date('m-d');
11465                        array_push($ytdArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
11466                    }
11467
11468                    $ytdArray = implode(' OR ', $ytdArray);
11469                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
11470                    $ytdArray = [];
11471                }
11472
11473                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
11474                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
11475            }
11476
11477            if (isset($data['lfl']) && $data['lfl'] != null && $data['lfl'] == true) {
11478                $isFy = false;
11479                $lflArray = [];
11480                $ytdAcceptanceArray = [];
11481                $lflCompanyIds = [];
11482                foreach ($dateLflArray as $k => $v) {
11483                    if (empty($v)) {
11484                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
11485                    }
11486
11487                    foreach ($dateLflArray[$k] as $item) {
11488                        $year = $item->year;
11489                        $min_date_like = $item->min_date_like;
11490                        $max_date_like = $item->max_date_like;
11491                        array_push($lflArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
11492                    }
11493
11494                    $lflArray = implode(' OR ', $lflArray);
11495                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
11496                    $lflArray = [];
11497                }
11498
11499                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
11500                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
11501            }
11502
11503            if ($isFy) {
11504                if ($companyId != 0) {
11505                    $where .= " AND q.company_id = {$companyId} ";
11506                } else {
11507                    $where .= " AND q.company_id IN ({$this->companyId})";
11508                }
11509            }
11510
11511            if (isset($data['source']) && $data['source'] != null) {
11512                $where .= " AND s.name = '{$data['source']}'";
11513            }
11514
11515            if (isset($data['month']) && $data['month'] != null) {
11516                $where .= " AND MONTH(q.{$field}) = '{$data['month']}'";
11517            }
11518
11519            if (isset($data['commercial']) && $data['commercial'] != null) {
11520                $where .= " AND q.commercial = '{$data['commercial']}'";
11521            }
11522
11523            if (isset($data['created_by']) && $data['created_by'] != null) {
11524                $where .= " AND q.created_by = '{$data['created_by']}'";
11525            }
11526
11527            if (isset($data['budget_type']) && $data['budget_type'] != null) {
11528                $where .= " AND bt.budget_type_id = {$data['budget_type']}";
11529            }
11530
11531            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
11532                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
11533            }
11534
11535            if (isset($data['budget_status']) && $data['budget_status'] != null) {
11536                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
11537            }
11538
11539            if (isset($data['client_type']) && $data['client_type'] != null) {
11540                $where .= " AND ct.customer_type_id = {$data['client_type']}";
11541            }
11542
11543            if (isset($data['segment_id']) && $data['segment_id'] != null) {
11544                $where .= " AND q.segment_id = {$data['segment_id']}";
11545            }
11546
11547            $col = '1';
11548
11549            if (isset($data['data_to_display']) && $data['data_to_display'] != null) {
11550                if ($data['data_to_display'] == 1) {
11551                    $col = '1';
11552                }
11553
11554                if ($data['data_to_display'] == 2) {
11555                    $col = 'q.amount';
11556                }
11557            }
11558
11559            $budgetTypes = TblBudgetTypes::orderByRaw('ISNULL(priority), priority ASC')->get();
11560            $cols = '';
11561            foreach ($budgetTypes as $item) {
11562                if ($item->name == '' || $item->name == null) {
11563                    $cols .= ",COALESCE(SUM(CASE WHEN bt.name IS NULL {$acc} THEN {$col} ELSE 0 END), 0) AS 'Otros'";
11564                } else {
11565                    $cols .= ",COALESCE(SUM(CASE WHEN bt.name = '{$item->name}' {$acc} THEN {$col} ELSE 0 END), 0) AS '{$item->name}'";
11566                }
11567            }
11568
11569            $budgetTypeGroups = TblBudgetTypeGroups::orderByRaw('ISNULL(priority), priority ASC')->get();
11570
11571            $colsGroups = ",COALESCE(SUM(CASE WHEN bt.name IS NULL {$acc} THEN {$col} END), 0) AS Otros";
11572
11573            foreach ($budgetTypeGroups as $item) {
11574                $budgetTypeGroupName = str_replace(' ', '', $item->name).$item->budget_type_group_id;
11575                $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
11576                $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN {$col} END), 0) AS '{$budgetTypeGroupName}'";
11577            }
11578
11579            $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN {$col} END), 0) AS total";
11580
11581            $col = $colsGroups.$cols;
11582
11583            if (@$data['data_to_display'] == 3) {
11584
11585                $cols = '';
11586                foreach ($budgetTypes as $item) {
11587                    if ($item->name == '' || $item->name == null) {
11588                        $cols .= ",COALESCE(
11589                                        SUM(CASE WHEN bt.name IS NULL {$acc} THEN q.amount ELSE 0 END) /
11590                                        SUM(CASE WHEN bt.name IS NULL {$acc} THEN 1 ELSE 0 END) * 100 , 0
11591                                    ) AS 'Otros'";
11592                    } else {
11593                        $cols .= ",COALESCE(
11594                                        SUM(CASE WHEN bt.name = '{$item->name}' {$acc} THEN q.amount ELSE 0 END) /
11595                                        SUM(CASE WHEN bt.name = '{$item->name}' {$acc} THEN 1 ELSE 0 END), 0
11596                                    ) AS '{$item->name}'";
11597                    }
11598                }
11599
11600                $colsGroups = ",COALESCE(
11601                                (SUM(CASE WHEN bt.name IS NULL {$acc} THEN q.amount END)) /
11602                                (SUM(CASE WHEN bt.name IS NULL {$acc} THEN 1 END))
11603                            , 0) Otros";
11604
11605                foreach ($budgetTypeGroups as $item) {
11606                    $budgetTypeGroupName = str_replace(' ', '', $item->name).$item->budget_type_group_id;
11607                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
11608                    $colsGroups .= ",COALESCE(
11609                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.amount END)) /
11610                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN 1 END))
11611                                    , 0) '{$budgetTypeGroupName}'";
11612                }
11613
11614                $colsGroups .= ",COALESCE(
11615                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN q.amount END)) /
11616                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN 1 END))
11617                                , 0) total";
11618
11619                $col = $colsGroups.$cols;
11620            }
11621
11622            if (@$data['data_to_display'] == 4) {
11623
11624                $cols = '';
11625
11626                foreach ($budgetTypes as $item) {
11627
11628                    if ($item->name == '' || $item->name == null) {
11629                        $cols .= ",COALESCE(
11630                                        SUM(CASE WHEN bt.name IS NULL AND q.acceptance_date IS NOT NULL THEN 1 ELSE 0 END) /
11631                                        SUM(CASE WHEN bt.name IS NULL AND q.created_at IS NOT NULL THEN 1 ELSE 0 END) * 100 , 0
11632                                ) AS 'Otros'";
11633                    } else {
11634                        $cols .= ", COALESCE(
11635                                        SUM(CASE WHEN bt.name = '{$item->name}' AND q.acceptance_date IS NOT NULL THEN 1 END) /
11636                                        SUM(CASE WHEN bt.name = '{$item->name}' AND q.created_at IS NOT NULL THEN 1 END) * 100, 0
11637                                ) AS '{$item->name}'";
11638                    }
11639                }
11640
11641                $colsGroups = ',COALESCE(
11642                                    (SUM(CASE WHEN bt.name IS NULL AND q.acceptance_date IS NOT NULL THEN 1 END)) /
11643                                    (SUM(CASE WHEN bt.name IS NULL AND q.created_at IS NOT NULL THEN 1 END)) * 100
11644                                    , 0) Otros';
11645
11646                foreach ($budgetTypeGroups as $item) {
11647                    $budgetTypeGroupName = str_replace(' ', '', $item->name).$item->budget_type_group_id;
11648                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
11649                    $colsGroups .= ",COALESCE(
11650                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) AND q.acceptance_date IS NOT NULL THEN 1 END)) /
11651                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) AND q.created_at IS NOT NULL THEN 1 END)) * 100
11652                                    , 0) '{$budgetTypeGroupName}'";
11653                }
11654
11655                $colsGroups .= ',COALESCE(
11656                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) AND q.acceptance_date IS NOT NULL THEN 1 END)) /
11657                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) AND q.created_at IS NOT NULL THEN 1 END)) * 100
11658                                    , 0) total';
11659
11660                $col = $colsGroups.$cols;
11661            }
11662
11663            $query = "SELECT
11664                            YEAR(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)) AS 'year',
11665                            LPAD(MONTH(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)), 2, 0) AS 'month',
11666                            LPAD(WEEK(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)), 2, 0) AS 'week',
11667                            DATE_FORMAT(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY), '%W, %M %e') 'namedate',
11668                            GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN q.id END) groupConcatIds
11669                            {$col}
11670                        FROM
11671                            tbl_quotations q
11672                            LEFT JOIN tbl_sources s ON s.source_id = q.source_id
11673                            LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
11674                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
11675                            LEFT JOIN tbl_budget_type_groups btg ON bt.budget_type_group_id = btg.budget_type_group_id
11676                            LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
11677                        WHERE
11678                            q.{$field} IS NOT NULL
11679                            AND q.for_add = 0
11680                            AND q.budget_type_id IS NOT NULL
11681                            AND q.budget_type_id != 7
11682                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
11683                            {$where}
11684                            {$whereYear}
11685                        GROUP BY
11686                            YEAR(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)),
11687                            MONTH(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)),
11688                            WEEK(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)) WITH ROLLUP
11689                        ORDER BY
11690                            YEAR DESC,
11691                            MONTH ASC,
11692                            WEEK ASC,
11693                            DATE_FORMAT(q.{$field}, '%e') ASC";
11694            // return $query;
11695            $result = DB::select($query);
11696
11697            $query = "SELECT
11698                        btg.budget_type_group_id,
11699                        btg.name,
11700                        (
11701                            SELECT
11702                                GROUP_CONCAT(COALESCE(bt.name, '') ORDER BY ISNULL(bt.priority), bt.priority ASC SEPARATOR '|')
11703                            FROM
11704                                tbl_budget_types bt
11705                            WHERE
11706                                bt.budget_type_group_id = btg.budget_type_group_id
11707                        ) budget_types
11708                        FROM
11709                            tbl_budget_type_groups btg
11710                        ORDER BY
11711                            ISNULL(btg.priority),
11712                            btg.priority ASC";
11713
11714            $budgetTypeGroups = DB::select($query);
11715
11716            foreach ($budgetTypeGroups as $item) {
11717                $item->group_key_name = str_replace(' ', '', $item->name).$item->budget_type_group_id;
11718                $item->budget_types = explode('|', (string) $item->budget_types);
11719            }
11720
11721            return response([
11722                'message' => 'OK',
11723                'data' => $result,
11724                'budgetTypeGroups' => $budgetTypeGroups,
11725            ]);
11726
11727        } catch (\Exception $e) {
11728            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_BY_TYPES_OF_BUDGETS_CREATED_PER_WEEK_EXCEPTION'));
11729
11730            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11731        }
11732    }
11733
11734    public function preview_file($id)
11735    {
11736
11737        try {
11738
11739            $file = TblFiles::where('file_id', $id)->first();
11740
11741            if (! $file) {
11742                return response()->json([
11743                    'message' => 'KO',
11744                    'error' => __('language.file_not_found'),
11745                ], 404);
11746            }
11747
11748            if (! Storage::disk('s3')->exists('uploads/'.$file->filename)) {
11749                return response()->json(['message' => 'File not found'], 404);
11750            }
11751
11752            $url = Storage::disk('s3')->temporaryUrl(
11753                'uploads/'.$file->filename,
11754                now()->addMinutes(5)
11755            );
11756
11757            return response()->json([
11758                'filename' => $file->filename,
11759                'url' => $url,
11760                'uploaded_by' => $file->uploaded_by,
11761                'uploaded_at' => $file->uploaded_at,
11762            ]);
11763
11764        } catch (\Exception $e) {
11765            report(AppException::fromException($e, 'PREVIEW_FILE_EXCEPTION'));
11766
11767            return response()->json([
11768                'message' => 'KO',
11769                'error' => $e->getMessage(),
11770            ], 500);
11771        }
11772    }
11773
11774    public function get_past_added_quotation(Request $request): ResponseFactory|HttpResponse
11775    {
11776
11777        try {
11778
11779            $data = $request->all();
11780            $keyword = addslashes((string) $data['keyword']);
11781            $result = [];
11782
11783            if (! empty($keyword)) {
11784                $array = explode(' ', $keyword);
11785
11786                $where = '';
11787
11788                $availableParameters = ['client', 'email'];
11789
11790                $searchTextArray = explode(' ', $keyword);
11791
11792                $searchArray = [];
11793                $matchScoreArray = [];
11794                foreach ($availableParameters as $field) {
11795                    foreach ($searchTextArray as $word) {
11796                        array_push($searchArray, "({$field} LIKE '%{$word}%')");
11797                        array_push($matchScoreArray, "CASE WHEN {$field} LIKE '%{$word}%' THEN 1 ELSE 0 END");
11798                    }
11799                }
11800
11801                $searchArray = implode(' OR ', $searchArray);
11802                $matchScoreArray = implode(' + ', $matchScoreArray);
11803                $matchScoreCol = "({$matchScoreArray})";
11804                $where .= " AND ({$searchArray}) ";
11805
11806                $query = "SELECT
11807                            id,
11808                            client,
11809                            segment_id,
11810                            CONCAT(`client`, ' - ', email) `client_email`,
11811                            email,
11812                            phone_number,
11813                            customer_type_id,
11814                            {$matchScoreCol} match_score
11815                        FROM tbl_quotations
11816                        WHERE for_add = 0
11817                        AND email IS NOT NULL AND phone_number IS NOT NULL
11818                        {$where}
11819                        GROUP BY client, email
11820                        ORDER BY match_score DESC, client ASC
11821                        ";
11822
11823                $result = DB::select($query);
11824            }
11825
11826            return response(['message' => 'OK', 'data' => $result]);
11827
11828        } catch (\Exception $e) {
11829            report(AppException::fromException($e, 'GET_PAST_ADDED_QUOTATION_EXCEPTION'));
11830
11831            return response(['message' => 'KO', 'error' => $e->getMessage()]);
11832        }
11833    }
11834
11835    public function send_acceptance_notification($quotationId, $companyId, $userId, $updatedBy): void
11836    {
11837
11838        $budget = TblQuotations::where('id', $quotationId)->first();
11839
11840        if ($budget != null) {
11841            $to = TblToAcceptanceNotifications::where('company_id', $companyId)->get();
11842            $cc = TblCcAcceptanceNotifications::where('company_id', $companyId)->get();
11843
11844            if (count($to) > 0 && count($cc) > 0) {
11845
11846                $company = TblCompanies::where('company_id', $companyId)->first();
11847
11848                $quoteId = $budget->quote_id;
11849                $amount = $this->currency($budget->amount, 1);
11850
11851                $url = config('app.frontend_url')."orders/{$quotationId}?company_id={$companyId}";
11852                $href = "<a href='{$url}'>{$quoteId}</a>";
11853
11854                $imgpath = file_get_contents(public_path('fireservicetitan.png'));
11855                $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
11856
11857                $body = __('language.send_acceptance_notification.body_hello');
11858                $body .= __('language.send_acceptance_notification.body_message');
11859
11860                $body = str_replace('{{client}}', $budget->client, $body);
11861                $body = str_replace('{{username}}', $updatedBy, $body);
11862                $body = str_replace('{{company}}', $company->name, $body);
11863                $body = str_replace('{{amount}}', $amount, $body);
11864                $body = str_replace('{{quote_id}}', $href, $body);
11865
11866                $body .= '<p>Fire Service Titan</p>';
11867                $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
11868
11869                $html = '<!DOCTYPE html>';
11870                $html .= '<html>';
11871                $html .= '<head>';
11872                $html .= '<meta charset="UTF-8">';
11873                $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
11874                $html .= '</head>';
11875                $html .= '<body>';
11876                $html .= $body;
11877                $html .= '</body>';
11878                $html .= '</html>';
11879
11880                $subject = __('language.send_acceptance_notification.subject');
11881                $subject = str_replace('{{quote_id}}', $quoteId, $subject);
11882
11883                $email = new Mail;
11884
11885                $user = TblUsers::where('id', $userId)->first();
11886
11887                if (config('services.sendgrid.staging')) {
11888                    // Staging: SENDGRID_TO_EMAIL only, never the salesperson.
11889                    if (! config('services.sendgrid.to_email')) {
11890                        return;
11891                    }
11892                    $email->addTo(config('services.sendgrid.to_email'));
11893                } else {
11894
11895                    $emails = [];
11896
11897                    foreach ($to as $item) {
11898                        if (! in_array($item->email, $emails)) {
11899                            array_push($emails, $item->email);
11900                            $email->addTo($item->email);
11901                        }
11902                    }
11903
11904                    foreach ($cc as $item) {
11905                        if (! in_array($item->email, $emails)) {
11906                            array_push($emails, $item->email);
11907                            $email->addCc($item->email);
11908                        }
11909                    }
11910
11911                    $email->addCc($user->email);
11912                    array_push($emails, $user->email);
11913
11914                    $ccUser = TblUsers::where('name', $budget->commercial)->first();
11915
11916                    if ($ccUser) {
11917                        if (! in_array($ccUser->email, $emails)) {
11918                            $email->addCc($ccUser->email);
11919                        }
11920                    }
11921                }
11922
11923                $email->setFrom('fire@fire.es', 'Fire Service Titan');
11924                $email->setSubject($subject);
11925                $email->addContent('text/html', $html);
11926
11927                $email->addAttachment(
11928                    $imgpath,
11929                    'image/png',
11930                    'fireservicetitan.png',
11931                    'inline',
11932                    'fireservicetitan'
11933                );
11934
11935                // FIRE-1930: internal email to the operations team, so it
11936                // follows the commercial kill switch. Gated (null) means
11937                // nothing was sent — skip the "email sent" comment too.
11938                $response = SendgridDispatcher::send(
11939                    $email,
11940                    SendgridDispatcher::BUCKET_COMMERCIAL,
11941                    (int) $companyId,
11942                    'Quotations::send_acceptance_notification',
11943                );
11944
11945                if ($response === null) {
11946                    return;
11947                }
11948
11949                if ($response->statusCode() == 202) {
11950                    $this->addUpdateLog($quotationId, $userId, 'send_acceptance_notification', null, null, 5);
11951                    $comment = 'Email de aprobación automática enviada al equipo de opearciones el '.date('Y-m-d H:i:s');
11952                    $budget->last_follow_up_comment = $budget->last_follow_up_comment."\n".$comment;
11953
11954                    TblQuotations::where('id', $quotationId)->update(
11955                        [
11956                            'last_follow_up_comment' => $budget->last_follow_up_comment,
11957                        ]
11958                    );
11959
11960                    Log::channel('email_log')->info('ID:'.$quoteId.' - ACCEPTANCE EMAIL NOTIFICATION SENT');
11961                } else {
11962                    $error = true;
11963                    Log::channel('email_log')->error('ID:'.$quoteId.' - '.$response->body());
11964                }
11965
11966            }
11967        }
11968    }
11969
11970    public function get_total_quotations_by_budget_status(Request $request): ResponseFactory|HttpResponse
11971    {
11972
11973        try {
11974
11975            $data = $request->all();
11976
11977            $companyId = addslashes((string) $data['company_id']);
11978
11979            $where = '';
11980
11981            if ($companyId != 0) {
11982                $where = " AND a.company_id = {$companyId} ";
11983            } else {
11984                $where = " AND a.company_id IN ({$this->companyId}) ";
11985            }
11986
11987            $user = null;
11988
11989            if (isset($data['commercial'])) {
11990                if ($data['commercial'] != 'All') {
11991                    $user = TblUsers::where('name', $data['commercial'])->first();
11992                }
11993            } else {
11994                $user = TblUsers::where('id', $this->userId)->first();
11995            }
11996
11997            $totalPendingFollowUps = 0;
11998            $totalRequestAndVisit = 0;
11999            $totalError = 0;
12000            $totalG3WError = 0;
12001            $totalSendToClient = 0;
12002
12003            $d = false;
12004
12005            if ($user != null) {
12006                $where .= " AND a.commercial = '{$user->name}' ";
12007                $d = true;
12008            }
12009
12010            if ($data['commercial'] == 'All') {
12011                $d = true;
12012            }
12013
12014            if ($d) {
12015                // Clicking this tile applies the is_send_follow_up filter, so
12016                // both use the same rule.
12017                $query = 'SELECT COUNT(DISTINCT a.id) total
12018                        FROM tbl_quotations a
12019                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
12020                        WHERE 1 = 1 '.self::pendingFollowUpSql()." {$where}";
12021
12022                $result = DB::select($query);
12023
12024                $totalPendingFollowUps = $result[0]->total;
12025
12026                $query = "SELECT
12027                                COUNT(1) total
12028                            FROM
12029                                tbl_quotations a
12030                            WHERE
12031                                a.budget_status_id IN (6, 8)
12032                                AND a.for_add = 0
12033                                {$where}
12034                            ";
12035
12036                $result = DB::select($query);
12037
12038                $totalRequestAndVisit = $result[0]->total;
12039
12040                $blacklist = implode('|', $this->getBlacklistEmails());
12041
12042                // FIRE-864 follow-up (04/05): anchored email pattern so the
12043                // badge count agrees with the bucket reclassifier on emails
12044                // like `no tiene@notien.com`. See comment at the matching
12045                // list_quotations branch above.
12046                // FIRE-1560: mismo whitelist reducido que el filtro de lista
12047                // arriba — solo estados vivos donde el email error sigue
12048                // siendo accionable.
12049                $query = "SELECT
12050                                COUNT(1) total
12051                            FROM
12052                                tbl_quotations a
12053                            WHERE
12054                                a.for_add = 0 AND
12055                                (
12056                                    a.x_status IN ('Error','Error - Bounce','Error - Spam')
12057                                    OR (
12058                                        a.email IS NULL
12059                                        OR TRIM(a.email) = ''
12060                                        OR a.email NOT REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}([[:space:]]*,[[:space:]]*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})*$'
12061                                        OR a.email REGEXP '($blacklist)'
12062                                    )
12063                                )
12064                                AND a.budget_status_id IN(1, 2, 11)
12065                                AND (a.send_channel IS NULL OR a.send_channel = 'email')
12066                                    {$where}
12067                            ";
12068                // FIRE-1377: keep the "emails with error" badge count in sync
12069                // with the grid filter — only email-channel budgets count.
12070
12071                $result = DB::select($query);
12072
12073                $totalError = $result[0]->total;
12074
12075                // Exclude IFEX (commercial='Ifex') — see matching clause in
12076                // list_orders_table's is_g3w_warning branch. IFEX rows can
12077                // carry g3w_warning=1 but they belong to a separate sync
12078                // integration, not to the G3W bucket.
12079                //
12080                // FIRE-1560: presupuestos rechazados/anulados no deben
12081                // contar en el tile. Mismo NOT IN que en list_orders_table.
12082                $query = "SELECT
12083                                COUNT(1) total
12084                                FROM
12085                                    tbl_quotations a
12086                                WHERE
12087                                    a.g3w_warning = 1
12088                                    AND a.for_add = 0
12089                                    AND (a.commercial IS NULL OR a.commercial <> 'Ifex')
12090                                    AND a.budget_status_id NOT IN (4, 5, 7, 12, 15, 17, 18, 20, 21, 22)
12091                                    {$where}
12092                                ";
12093
12094                $result = DB::select($query);
12095
12096                $totalG3WError = $result[0]->total;
12097
12098                $query = "SELECT
12099                                COUNT(1) total
12100                                FROM
12101                                    tbl_quotations a
12102                                WHERE
12103                                    a.budget_status_id = (SELECT budget_status_id FROM tbl_budget_status WHERE name = 'Validado')
12104                                    AND a.total_sent = 0
12105                                    AND a.for_add = 0
12106                                    -- Clicking this tile applies the
12107                                    -- is_send_to_client filter, which now drops
12108                                    -- budgets awaiting approval; exclude them
12109                                    -- here too so the badge matches the list it
12110                                    -- opens.
12111                                    AND ".self::NOT_PENDING_APPROVAL_SQL."
12112                                    {$where}
12113                                ";
12114
12115                $result = DB::select($query);
12116
12117                $totalSendToClient = $result[0]->total;
12118            }
12119
12120            return response([
12121                'message' => 'OK',
12122                'userId' => ($user) ? $user->id : null,
12123                'totalPendingFollowUps' => $totalPendingFollowUps,
12124                'totalRequestAndVisit' => $totalRequestAndVisit,
12125                'totalError' => $totalError,
12126                'totalG3WError' => $totalG3WError,
12127                'totalSendToClient' => $totalSendToClient,
12128            ]);
12129
12130        } catch (\Exception $e) {
12131            report(AppException::fromException($e, 'GET_TOTAL_QUPTATIONS_BY_BUDGET_STATUS_EXCEPTION'));
12132
12133            return response(['message' => 'KO', 'error' => $e->getMessage()]);
12134        }
12135
12136    }
12137
12138    public function sendgrid_webhook_receiver(Request $request)
12139    {
12140
12141        try {
12142
12143            $data = $request->all();
12144
12145            $jsonBody = [];
12146            $order = [];
12147            $orderEmails = [];
12148
12149            Log::channel('email_log')->info('WEBHOOK: '.json_encode($data));
12150
12151            $quoteId = null;
12152            $touchedQuoteIds = [];
12153
12154            // FIRE-864: SendGrid bounce/drop events should flag the quotation
12155            // so the sales flow shows the truth instead of defaulting to
12156            // "Enviado".
12157            // FIRE-1280: a SendGrid error event means Titan DID attempt the
12158            // send and it failed, so the correct status is "Fallo envío -
12159            // correo erróneo" (21), NOT "Correo erróneo" (22). Status 22 is
12160            // reserved for invalid addresses we never even tried to send to.
12161            $errorEvents = ['bounce', 'dropped', 'blocked', 'spamreport'];
12162
12163            foreach ($data as $item) {
12164                $matches = explode('.', (string) $item['sg_message_id']);
12165                $messageId = $matches[0];
12166
12167                Log::channel('email_log')->info('MESSAGE-ID: '.$messageId);
12168
12169                $result = TblSendgridWebhook::where('x_message_id', $messageId)->first();
12170                if (! $result) {
12171                    Log::channel('email_log')->warning("No tbl_sendgrid_webhook row for x_message_id={$messageId}. Skipping event.");
12172
12173                    continue;
12174                }
12175                $quoteId = $result->quotation_id;
12176                Log::channel('email_log')->info('SENDGRID-BODY: '.json_encode($result));
12177
12178                if (empty($order)) {
12179                    $order = TblQuotations::where('x_message_id', $messageId)->first();
12180                    if ($order) {
12181                        $quoteId = $order->id;
12182                        $orderEmails = explode(',', (string) $order->email);
12183                    }
12184                }
12185
12186                if ($result->json_body == null) {
12187                    array_push($jsonBody, $item);
12188                } else {
12189                    $jsonBody = json_decode((string) $result->json_body);
12190                    array_push($jsonBody, $item);
12191                }
12192
12193                Log::channel('email_log')->info('JSON-BODY: '.json_encode($jsonBody));
12194
12195                TblSendgridWebhook::where('x_message_id', $messageId)->update(
12196                    [
12197                        'json_body' => json_encode($jsonBody),
12198                        'updated_at' => date('Y-m-d H:i:s'),
12199                    ]
12200                );
12201
12202                // FIRE-1280: mark quotation as "Fallo envío - correo erróneo"
12203                // (21) on bounce/drop — the arrival of a SendGrid event proves
12204                // a send was attempted, so this is a delivery failure, not a
12205                // never-tried invalid address (22).
12206                // FIRE-1072: do not clobber rows the commercial has manually
12207                // moved off the send pipeline. Status 3 (Aceptado) and 7
12208                // (Rechazado) are terminal, status 12 (En curso) means the
12209                // rep is working it. A pre-classified "Correo erróneo" (22) IS
12210                // promoted to 21 here because the SendGrid event tells us Titan
12211                // did try to send. A row already at 21 is left untouched.
12212                if ($quoteId !== null && isset($item['event']) && in_array(strtolower((string) $item['event']), $errorEvents, true)) {
12213                    // Resolve the row for THIS event's quotation, not the sticky
12214                    // $order (which holds the first message's quotation across a
12215                    // multi-message webhook batch) — otherwise the protected-
12216                    // status guard and the update could target different rows.
12217                    $current = TblQuotations::where('id', $quoteId)->first();
12218                    $protectedStatuses = [3, 7, 12];
12219                    if ($current && (int) $current->budget_status_id !== 21 && ! in_array((int) $current->budget_status_id, $protectedStatuses, true)) {
12220                        TblQuotations::where('id', $quoteId)->update(['budget_status_id' => 21]);
12221                        // budget_status_id is shown in list_quotations.
12222                        ResultCache::forgetDomain('quotations');
12223                        $this->addUpdateLog($quoteId, 'SendGrid', 'budget_status_id', $current->budget_status_id, 21, 4);
12224                        Log::channel('email_log')->info("FIRE-1280: quotation {$quoteId} → budget_status_id=21 (fallo envío - correo erróneo) due to SendGrid event '{$item['event']}'.");
12225                    } elseif ($current) {
12226                        Log::channel('email_log')->info("FIRE-1072: skipped reclassifying quotation {$quoteId} (current status {$current->budget_status_id}) for SendGrid event '{$item['event']}'.");
12227                    }
12228                }
12229
12230                if ($quoteId != null) {
12231                    $touchedQuoteIds[$quoteId] = true;
12232                }
12233            }
12234
12235            // Sentry perf (sendgridWebhookReceiver N+1 / slow DB): get_files()
12236            // is ~8 queries and used to run once per EVENT, with a full
12237            // quotations-cache flush each time. It derives x_status from the
12238            // latest stored json_body, so running it once per quotation after
12239            // the whole batch is stored gives the same final state. It flushes
12240            // the quotations cache itself when x_status changes; the only
12241            // other list-visible write here (budget_status_id) flushes above.
12242            foreach (array_keys($touchedQuoteIds) as $touchedQuoteId) {
12243                $this->get_files($touchedQuoteId);
12244            }
12245
12246        } catch (\Exception $e) {
12247            report(AppException::fromException($e, 'SENDGRID_WEBHOOK_RECEIVER_EXCEPTION'));
12248
12249            return response(['message' => 'KO', 'error' => $e->getMessage()]);
12250        }
12251
12252        return response(['message' => 'OK']);
12253    }
12254
12255    public function isEmailValid($email): bool
12256    {
12257        // Regular expression pattern for email validation
12258        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
12259
12260        // Check if the email matches the pattern
12261        if (preg_match($pattern, (string) $email)) {
12262            return true; // Valid email
12263        } else {
12264            return false; // Invalid email
12265        }
12266    }
12267
12268    public function list_email_status($companyId): ResponseFactory|HttpResponse
12269    {
12270        try {
12271            $params = [];
12272
12273            if ($companyId != 0) {
12274                $where = ' company_id = ? ';
12275                $params[] = $companyId;
12276            } else {
12277                $ids = is_string($this->companyId) ? explode(',', $this->companyId) : $this->companyId;
12278                $ids = array_filter($ids);
12279
12280                if (empty($ids)) {
12281                    return response(['message' => 'OK', 'data' => []]);
12282                }
12283
12284                $placeholders = implode(',', array_fill(0, count($ids), '?'));
12285                $where = " company_id IN ($placeholders) ";
12286                $params = array_values($ids);
12287            }
12288
12289            $query = "SELECT DISTINCT x_status FROM tbl_quotations WHERE {$where} AND x_status IS NOT NULL";
12290            $result = DB::select($query, $params);
12291
12292            return response([
12293                'message' => 'OK',
12294                'data' => $result,
12295            ]);
12296
12297        } catch (\Exception $e) {
12298            report($e);
12299
12300            return response(['message' => 'KO', 'error' => $e->getMessage()], 500);
12301        }
12302    }
12303
12304    public function list_quotation_analytics_commercial(Request $request): ResponseFactory|HttpResponse
12305    {
12306
12307        try {
12308
12309            $data = $request->all();
12310            $companyId = addslashes((string) $data['company_id']);
12311            $field = $data['field'];
12312
12313            $where = '';
12314            $whereYear = '';
12315            $dateLflArray = [];
12316            $companyIds = $this->companyIds;
12317            $whereQ = '';
12318
12319            $acc = '';
12320            if ($field == 'acceptance_date') {
12321                $acc = ' AND q.acceptance_date IS NOT NULL ';
12322                // $field = 'created_at';
12323
12324                if (@$data['data_to_display'] == 4) {
12325                    $field = 'created_at';
12326                    $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
12327                    $whereQ .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
12328                }
12329            } else {
12330                $field = 'created_at';
12331                $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
12332                $whereQ .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
12333            }
12334
12335            if (isset($data['years']) && $data['years'] != null) {
12336                $years = implode(',', $data['years']);
12337                if (count($data['years']) > 0) {
12338                    $whereYear = " AND YEAR(q.{$field}) IN ({$years})";
12339                }
12340            }
12341
12342            if ($companyId != 0) {
12343                $companyIds = [$companyId];
12344            }
12345
12346            foreach ($companyIds as $v) {
12347
12348                $lflWhere = " AND q.company_id = {$v} ";
12349
12350                $query = "SELECT
12351                            CONCAT(
12352                                DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field}),
12353                                ' - ',
12354                                DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field})
12355                            ) AS date_like,
12356                            YEAR(q.{$field}) 'year',
12357                            DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
12358                            DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
12359                            {$v} 'company_id'
12360                        FROM
12361                            tbl_quotations q
12362                        WHERE
12363                            q.{$field} IS NOT NULL
12364                            AND q.for_add = 0
12365                            {$lflWhere}
12366                            {$whereYear}
12367                        GROUP BY YEAR(q.{$field})
12368                        ORDER BY YEAR(q.{$field}) DESC";
12369
12370                $dateLike = DB::select($query);
12371
12372                $dateLflArray[$v] = $dateLike;
12373            }
12374
12375            $isFy = true;
12376
12377            if (isset($data['ytd']) && $data['ytd'] != null && $data['ytd'] == true) {
12378                $isFy = false;
12379                $ytdArray = [];
12380                $ytdAcceptanceArray = [];
12381                $lflCompanyIds = [];
12382                foreach ($dateLflArray as $k => $v) {
12383                    if (empty($v)) {
12384                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
12385                    }
12386
12387                    foreach ($dateLflArray[$k] as $item) {
12388                        $year = $item->year;
12389                        $now = date('m-d');
12390                        array_push($ytdArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
12391                    }
12392
12393                    $ytdArray = implode(' OR ', $ytdArray);
12394                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
12395                    $ytdArray = [];
12396                }
12397
12398                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
12399                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
12400                $whereQ .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
12401            }
12402
12403            if (isset($data['lfl']) && $data['lfl'] != null && $data['lfl'] == true) {
12404                $isFy = false;
12405                $lflArray = [];
12406                $ytdAcceptanceArray = [];
12407                $lflCompanyIds = [];
12408                foreach ($dateLflArray as $k => $v) {
12409                    if (empty($v)) {
12410                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
12411                    }
12412
12413                    foreach ($dateLflArray[$k] as $item) {
12414                        $year = $item->year;
12415                        $min_date_like = $item->min_date_like;
12416                        $max_date_like = $item->max_date_like;
12417                        array_push($lflArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
12418                    }
12419
12420                    $lflArray = implode(' OR ', $lflArray);
12421                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
12422                    $lflArray = [];
12423                }
12424
12425                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
12426                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
12427                $whereQ .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
12428            }
12429
12430            if ($isFy) {
12431                if ($companyId != 0) {
12432                    $where .= " AND q.company_id = {$companyId} ";
12433                    $whereQ .= " AND q.company_id = {$companyId} ";
12434                } else {
12435                    $where .= " AND q.company_id IN ({$this->companyId})";
12436                    $whereQ .= " AND q.company_id IN ({$this->companyId})";
12437                }
12438            }
12439
12440            if (isset($data['source']) && $data['source'] != null) {
12441                $where .= " AND s.name = '{$data['source']}'";
12442            }
12443
12444            if (isset($data['month']) && $data['month'] != null) {
12445                $where .= " AND MONTH(q.{$field}) = '{$data['month']}'";
12446            }
12447
12448            if (isset($data['week']) && $data['week'] != null) {
12449                $where .= " AND WEEK(q.{$field}) = '{$data['week']}'";
12450            }
12451
12452            if (isset($data['commercial']) && $data['commercial'] != null) {
12453                $where .= " AND q.commercial = '{$data['commercial']}'";
12454            }
12455
12456            if (isset($data['created_by']) && $data['created_by'] != null) {
12457                $where .= " AND q.created_by = '{$data['created_by']}'";
12458            }
12459
12460            if (isset($data['budget_type']) && $data['budget_type'] != null) {
12461                $where .= " AND bt.budget_type_id = {$data['budget_type']}";
12462            }
12463
12464            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
12465                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
12466            }
12467
12468            if (isset($data['budget_status']) && $data['budget_status'] != null) {
12469                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
12470            }
12471
12472            if (isset($data['client_type']) && $data['client_type'] != null) {
12473                $where .= " AND ct.customer_type_id = {$data['client_type']}";
12474            }
12475
12476            if (isset($data['segment_id']) && $data['segment_id'] != null) {
12477                $where .= " AND q.segment_id = {$data['segment_id']}";
12478            }
12479
12480            $col = '1';
12481
12482            if (isset($data['data_to_display']) && $data['data_to_display'] != null) {
12483                if ($data['data_to_display'] == 1) {
12484                    $col = '1';
12485                }
12486
12487                if ($data['data_to_display'] == 2) {
12488                    $col = 'q.amount';
12489                }
12490            }
12491
12492            $query = "SELECT
12493                        q.commercial 'name',
12494                        COUNT(q.commercial) totalCommercial
12495                    FROM tbl_quotations q
12496                    WHERE
12497                        q.for_add = 0
12498                        AND q.{$field} IS NOT NULL
12499                        {$whereQ}
12500                    GROUP BY q.commercial
12501                    HAVING COUNT(q.commercial) > 0
12502                    ORDER BY totalCommercial DESC";
12503
12504            $resultCommercials = DB::select($query);
12505
12506            $now = TblQuotations::whereIn('company_id', $this->companyIds)->orderBy($field, 'DESC')->pluck($field)->first();
12507            $weekNumber = date('W', strtotime((string) $now));
12508            $thisWeek = date('Y-m-d', strtotime($now.' - '.(date('N', strtotime((string) $now)) - 1).' days'));
12509
12510            $query = "SELECT
12511                        q.commercial 'name',
12512                        COUNT(q.commercial) totalCommercial
12513                    FROM tbl_quotations q
12514                    WHERE
12515                        q.for_add = 0
12516                        AND q.{$field} IS NOT NULL
12517                        AND YEARWEEK(q.{$field}, 1) = YEARWEEK(NOW(), 1)
12518                        {$whereQ}
12519                    GROUP BY q.commercial
12520                    HAVING COUNT(q.commercial) > 0
12521                    ORDER BY totalCommercial DESC";
12522
12523            $resultCommercialsOrder = DB::select($query);
12524
12525            $namesToRemove = [];
12526
12527            foreach ($resultCommercialsOrder as $item) {
12528                $namesToRemove[$item->name] = true;
12529            }
12530
12531            $resultArray = [];
12532            foreach ($resultCommercials as $item) {
12533                if (! isset($namesToRemove[$item->name])) {
12534                    $resultArray[] = $item;
12535                }
12536            }
12537
12538            $resultCommercials = array_merge($resultCommercialsOrder, $resultArray);
12539
12540            $cols = '';
12541
12542            $colsGroupConcatIds = '';
12543
12544            foreach ($resultCommercials as $item) {
12545                $cols .= ",COALESCE(
12546                    SUM(
12547                        CASE WHEN q.commercial = '{$item->name}' {$acc} THEN {$col} ELSE 0 END
12548                    ), 0
12549                ) '{$item->name}'";
12550
12551                $colsGroupConcatIds .= ",GROUP_CONCAT(CASE WHEN q.commercial = '{$item->name}' {$acc} THEN q.id END) 'groupConcatIds-{$item->name}'";
12552            }
12553
12554            $cols .= ",COALESCE(
12555                SUM(
12556                    CASE WHEN q.commercial IS NOT NULL {$acc} THEN {$col} ELSE 0 END
12557                ), 0
12558            ) total";
12559
12560            if (@$data['data_to_display'] == 3) {
12561
12562                $cols = '';
12563
12564                foreach ($resultCommercials as $item) {
12565                    $cols .= ",COALESCE(
12566                        (
12567                            SUM(CASE WHEN q.commercial = '{$item->name}' {$acc} THEN q.amount END)
12568                        ) /
12569                        (
12570                            SUM(CASE WHEN q.commercial = '{$item->name}' {$acc} THEN 1 END)
12571                        )
12572                    , 0) '{$item->name}'";
12573                }
12574
12575                $cols .= ",COALESCE(
12576                    (
12577                        SUM(CASE WHEN q.commercial IS NOT NULL {$acc} THEN q.amount END)
12578                    ) /
12579                    (
12580                        SUM(CASE WHEN q.commercial IS NOT NULL {$acc} THEN 1 END)
12581                    )
12582                , 0) total";
12583            }
12584
12585            if (@$data['data_to_display'] == 4) {
12586
12587                $cols = '';
12588
12589                foreach ($resultCommercials as $item) {
12590                    $cols .= ",COALESCE(
12591                        (
12592                            SUM(CASE WHEN q.commercial = '{$item->name}' AND q.acceptance_date IS NOT NULL THEN 1 END)
12593                        ) /
12594                        (
12595                            SUM(CASE WHEN q.commercial = '{$item->name}' AND q.created_at IS NOT NULL THEN 1 END)
12596                        ) * 100
12597                    , 0) '{$item->name}'";
12598                }
12599
12600                $cols .= ',COALESCE(
12601                    (
12602                        SUM(CASE WHEN q.commercial IS NOT NULL AND q.acceptance_date IS NOT NULL THEN 1 END)
12603                    ) /
12604                    (
12605                        SUM(CASE WHEN q.commercial IS NOT NULL AND q.created_at IS NOT NULL THEN 1 END)
12606                    ) * 100
12607                , 0) total';
12608            }
12609
12610            $query = "SELECT
12611                            YEAR(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)) AS 'year',
12612                            LPAD(MONTH(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)), 2, 0) AS 'month',
12613                            LPAD(WEEK(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)), 2, 0) AS 'week',
12614                            DATE_FORMAT(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY), '%W, %M %e') 'namedate',
12615                            GROUP_CONCAT(
12616                                CASE WHEN q.{$field} IS NOT NULL
12617                                THEN q.id END
12618                            ) AS groupConcatIds
12619                            {$colsGroupConcatIds}
12620                            {$cols}
12621                        FROM
12622                            tbl_quotations q
12623                            LEFT JOIN tbl_sources s ON s.source_id = q.source_id
12624                            LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
12625                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
12626                            LEFT JOIN tbl_budget_type_groups btg ON bt.budget_type_group_id = btg.budget_type_group_id
12627                            LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
12628                        WHERE
12629                            q.{$field} IS NOT NULL
12630                            AND q.for_add = 0
12631                            AND q.budget_type_id != 7
12632                            AND q.budget_type_id IS NOT NULL
12633                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
12634                            {$where}
12635                            {$whereYear}
12636                        GROUP BY
12637                            YEAR(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)),
12638                            MONTH(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)),
12639                            WEEK(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)) WITH ROLLUP
12640                        ORDER BY
12641                            YEAR DESC,
12642                            MONTH ASC,
12643                            WEEK ASC,
12644                            DATE_FORMAT(q.{$field}, '%e') ASC";
12645
12646            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
12647            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
12648
12649            return response([
12650                'message' => 'OK',
12651                'data' => $result,
12652                'commercials' => $resultCommercials,
12653            ]);
12654
12655        } catch (\Exception $e) {
12656            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_COMMERCIAL_EXCEPTION'));
12657
12658            return response(['message' => 'KO', 'error' => $e->getMessage()]);
12659        }
12660    }
12661
12662    public function clear_open_data($companyId): ResponseFactory|HttpResponse
12663    {
12664
12665        try {
12666
12667            $companyIds = [$companyId];
12668            if ($companyId == 0) {
12669                $companyIds = $this->companyIds;
12670            }
12671
12672            $user = TblUsers::where('id', $this->userId)->first();
12673
12674            if (count($companyIds) > 0) {
12675
12676                foreach ($companyIds as $id) {
12677                    $startedAt = date('Y-m-d H:i:s');
12678                    $affectedRows = DB::delete("DELETE FROM tbl_quotations WHERE company_id = {$id} AND for_add = 1 AND DATE_FORMAT(created_at, '%Y-%m-%d') != DATE_FORMAT(NOW(), '%Y-%m-%d')");
12679
12680                    TblOrdersUpdateLogs::create(
12681                        [
12682                            'company_id' => $id,
12683                            'to_process' => 'Orders',
12684                            'status' => 'success',
12685                            'for_add_deleted_affected_rows' => $affectedRows,
12686                            'processed_by' => $user->name,
12687                            'started_at' => $startedAt,
12688                            'ended_at' => date('Y-m-d H:i:s'),
12689                        ]
12690                    );
12691                }
12692            }
12693
12694            return response([
12695                'message' => 'OK',
12696            ]);
12697
12698        } catch (\Exception $e) {
12699            report(AppException::fromException($e, 'CLEAR_OPEN_DATA_EXCEPTION'));
12700
12701            return response(['message' => 'KO', 'error' => $e->getMessage()]);
12702        }
12703
12704    }
12705
12706    public function list_quotation_analytics_order_size(Request $request): ResponseFactory|HttpResponse
12707    {
12708
12709        try {
12710
12711            $data = $request->all();
12712            $companyId = addslashes((string) $data['company_id']);
12713            $field = $data['field'];
12714
12715            $where = '';
12716            $dateLflArray = [];
12717            $whereYear = '';
12718            $companyIds = $this->companyIds;
12719
12720            if ($field == 'acceptance_date') {
12721                if (@$data['data_to_display'] == 4) {
12722                    $field = 'created_at';
12723                    $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
12724                }
12725            } else {
12726                $field = 'created_at';
12727                $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
12728            }
12729
12730            if (isset($data['years']) && $data['years'] != null) {
12731                $years = implode(',', $data['years']);
12732                if (count($data['years']) > 0) {
12733                    $whereYear = " AND YEAR(q.{$field}) IN ({$years})";
12734                }
12735            }
12736
12737            if ($companyId != 0) {
12738                $companyIds = [$companyId];
12739            }
12740
12741            foreach ($companyIds as $v) {
12742
12743                $lflWhere = " AND q.company_id = {$v} ";
12744
12745                $query = "SELECT
12746                            CONCAT(
12747                                DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field}),
12748                                ' - ',
12749                                DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field})
12750                            ) AS date_like,
12751                            YEAR(q.{$field}) 'year',
12752                            DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
12753                            DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
12754                            {$v} 'company_id'
12755                        FROM
12756                            tbl_quotations q
12757                        WHERE
12758                            q.{$field} IS NOT NULL
12759                            AND q.for_add = 0
12760                            {$lflWhere}
12761                            {$whereYear}
12762                        GROUP BY YEAR(q.{$field})
12763                        ORDER BY YEAR(q.{$field}) DESC";
12764
12765                $dateLike = DB::select($query);
12766
12767                $dateLflArray[$v] = $dateLike;
12768            }
12769
12770            $isFy = true;
12771
12772            if (isset($data['ytd']) && $data['ytd'] != null && $data['ytd'] == true) {
12773                $isFy = false;
12774                $ytdArray = [];
12775                $ytdAcceptanceArray = [];
12776                $lflCompanyIds = [];
12777                foreach ($dateLflArray as $k => $v) {
12778                    if (empty($v)) {
12779                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
12780                    }
12781
12782                    foreach ($dateLflArray[$k] as $item) {
12783                        $year = $item->year;
12784                        $now = date('m-d');
12785                        array_push($ytdArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
12786                    }
12787
12788                    $ytdArray = implode(' OR ', $ytdArray);
12789                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
12790                    $ytdArray = [];
12791                }
12792
12793                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
12794                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
12795            }
12796
12797            if (isset($data['lfl']) && $data['lfl'] != null && $data['lfl'] == true) {
12798                $isFy = false;
12799                $lflArray = [];
12800                $ytdAcceptanceArray = [];
12801                $lflCompanyIds = [];
12802                foreach ($dateLflArray as $k => $v) {
12803                    if (empty($v)) {
12804                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
12805                    }
12806
12807                    foreach ($dateLflArray[$k] as $item) {
12808                        $year = $item->year;
12809                        $min_date_like = $item->min_date_like;
12810                        $max_date_like = $item->max_date_like;
12811                        array_push($lflArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
12812                    }
12813
12814                    $lflArray = implode(' OR ', $lflArray);
12815                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
12816                    $lflArray = [];
12817                }
12818
12819                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
12820                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
12821            }
12822
12823            if ($isFy) {
12824                if ($companyId != 0) {
12825                    $where .= " AND q.company_id = {$companyId} ";
12826                } else {
12827                    $where .= " AND q.company_id IN ({$this->companyId})";
12828                }
12829            }
12830
12831            if (isset($data['source']) && $data['source'] != null) {
12832                $where .= " AND s.name = '{$data['source']}'";
12833            }
12834
12835            if (isset($data['source']) && $data['source'] != null) {
12836                $where .= " AND s.name = '{$data['source']}'";
12837            }
12838
12839            if (isset($data['commercial']) && $data['commercial'] != null) {
12840                $where .= " AND q.commercial = '{$data['commercial']}'";
12841            }
12842
12843            if (isset($data['created_by']) && $data['created_by'] != null) {
12844                $where .= " AND q.created_by = '{$data['created_by']}'";
12845            }
12846
12847            if (isset($data['budget_type']) && $data['budget_type'] != null) {
12848                $where .= " AND bt.budget_type_id = {$data['budget_type']}";
12849            }
12850
12851            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
12852                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
12853            }
12854
12855            if (isset($data['budget_status']) && $data['budget_status'] != null) {
12856                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
12857            }
12858
12859            if (isset($data['client_type']) && $data['client_type'] != null) {
12860                $where .= " AND ct.customer_type_id = {$data['client_type']}";
12861            }
12862
12863            if (isset($data['segment_id']) && $data['segment_id'] != null) {
12864                $where .= " AND q.segment_id = {$data['segment_id']}";
12865            }
12866
12867            $col = 'q.one';
12868
12869            if (isset($data['data_to_display']) && $data['data_to_display'] != null) {
12870                if ($data['data_to_display'] == 1) {
12871                    $col = 'q.one';
12872                }
12873
12874                if ($data['data_to_display'] == 2) {
12875                    $col = 'q.amount';
12876                }
12877            }
12878
12879            if ((isset($data['start_date']) && $data['start_date'] != null) && isset($data['end_date']) && $data['end_date'] != null) {
12880                $where .= " AND q.{$field} BETWEEN '{$data['start_date']}' AND '{$data['end_date']}' ";
12881            } elseif ((isset($data['start_date']) && $data['start_date'] == null || $data['start_date'] == '') && isset($data['end_date']) && $data['end_date'] != null) {
12882                $where .= " AND q.{$field} = '{$data['end_date']}' ";
12883            }
12884
12885            $whereQ = $where;
12886
12887            $sortBy = [
12888                0 => 'q.amount < 100',
12889                1 => 'q.amount BETWEEN 100 AND 500',
12890                2 => 'q.amount BETWEEN 500 AND 2000',
12891                3 => 'q.amount BETWEEN 2000 AND 10000',
12892                4 => 'q.amount BETWEEN 10000 AND 30000',
12893                5 => 'q.amount BETWEEN 30000 AND 100000',
12894                6 => 'q.amount BETWEEN 100000 AND 999999999999',
12895            ];
12896
12897            $query = "SELECT
12898                        q.commercial 'name',
12899                        COUNT(q.commercial) totalCommercial
12900                    FROM tbl_quotations q
12901                    LEFT JOIN tbl_sources s ON s.source_id = q.source_id
12902                    LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
12903                    LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
12904                    LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
12905                    WHERE
12906                        q.for_add = 0
12907                        AND q.{$field} IS NOT NULL
12908                        AND q.budget_type_id != 7
12909                        AND q.budget_type_id IS NOT NULL
12910                        {$whereQ}
12911                        {$whereYear}
12912                    GROUP BY q.commercial
12913                    HAVING COUNT(q.commercial) > 0
12914                    ORDER BY totalCommercial DESC";
12915
12916            $resultCommercials = DB::select($query);
12917
12918            if (isset($data['sort_by'])) {
12919                if ($data['sort_by'] != 7) {
12920                    $s = $sortBy[$data['sort_by']];
12921                    $whereQ .= " AND {$s} ";
12922                }
12923            }
12924
12925            $num = 'COUNT(1)';
12926
12927            if (@$data['data_to_display'] == 2) {
12928                $num = 'SUM(q.amount)';
12929            }
12930
12931            if (@$data['data_to_display'] == 3) {
12932                $num = 'SUM(q.amount) / COUNT(1)';
12933            }
12934
12935            if (@$data['data_to_display'] == 4) {
12936                $num = '(SUM(CASE WHEN q.acceptance_date IS NOT NULL THEN 1 ELSE 0 END) / COUNT(q.created_at) * 100)';
12937            }
12938
12939            $query = "SELECT
12940                    q.commercial 'name',
12941                    COUNT(q.commercial) totalCommercial,
12942                    {$num} num
12943                FROM tbl_quotations q
12944                LEFT JOIN tbl_sources s ON s.source_id = q.source_id
12945                LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
12946                LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
12947                LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
12948                WHERE
12949                    q.for_add = 0
12950                    AND q.{$field} IS NOT NULL
12951                    AND q.budget_type_id != 7
12952                    AND q.budget_type_id IS NOT NULL
12953                    {$whereQ}
12954                    {$whereYear}
12955                GROUP BY q.commercial
12956                HAVING COUNT(q.commercial) > 0
12957                ORDER BY num DESC";
12958
12959            $resultCommercialsOrder = DB::select($query);
12960
12961            foreach ($resultCommercialsOrder as $item) {
12962                $namesToRemove[$item->name] = true;
12963            }
12964
12965            $resultArray = [];
12966            foreach ($resultCommercials as $item) {
12967                if (! isset($namesToRemove[$item->name])) {
12968                    $resultArray[] = $item;
12969                }
12970            }
12971
12972            $resultCommercials = array_merge($resultCommercialsOrder, $resultArray);
12973
12974            $cols = '';
12975
12976            $colsGroupConcatIds = '';
12977
12978            foreach ($resultCommercials as $item) {
12979                $cols .= ",COALESCE(
12980                    SUM(
12981                        CASE WHEN q.commercial = '{$item->name}' THEN {$col} ELSE 0 END
12982                    ), 0
12983                ) '{$item->name}'";
12984
12985                $colsGroupConcatIds .= ",GROUP_CONCAT(CASE WHEN q.commercial = '{$item->name}' THEN q.id END) 'groupConcatIds-{$item->name}'";
12986            }
12987
12988            $cols .= ",COALESCE(
12989                SUM(
12990                    CASE WHEN q.commercial IS NOT NULL THEN {$col} ELSE 0 END
12991                ), 0
12992            ) total";
12993
12994            $range = "CASE
12995                        WHEN amount < 100 THEN '< 100€'
12996                        WHEN amount BETWEEN 100 AND 500 THEN '100€ - 500€'
12997                        WHEN amount BETWEEN 500 AND 2000 THEN '500€ - 2k€'
12998                        WHEN amount BETWEEN 2000 AND 10000 THEN '2k€ - 10k€'
12999                        WHEN amount BETWEEN 10000 AND 30000 THEN '10k€ - 30k€'
13000                        WHEN amount BETWEEN 30000 AND 100000 THEN '30k€ - 100k€'
13001                        WHEN amount BETWEEN 100000 AND 999999999999 THEN '> 100k€'
13002                    END AS amount_range";
13003
13004            if (@$data['data_to_display'] == 3) {
13005
13006                $range = "CASE
13007                            WHEN SUM(amount) / COUNT(1) < 100 THEN '< 100€'
13008                            WHEN SUM(amount) / COUNT(1) BETWEEN 100 AND 500 THEN '100€ - 500€'
13009                            WHEN SUM(amount) / COUNT(1) BETWEEN 500 AND 2000 THEN '500€ - 2k€'
13010                            WHEN SUM(amount) / COUNT(1) BETWEEN 2000 AND 10000 THEN '2k€ - 10k€'
13011                            WHEN SUM(amount) / COUNT(1) BETWEEN 10000 AND 30000 THEN '10k€ - 30k€'
13012                            WHEN SUM(amount) / COUNT(1) BETWEEN 30000 AND 100000 THEN '30k€ - 100k€'
13013                            WHEN SUM(amount) / COUNT(1) BETWEEN 100000 AND 999999999999 THEN '> 100k€'
13014                        END AS amount_range";
13015
13016                $cols = '';
13017
13018                foreach ($resultCommercials as $item) {
13019                    $cols .= ",COALESCE(
13020                        (
13021                            SUM(CASE WHEN q.commercial = '{$item->name}' THEN q.amount END)
13022                        ) /
13023                        (
13024                            SUM(CASE WHEN q.commercial = '{$item->name}' THEN q.one END)
13025                        )
13026                    , 0) '{$item->name}'";
13027                }
13028
13029                $cols .= ',COALESCE(
13030                    (
13031                        SUM(CASE WHEN q.commercial IS NOT NULL THEN q.amount END)
13032                    ) /
13033                    (
13034                        SUM(CASE WHEN q.commercial IS NOT NULL THEN q.one END)
13035                    )
13036                , 0) total';
13037            }
13038
13039            if (@$data['data_to_display'] == 4) {
13040
13041                $cols = '';
13042
13043                foreach ($resultCommercials as $item) {
13044                    $cols .= ",COALESCE(
13045                        (
13046                            SUM(CASE WHEN q.commercial = '{$item->name}' THEN q.acceptanceDate END)
13047                        ) /
13048                        (
13049                            SUM(CASE WHEN q.commercial = '{$item->name}' THEN q.createdAt END)
13050                        ) * 100
13051                    , 0) '{$item->name}'";
13052                }
13053
13054                $cols .= ',COALESCE(
13055                    (
13056                        SUM(CASE WHEN q.commercial IS NOT NULL THEN q.acceptanceDate END)
13057                    ) /
13058                    (
13059                        SUM(CASE WHEN q.commercial IS NOT NULL THEN q.createdAt END)
13060                    ) * 100
13061                , 0) total';
13062            }
13063
13064            $query = "WITH amount_ranges AS (
13065                            SELECT '< 100€' AS amount_range
13066                            UNION ALL SELECT '100€ - 500€'
13067                            UNION ALL SELECT '500€ - 2k€'
13068                            UNION ALL SELECT '2k€ - 10k€'
13069                            UNION ALL SELECT '10k€ - 30k€'
13070                            UNION ALL SELECT '30k€ - 100k€'
13071                            UNION ALL SELECT '> 100k€'
13072                        )
13073
13074                        SELECT
13075                            ar.amount_range,
13076                             GROUP_CONCAT(
13077                                q.id
13078                            ) AS groupConcatIds
13079                            {$colsGroupConcatIds}
13080                            {$cols}
13081                        FROM
13082                            amount_ranges ar
13083                        LEFT JOIN (
13084                            SELECT
13085                                commercial,
13086                                GROUP_CONCAT(
13087                                    CASE WHEN q.{$field} IS NOT NULL THEN id END
13088                                ) id,
13089                                amount AS amount,
13090                                COUNT(CASE WHEN q.created_at IS NOT NULL THEN 1 END) createdAt,
13091                                COUNT(CASE WHEN q.acceptance_date IS NOT NULL THEN 1 END) acceptanceDate,
13092                                COUNT(1) AS one,
13093                                {$range}
13094                            FROM
13095                                tbl_quotations q
13096                                LEFT JOIN tbl_sources s ON s.source_id = q.source_id
13097                                LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
13098                                LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
13099                                LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
13100                            WHERE
13101                                q.{$field} IS NOT NULL
13102                                AND q.for_add = 0
13103                                AND q.budget_type_id != 7
13104                                AND q.budget_type_id IS NOT NULL
13105                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
13106                                {$where}
13107                                {$whereYear}
13108                            GROUP BY
13109                                commercial,
13110                                id
13111                        ) AS q ON ar.amount_range = q.amount_range
13112                        GROUP BY
13113                            ar.amount_range WITH ROLLUP
13114                        ORDER BY
13115                            CASE
13116                                WHEN ar.amount_range = '< 100€' THEN 1
13117                                WHEN ar.amount_range = '100€ - 500€' THEN 2
13118                                WHEN ar.amount_range = '500€ - 2k€' THEN 3
13119                                WHEN ar.amount_range = '2k€ - 10k€' THEN 4
13120                                WHEN ar.amount_range = '10k€ - 30k€' THEN 5
13121                                WHEN ar.amount_range = '30k€ - 100k€' THEN 6
13122                                ELSE 7
13123                            END";
13124
13125            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
13126            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
13127
13128            return response([
13129                'message' => 'OK',
13130                'data' => $result,
13131                'commercials' => $resultCommercials,
13132            ]);
13133
13134        } catch (\Exception $e) {
13135            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_COMMERCIAL_EXCEPTION'));
13136
13137            return response(['message' => 'KO', 'error' => $e->getMessage()]);
13138        }
13139
13140    }
13141
13142    public function send_email_template_preview($emailTemplateId): ResponseFactory|HttpResponse
13143    {
13144
13145        try {
13146
13147            $emailTemplateId = addslashes((string) $emailTemplateId);
13148
13149            $emailTemplate = TblEmailConfiguration::where('id', $emailTemplateId)->first();
13150
13151            $user = TblUsers::where('id', $this->userId)->first();
13152            $error = false;
13153
13154            $toEmail = $user->email;
13155
13156            $availableParameters = [
13157                'quote_id',
13158                'company_id',
13159                'client',
13160                'client_type',
13161                'phone_number',
13162                'email',
13163                'issue_date',
13164                'request_date',
13165                'duration',
13166                'invoice_number',
13167                'type',
13168                'acceptance_date',
13169                'status',
13170                'source',
13171                'amount',
13172                'reason_for_not_following_up',
13173                'last_follow_up_date',
13174                'last_follow_up_comment',
13175                'reason_for_rejection_id',
13176                'reason_for_rejection',
13177                'commercial',
13178                'created_at',
13179                'created_by',
13180                'updated_at',
13181                'updated_by',
13182            ];
13183
13184            $dateParameters = [
13185                'issue_date',
13186                'request_date',
13187                'acceptance_date',
13188                'last_follow_up_date',
13189                'created_at',
13190                'updated_at',
13191            ];
13192
13193            if ($this->locale == 'es') {
13194                setlocale(LC_ALL, 'es_ES', 'Spanish_Spain', 'Spanish');
13195                setlocale(LC_ALL, 'es_ES', 'Spanish_Spain', 'Spanish');
13196            }
13197
13198            $body = $emailTemplate->html;
13199            $subject = $emailTemplate->subject;
13200
13201            preg_match_all('/{{(.*?)}}/', (string) $body, $matches);
13202
13203            $parameters = $matches[1];
13204
13205            $result = TblQuotations::where('for_add', 0)->whereIn('company_id', $this->companyIds)->first();
13206
13207            foreach ($parameters as $parameter) {
13208
13209                if (in_array($parameter, $dateParameters)) {
13210                    if ($result->{$parameter}) {
13211                        $result->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result->{$parameter})));
13212                    }
13213                }
13214
13215                if (in_array($parameter, $availableParameters)) {
13216                    $body = str_replace('{{'.$parameter.'}}', $result->{$parameter}, $body);
13217                }
13218            }
13219
13220            preg_match_all('/{{(.*?)}}/', (string) $subject, $matches);
13221
13222            $parameters = $matches[1];
13223
13224            foreach ($parameters as $parameter) {
13225
13226                if (in_array($parameter, $dateParameters)) {
13227                    if ($result->{$parameter}) {
13228                        $result->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result->{$parameter})));
13229                    }
13230                }
13231
13232                if (in_array($parameter, $availableParameters)) {
13233                    $subject = str_replace('{{'.$parameter.'}}', $result->{$parameter}, $subject);
13234                }
13235            }
13236
13237            $email = new Mail;
13238
13239            $templateFiles = TblEmailFiles::where('email_template_id', $emailTemplateId)->orderBy('order', 'asc')->get();
13240
13241            foreach ($templateFiles as $item) {
13242                $f = storage_path('app/public/uploads/'.$item->filename);
13243                $imgpath = file_get_contents($f);
13244                $mimeType = mime_content_type($f);
13245
13246                $email->addAttachment(
13247                    $imgpath,
13248                    $mimeType,
13249                    str_replace(' ', '', $item->original_name),
13250                    'inline',
13251                    str_replace(' ', '', $item->original_name),
13252                );
13253
13254                // An image the template already places itself (src="cid:<name>") is not
13255                // repeated in the logo strip under the body.
13256                if (! str_contains($body, 'cid:'.$item->original_name)) {
13257                    $body .= "<img src='cid:{$item->original_name}' style='height: 45px; padding-right: 6px' />";
13258                }
13259            }
13260
13261            $html = '<!DOCTYPE html>';
13262            $html .= '<html>';
13263            $html .= '<head>';
13264            $html .= '<meta charset="UTF-8">';
13265            $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
13266            $html .= '</head>';
13267            $html .= '<body>';
13268            $html .= $body;
13269            $html .= '</body>';
13270            $html .= '</html>';
13271
13272            if ($toEmail != null) {
13273
13274                $companyEmail = null;
13275
13276                if ($emailTemplate->from_id != null) {
13277                    $companyEmail = TblCompanyEmails::where('id', $emailTemplate->from_id)->first();
13278                } else {
13279                    $companyEmail = TblCompanyEmails::where('is_active', 1)->where('verified', 1)->where('company_id', $result->company_id)->first();
13280                }
13281
13282                if (! $companyEmail) {
13283                    return response(['message' => 'KO', 'error' => __('language.no_active_verified_sender')]);
13284                }
13285
13286                $email->setFrom($companyEmail->from_email, $companyEmail->from_name);
13287                $email->setSubject($subject);
13288                $email->addTo($toEmail);
13289                $email->addContent('text/html', $html);
13290
13291                $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
13292
13293                try {
13294                    $response = $sendgrid->send($email);
13295                    SendgridLogger::log($email, $response);
13296                } catch (\Throwable $sendException) {
13297                    SendgridLogger::logException($email, $sendException);
13298                    throw $sendException;
13299                }
13300
13301                if ($response->statusCode() == 202) {
13302                    return response(['message' => 'OK']);
13303                }
13304            }
13305
13306            return response(['message' => 'KO']);
13307
13308        } catch (\Exception $e) {
13309            report(AppException::fromException($e, 'SEND_EMAIL_TEMPLATE_EXCEPTION'));
13310
13311            return response(['message' => 'KO', 'error' => $e->getMessage()]);
13312        }
13313
13314    }
13315
13316    public function list_quotation_analytics_by_types_of_budgets_company_per_week(Request $request): ResponseFactory|HttpResponse
13317    {
13318
13319        try {
13320
13321            $data = $request->all();
13322            $companyId = addslashes((string) $data['company_id']);
13323            $field = $data['field'];
13324
13325            $where = '';
13326            $whereYear = '';
13327            $dateLflArray = [];
13328            $companyIds = $this->companyIds;
13329
13330            $acc = '';
13331            if ($field == 'acceptance_date') {
13332                $acc = ' AND q.acceptance_date IS NOT NULL ';
13333                // $field = 'created_at';
13334
13335                if (@$data['data_to_display'] == 4) {
13336                    $field = 'created_at';
13337                    $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
13338                }
13339            } else {
13340                $field = 'created_at';
13341                $where .= ' AND YEAR(q.created_at) = YEAR(q.issue_date)';
13342            }
13343
13344            if ($companyId != 0) {
13345                $companyIds = [$companyId];
13346            }
13347
13348            if (isset($data['years']) && $data['years'] != null) {
13349
13350                if (count($data['years']) > 0) {
13351                    foreach ($data['years'] as $year) {
13352                        if (isset($data['week']) && $data['week'] != null) {
13353                            $w = sprintf('%02d', $data['week']);
13354                            $whereYear .= " AND YEARWEEK(q.{$field}, 1) = '{$year}{$w}'";
13355                        } else {
13356                            $whereYear .= " AND YEAR(q.{$field}) = {$year}";
13357                        }
13358                    }
13359                }
13360            }
13361
13362            foreach ($companyIds as $v) {
13363
13364                $lflWhere = " AND q.company_id = {$v} ";
13365
13366                $query = "SELECT
13367                            CONCAT(
13368                                DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field}),
13369                                ' - ',
13370                                DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$field})
13371                            ) AS date_like,
13372                            YEAR(q.{$field}) 'year',
13373                            DATE_FORMAT((SELECT MIN(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
13374                            DATE_FORMAT((SELECT MAX(q.{$field}) FROM tbl_quotations q WHERE q.{$field} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
13375                            {$v} 'company_id'
13376                        FROM
13377                            tbl_quotations q
13378                        WHERE
13379                            q.{$field} IS NOT NULL
13380                            AND q.for_add = 0
13381                            {$lflWhere}
13382                            {$whereYear}
13383                        GROUP BY YEAR(q.{$field})
13384                        ORDER BY YEAR(q.{$field}) DESC";
13385
13386                $dateLike = DB::select($query);
13387
13388                $dateLflArray[$v] = $dateLike;
13389            }
13390
13391            $isFy = true;
13392
13393            if (isset($data['ytd']) && $data['ytd'] != null && $data['ytd'] == true) {
13394                $isFy = false;
13395                $ytdArray = [];
13396                $ytdAcceptanceArray = [];
13397                $lflCompanyIds = [];
13398                foreach ($dateLflArray as $k => $v) {
13399                    if (empty($v)) {
13400                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
13401                    }
13402
13403                    foreach ($dateLflArray[$k] as $item) {
13404                        $year = $item->year;
13405                        $now = date('m-d');
13406                        array_push($ytdArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN '{$year}-01-01' AND '{$year}-{$now}'");
13407                    }
13408
13409                    $ytdArray = implode(' OR ', $ytdArray);
13410                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$ytdArray})");
13411                    $ytdArray = [];
13412                }
13413
13414                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
13415                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
13416            }
13417
13418            if (isset($data['lfl']) && $data['lfl'] != null && $data['lfl'] == true) {
13419                $isFy = false;
13420                $lflArray = [];
13421                $ytdAcceptanceArray = [];
13422                $lflCompanyIds = [];
13423                foreach ($dateLflArray as $k => $v) {
13424                    if (empty($v)) {
13425                        continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
13426                    }
13427
13428                    foreach ($dateLflArray[$k] as $item) {
13429                        $year = $item->year;
13430                        $min_date_like = $item->min_date_like;
13431                        $max_date_like = $item->max_date_like;
13432                        array_push($lflArray, "DATE_FORMAT(q.{$field}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
13433                    }
13434
13435                    $lflArray = implode(' OR ', $lflArray);
13436                    array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
13437                    $lflArray = [];
13438                }
13439
13440                $lflCompanyIds = implode(' OR ', $lflCompanyIds);
13441                $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
13442            }
13443
13444            if ($isFy) {
13445                if ($companyId != 0) {
13446                    $where .= " AND q.company_id = {$companyId} ";
13447                } else {
13448                    $where .= " AND q.company_id IN ({$this->companyId})";
13449                }
13450            }
13451
13452            if (isset($data['source']) && $data['source'] != null) {
13453                $where .= " AND s.name = '{$data['source']}'";
13454            }
13455
13456            if (isset($data['month']) && $data['month'] != null) {
13457                $where .= " AND MONTH(q.{$field}) = '{$data['month']}'";
13458            }
13459
13460            if (isset($data['commercial']) && $data['commercial'] != null) {
13461                $where .= " AND q.commercial = '{$data['commercial']}'";
13462            }
13463
13464            if (isset($data['created_by']) && $data['created_by'] != null) {
13465                $where .= " AND q.created_by = '{$data['created_by']}'";
13466            }
13467
13468            if (isset($data['budget_type']) && $data['budget_type'] != null) {
13469                $where .= " AND bt.budget_type_id = {$data['budget_type']}";
13470            }
13471
13472            if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
13473                $where .= " AND bt.budget_type_group_id = {$data['budget_type_group']}";
13474            }
13475
13476            if (isset($data['budget_status']) && $data['budget_status'] != null) {
13477                $where .= " AND bs.budget_status_id = {$data['budget_status']}";
13478            }
13479
13480            if (isset($data['client_type']) && $data['client_type'] != null) {
13481                $where .= " AND ct.customer_type_id = {$data['client_type']}";
13482            }
13483
13484            if (isset($data['segment_id']) && $data['segment_id'] != null) {
13485                $where .= " AND q.segment_id = {$data['segment_id']}";
13486            }
13487
13488            $col = '1';
13489
13490            if (isset($data['data_to_display']) && $data['data_to_display'] != null) {
13491                if ($data['data_to_display'] == 1) {
13492                    $col = '1';
13493                }
13494
13495                if ($data['data_to_display'] == 2) {
13496                    $col = 'q.amount';
13497                }
13498            }
13499
13500            $budgetTypes = TblBudgetTypes::orderByRaw('ISNULL(priority), priority ASC')->get();
13501            $cols = '';
13502            foreach ($budgetTypes as $item) {
13503                if ($item->name == '' || $item->name == null) {
13504                    $cols .= ",COALESCE(SUM(CASE WHEN bt.name IS NULL {$acc} THEN {$col} ELSE 0 END), 0) AS 'Otros'";
13505                } else {
13506                    $cols .= ",COALESCE(SUM(CASE WHEN bt.name = '{$item->name}' {$acc} THEN {$col} ELSE 0 END), 0) AS '{$item->name}'";
13507                }
13508            }
13509
13510            $budgetTypeGroups = TblBudgetTypeGroups::orderByRaw('ISNULL(priority), priority ASC')->get();
13511
13512            $colsGroups = ",COALESCE(SUM(CASE WHEN bt.name IS NULL {$acc} THEN {$col} END), 0) AS Otros";
13513
13514            foreach ($budgetTypeGroups as $item) {
13515                $budgetTypeGroupName = str_replace(' ', '', $item->name).$item->budget_type_group_id;
13516                $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
13517                $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN {$col} END), 0) AS '{$budgetTypeGroupName}'";
13518            }
13519
13520            $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN {$col} END), 0) AS total";
13521
13522            $col = $colsGroups.$cols;
13523
13524            if (@$data['data_to_display'] == 3) {
13525
13526                $cols = '';
13527                foreach ($budgetTypes as $item) {
13528                    if ($item->name == '' || $item->name == null) {
13529                        $cols .= ",COALESCE(
13530                                        SUM(CASE WHEN bt.name IS NULL {$acc} THEN q.amount ELSE 0 END) /
13531                                        SUM(CASE WHEN bt.name IS NULL {$acc} THEN 1 ELSE 0 END) * 100
13532                                    , 0) AS 'Otros'";
13533                    } else {
13534                        $cols .= ", COALESCE(
13535                                        SUM(CASE WHEN bt.name = '{$item->name}' {$acc} THEN q.amount ELSE 0 END) /
13536                                        SUM(CASE WHEN bt.name = '{$item->name}' {$acc} THEN 1 ELSE 0 END)
13537                                    , 0) AS '{$item->name}'";
13538                    }
13539                }
13540
13541                $colsGroups = ",COALESCE(
13542                                (SUM(CASE WHEN bt.name IS NULL {$acc} THEN q.amount END)) /
13543                                (SUM(CASE WHEN bt.name IS NULL {$acc} THEN 1 END))
13544                            , 0) Otros";
13545
13546                foreach ($budgetTypeGroups as $item) {
13547                    $budgetTypeGroupName = str_replace(' ', '', $item->name).$item->budget_type_group_id;
13548                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
13549                    $colsGroups .= ",COALESCE(
13550                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.amount END)) /
13551                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN 1 END))
13552                                    , 0) '{$budgetTypeGroupName}'";
13553                }
13554
13555                $colsGroups .= ",COALESCE(
13556                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN q.amount END)) /
13557                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN 1 END))
13558                                , 0) total";
13559
13560                $col = $colsGroups.$cols;
13561            }
13562
13563            if (@$data['data_to_display'] == 4) {
13564
13565                $cols = '';
13566
13567                foreach ($budgetTypes as $item) {
13568
13569                    if ($item->name == '' || $item->name == null) {
13570                        $cols .= ",COALESCE(
13571                                        SUM(CASE WHEN bt.name IS NULL AND q.acceptance_date IS NOT NULL THEN 1 ELSE 0 END) /
13572                                        SUM(CASE WHEN bt.name IS NULL AND q.created_at IS NOT NULL THEN 1 ELSE 0 END) * 100
13573                                    , 0) AS 'Otros'";
13574                    } else {
13575                        $cols .= ", COALESCE(
13576                                        SUM(CASE WHEN bt.name = '{$item->name}' AND q.acceptance_date IS NOT NULL THEN 1 END) /
13577                                        SUM(CASE WHEN bt.name = '{$item->name}' AND q.created_at IS NOT NULL THEN 1 END) * 100
13578                                    , 0) AS '{$item->name}'";
13579                    }
13580                }
13581
13582                $colsGroups = ',COALESCE(
13583                                    (SUM(CASE WHEN bt.name IS NULL AND q.acceptance_date IS NOT NULL THEN 1 END)) /
13584                                    (SUM(CASE WHEN bt.name IS NULL AND q.created_at IS NOT NULL THEN 1 END)) * 100
13585                                , 0) Otros';
13586
13587                foreach ($budgetTypeGroups as $item) {
13588                    $budgetTypeGroupName = str_replace(' ', '', $item->name).$item->budget_type_group_id;
13589                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) {$acc} THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
13590                    $colsGroups .= ",COALESCE(
13591                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) AND q.acceptance_date IS NOT NULL THEN 1 END)) /
13592                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) AND q.created_at IS NOT NULL THEN 1 END)) * 100
13593                                    , 0) '{$budgetTypeGroupName}'";
13594                }
13595
13596                $colsGroups .= ',COALESCE(
13597                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) AND q.acceptance_date IS NOT NULL THEN 1 END)) /
13598                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) AND q.created_at IS NOT NULL THEN 1 END)) * 100
13599                                    , 0) total';
13600
13601                $col = $colsGroups.$cols;
13602            }
13603
13604            $query = "SELECT
13605                            YEAR(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)) AS 'year',
13606                            LPAD(MONTH(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)), 2, 0) AS 'month',
13607                            q.company_id,
13608                            c.name 'companyName',
13609                            GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) {$acc} THEN q.id END) groupConcatIds
13610                            {$col}
13611                        FROM
13612                            tbl_quotations q
13613                            LEFT JOIN tbl_sources s ON s.source_id = q.source_id
13614                            LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
13615                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
13616                            LEFT JOIN tbl_budget_type_groups btg ON bt.budget_type_group_id = btg.budget_type_group_id
13617                            LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
13618                            LEFT JOIN tbl_companies c ON q.company_id = c.company_id
13619                        WHERE
13620                            q.{$field} IS NOT NULL
13621                            AND q.for_add = 0
13622                            AND q.budget_type_id != 7
13623                            AND q.budget_type_id IS NOT NULL
13624                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
13625                            {$where}
13626                            {$whereYear}
13627                        GROUP BY
13628                            YEAR(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)),
13629                            MONTH(DATE_ADD(q.{$field}, INTERVAL - WEEKDAY(q.{$field}) DAY)),
13630                            q.company_id WITH ROLLUP
13631                        ORDER BY
13632                            YEAR DESC,
13633                            MONTH ASC,
13634                            q.company_id ASC,
13635                            DATE_FORMAT(q.{$field}, '%e') ASC";
13636
13637            $result = DB::select($query);
13638
13639            $query = "SELECT
13640                        btg.budget_type_group_id,
13641                        btg.name,
13642                        (
13643                            SELECT
13644                                GROUP_CONCAT(COALESCE(bt.name, '') ORDER BY ISNULL(bt.priority), bt.priority ASC SEPARATOR '|')
13645                            FROM
13646                                tbl_budget_types bt
13647                            WHERE
13648                                bt.budget_type_group_id = btg.budget_type_group_id
13649                        ) budget_types
13650                        FROM
13651                            tbl_budget_type_groups btg
13652                        ORDER BY
13653                            ISNULL(btg.priority),
13654                            btg.priority ASC";
13655
13656            $budgetTypeGroups = DB::select($query);
13657
13658            foreach ($budgetTypeGroups as $item) {
13659                $item->group_key_name = str_replace(' ', '', $item->name).$item->budget_type_group_id;
13660                $item->budget_types = explode('|', (string) $item->budget_types);
13661            }
13662
13663            return response([
13664                'message' => 'OK',
13665                'data' => $result,
13666                'budgetTypeGroups' => $budgetTypeGroups,
13667            ]);
13668
13669        } catch (\Exception $e) {
13670            report(AppException::fromException($e, 'LIST_QUOTATION_ANALYTICS_BY_TYPES_OF_BUDGETS_COMPANT_PER_WEEK_EXCEPTION'));
13671
13672            return response(['message' => 'KO', 'error' => $e->getMessage()]);
13673        }
13674    }
13675
13676    public function request_permission_commercial(Request $request): ResponseFactory|HttpResponse
13677    {
13678
13679        try {
13680
13681            $data = $request->all();
13682
13683            $id = addslashes((string) $data['id']);
13684            $requestedBy = $data['requested_by'];
13685            $body = '';
13686
13687            $result = TblQuotations::where('id', $id)->first();
13688
13689            $subject = __('language.request_permission_commercial.subject');
13690            $subject = str_replace('{{quote_id}}', $result->quote_id, $subject);
13691            $subject = str_replace('{{username}}', $requestedBy, $subject);
13692
13693            $email = new Mail;
13694
13695            $imgpath = file_get_contents(public_path('fireservicetitan.png'));
13696
13697            $email->addAttachment(
13698                $imgpath,
13699                'image/png',
13700                'fireservicetitan.png',
13701                'inline',
13702                'fireservicetitan'
13703            );
13704
13705            $url = config('app.frontend_url')."orders/{$id}?company_id={$result->company_id}";
13706            $href = "<a href='{$url}'>{$result->quote_id}</a>";
13707
13708            $user = TblUsers::where('name', $requestedBy)->first();
13709
13710            $urlClick = config('app.frontend_url')."update?confirm_request={$id}&requested_by={$user->id}&quote_id={$result->quote_id}";
13711            $company = TblCompanies::where('company_id', $result->company_id)->first();
13712
13713            $body .= __('language.request_permission_commercial.body_hello');
13714            $body .= __('language.request_permission_commercial.body_message');
13715
13716            $amount = $this->currency($result->amount, 1);
13717
13718            $body = str_replace('{{commercial}}', $result->commercial, $body);
13719            $body = str_replace('{{company}}', $company->name, $body);
13720            $body = str_replace('{{client}}', $result->client, $body);
13721            $body = str_replace('{{amount}}', $amount, $body);
13722            $body = str_replace('{{quote_id}}', $href, $body);
13723            $body = str_replace('{{click}}', $urlClick, $body);
13724            $body = str_replace('{{username}}', $requestedBy, $body);
13725
13726            $body .= '<p>Fire Service Titan</p>';
13727            $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
13728
13729            $html = '<!DOCTYPE html>';
13730            $html .= '<html>';
13731            $html .= '<head>';
13732            $html .= '<meta charset="UTF-8">';
13733            $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
13734            $html .= '</head>';
13735            $html .= '<body>';
13736            $html .= $body;
13737            $html .= '</body>';
13738            $html .= '</html>';
13739
13740            $user = TblUsers::where('id', $this->userId)->first();
13741
13742            if (config('services.sendgrid.staging')) {
13743                $email->addTo($user->email);
13744            } else {
13745                $email->addTo('luis.collar@fire.es');
13746
13747                $user = TblUsers::where('name', $result->created_by)->first();
13748                if ($user && $user->email != 'luis.collar@fire.es') {
13749                    $email->addTo($user->email);
13750                }
13751
13752                if ($result->created_by != $result->commercial) {
13753                    $user = TblUsers::where('name', $result->commercial)->first();
13754                    if ($user->email != 'luis.collar@fire.es') {
13755                        $email->addTo($user->email);
13756                    }
13757                }
13758            }
13759
13760            $email->setFrom('titan@fire.es');
13761            $email->setSubject($subject);
13762
13763            $email->addContent('text/html', $html);
13764
13765            // FIRE-1930: internal email, follows the commercial kill switch.
13766            $response = SendgridDispatcher::send(
13767                $email,
13768                SendgridDispatcher::BUCKET_COMMERCIAL,
13769                (int) $result->company_id,
13770                'Quotations::request_permission_commercial',
13771            );
13772
13773            if ($response === null) {
13774                return response(['message' => 'KO', 'error' => __('language.email_sending_disabled')]);
13775            }
13776
13777            if ($response->statusCode() == 202) {
13778                return response(['message' => 'OK']);
13779            }
13780
13781            $this->addUpdateLog($id, $requestedBy, 'request_permission_commercial', null, null, 4);
13782
13783            return response(['message' => 'KO']);
13784
13785        } catch (\Exception $e) {
13786            report(AppException::fromException($e, 'REQUEST_PERMISSION_EXCEPTION'));
13787
13788            return response(['message' => 'KO', 'error' => $e->getMessage()]);
13789        }
13790
13791    }
13792
13793    public function confirm_update_commercial(Request $request): ResponseFactory|HttpResponse
13794    {
13795
13796        try {
13797            sleep(3);
13798            $data = $request->all();
13799            $id = addslashes((string) $data['id']);
13800            $userId = addslashes((string) $data['requested_by']);
13801
13802            $user = TblUsers::where('id', $userId)->first();
13803
13804            if ($user) {
13805
13806                TblQuotations::where('id', $data['id'])->update(
13807                    [
13808                        'commercial' => $user->name,
13809                        'updated_at' => date('Y-m-d H:i:s'),
13810                    ]
13811                );
13812
13813            } else {
13814                return response(['message' => 'KO', 'error' => 'invalid_user']);
13815            }
13816
13817            return response(['message' => 'OK']);
13818
13819        } catch (\Exception $e) {
13820            report(AppException::fromException($e, 'CONFIRM_UPDATE_COMMERCIAL_EXCEPTION'));
13821
13822            return response(['message' => 'KO', 'error' => $e->getMessage()]);
13823        }
13824    }
13825
13826    public function calculateEmailRequestSize(Mail $email): int
13827    {
13828
13829        $size = 0;
13830
13831        // Add size of 'from', 'to', 'subject', 'content'
13832        $from = $email->getFrom();
13833        $size += strlen(json_encode([
13834            'from' => $from->getEmail().' '.$from->getName(),
13835            'subject' => $email->getSubject(),
13836        ]));
13837
13838        // Add size of 'to' (recipients)
13839        $personalizations = $email->getPersonalizations() ?? [];
13840        foreach ($personalizations as $personalization) {
13841            foreach ($personalization->getTos() as $to) {
13842                $size += strlen($to->getEmail().' '.$to->getName());
13843            }
13844        }
13845
13846        // Add size of content
13847        foreach ($email->getContents() as $content) {
13848            $size += strlen((string) $content->getValue());
13849        }
13850
13851        // Add size of attachments (if any)
13852
13853        if ($email->getAttachments() != null && $email->getAttachments() != '') {
13854            foreach ($email->getAttachments() as $attachment) {
13855                $size += strlen($attachment->getContent()); // Base64 encoded size
13856                $size += strlen($attachment->getFilename());
13857                $size += strlen($attachment->getType());
13858            }
13859        }
13860
13861        $sizeInMegabytes = $size / 1048576; // 1 MB = 1,048,576 bytes
13862
13863        return (int) ceil($sizeInMegabytes);
13864    }
13865
13866    public function list_quotation_analytics_commercial_productivity(Request $request): ResponseFactory|HttpResponse
13867    {
13868
13869        // try {
13870
13871        $data = $request->all();
13872        $companyId = addslashes((string) $data['company_id']);
13873
13874        // "Replace quotation" (sustitutos): a superseded quote must not be
13875        // counted here. Seeded at initialisation so it reaches the three
13876        // quotation subqueries - $whereAcceptanceDate and $whereCreatedAt are
13877        // copied from $where further down.
13878        //
13879        // NOT $whereVisit: that subquery selects FROM tbl_pipelines, which has
13880        // no budget_status_id column, so the filter is a hard 1054 error there
13881        // (it broke the whole endpoint). It would be meaningless even if the
13882        // column existed - pipeline rows are visits and calls, so matching
13883        // their id against replaced_quotes.old_quotation_id compares a pipeline
13884        // id to a quotation id. There is nothing to exclude on that branch.
13885        $excludeReplaced = $this->excludeReplacedQuotesSql();
13886
13887        $where = $excludeReplaced;
13888        $whereYear = '';
13889        $whereYearIssueDate = '';
13890        $whereVisit = '';
13891        // Year filter for the visit/call subquery. $whereYear is expressed on
13892        // q.sent_date, which does not exist on tbl_pipelines, so the Embudo
13893        // branch needs its own copy keyed on visit_date.
13894        $whereYearVisit = '';
13895
13896        $dateLflArray = [];
13897        $companyIds = $this->companyIds;
13898
13899        if ($companyId != 0) {
13900            $companyIds = [$companyId];
13901        }
13902
13903        // Emitidos KPI counts a quotation once, in the period of its LAST send
13904        // (tbl_quotations.sent_date), not by the ERP issue_date.
13905        $field = 'sent_date';
13906        $fq = 'COALESCE(q.sent_date, q.issue_date)';
13907        $fb = 'COALESCE(sent_date, issue_date)';
13908
13909        // "Vista por semana" (default) vs "Vista por mes".
13910        //
13911        // Historically every row's year/month came from the MONDAY of its week
13912        // (DATE_ADD(date, INTERVAL -WEEKDAY(date) DAY)), so a week straddling a
13913        // month boundary landed whole under the month its Monday belongs to —
13914        // e.g. the 29 Jun–5 Jul week counted its five July days under June, and
13915        // July never saw them. That is the week view: weeks are never cut, and
13916        // each one sits under the month it started in.
13917        //
13918        // With calendar_month = 1 the year/month come from the row's OWN date
13919        // instead, so every day counts in the calendar month it actually falls
13920        // in. The straddling week then appears under BOTH months — once with
13921        // its June days, once with its July days — and each month subtotal only
13922        // ever covers its own days. The week number stays ISO (WEEK(d, 3)), so
13923        // the same week keeps the same label in both places.
13924        $calendarMonth = isset($data['calendar_month'])
13925            && ($data['calendar_month'] === true || $data['calendar_month'] == 1);
13926
13927        // Per-date-field period expressions, built once and interpolated into
13928        // each of the four UNIONed subqueries below (issue / acceptance /
13929        // created / visit).
13930        $periodYear = [];
13931        $periodMonth = [];
13932        foreach (['sent_date', 'acceptance_date', 'created_at', 'visit_date'] as $dateField) {
13933            $dateCol = $dateField === 'sent_date' ? 'COALESCE(q.sent_date, q.issue_date)' : 'q.'.$dateField;
13934            $monday = "DATE_ADD({$dateCol}, INTERVAL - WEEKDAY({$dateCol}) DAY)";
13935            $periodYear[$dateField] = $calendarMonth ? "YEAR({$dateCol})" : "YEAR({$monday})";
13936            $periodMonth[$dateField] = $calendarMonth ? "MONTH({$dateCol})" : "MONTH({$monday})";
13937        }
13938
13939        if (isset($data['years']) && $data['years'] != null) {
13940            $years = implode(',', $data['years']);
13941            if (count($data['years']) > 0) {
13942                $whereYear = " AND YEAR({$fq}) IN ({$years})";
13943                // Acceptance / created branches keep their historic
13944                // issue_date year filter - only Emitidos moved to sent_date.
13945                $whereYearIssueDate = " AND YEAR(q.issue_date) IN ({$years})";
13946                $whereYearVisit = " AND YEAR(q.visit_date) IN ({$years})";
13947            }
13948        }
13949
13950        foreach ($companyIds as $v) {
13951
13952            $lflWhere = " AND q.company_id = {$v} ";
13953
13954            $query = "SELECT
13955                            CONCAT(
13956                                DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb}),
13957                                ' - ',
13958                                DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%c/%e/'), YEAR({$fb})
13959                            ) AS date_like,
13960                            YEAR({$fq}) 'year',
13961                            DATE_FORMAT((SELECT MIN({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS min_date_like,
13962                            DATE_FORMAT((SELECT MAX({$fq}) FROM tbl_quotations q WHERE {$fq} IS NOT NULL {$lflWhere}), '%m-%d') AS max_date_like,
13963                            {$v} 'company_id'
13964                        FROM
13965                            tbl_quotations q
13966                        WHERE
13967                            {$fq} IS NOT NULL
13968                            AND q.for_add = 0
13969                            {$lflWhere}
13970                            {$whereYear}
13971                        GROUP BY YEAR({$fq})
13972                        ORDER BY YEAR({$fq}) DESC";
13973
13974            $dateLike = DB::select($query);
13975
13976            if (count($dateLike) > 0) {
13977                $dateLflArray[$v] = $dateLike;
13978            }
13979        }
13980
13981        $whereAcceptanceDate = '';
13982
13983        if (isset($data['source']) && $data['source'] != null) {
13984            $where .= " AND s.name = '{$data['source']}'";
13985        }
13986
13987        if (isset($data['month']) && $data['month'] != null) {
13988            $where .= " AND MONTH(q.created_at) = '{$data['month']}'";
13989            // The Llamadas/Visitas columns come from tbl_pipelines, whose period
13990            // column is visit_date. Without this the month filter narrowed the
13991            // budget columns only and the visit/call counts kept showing the
13992            // whole year (and spawned extra month rows the filter excluded).
13993            $whereVisit .= " AND MONTH(q.visit_date) = '{$data['month']}'";
13994        }
13995
13996        if (isset($data['week']) && $data['week'] != null) {
13997            // FIRE-1202: WEEK(d, 3) = ISO 8601 (Monday-start, first week
13998            // contains Jan 4). Matches PHP date('W') used by the weekly
13999            // executive report (`Notifications::send_weekly_commercial_report`),
14000            // so a week number in the email and a week number on this page
14001            // refer to the same Mon–Sun range. Mode 0 (the previous default)
14002            // produces a "Week 0" partial week and disagrees with ISO by 1
14003            // for most of the year — see findings/FIRE-1202_Investigation.md.
14004            $where .= " AND WEEK(q.created_at, 3) = '{$data['week']}'";
14005            $whereVisit .= " AND WEEK(q.visit_date, 3) = '{$data['week']}'";
14006        }
14007
14008        if (isset($data['commercial']) && $data['commercial'] != null) {
14009            $commercial = implode("','", $data['commercial']);
14010            if (count($data['commercial']) > 0) {
14011                $where .= " AND q.commercial IN ('{$commercial}') ";
14012                $whereVisit .= " AND q.commercial IN ('{$commercial}') ";
14013            }
14014        }
14015
14016        if (isset($data['created_by']) && $data['created_by'] != null) {
14017            $created_by = implode("','", $data['created_by']);
14018            if (count($data['created_by']) > 0) {
14019                $where .= " AND q.created_by IN ('{$created_by}')";
14020            }
14021        }
14022
14023        if (isset($data['budget_type']) && $data['budget_type'] != null) {
14024            $where .= " AND bt.budget_type_id = {$data['budget_type']}";
14025        }
14026
14027        if (isset($data['budget_type_group']) && $data['budget_type_group'] != null) {
14028            $budgetTypeGroupIds = implode(',', $data['budget_type_group']);
14029            if (count($data['budget_type_group']) > 0) {
14030                $where .= " AND bt.budget_type_group_id IN ({$budgetTypeGroupIds})";
14031            }
14032        }
14033
14034        if (isset($data['budget_status']) && $data['budget_status'] != null) {
14035            $where .= " AND bs.budget_status_id = {$data['budget_status']}";
14036        }
14037
14038        if (isset($data['client_type']) && $data['client_type'] != null) {
14039            $where .= " AND ct.customer_type_id = {$data['client_type']}";
14040        }
14041
14042        if (isset($data['segment_id']) && $data['segment_id'] != null) {
14043            $where .= " AND q.segment_id = {$data['segment_id']}";
14044        }
14045
14046        if (isset($data['role_id']) && $data['role_id'] != null) {
14047            $roleId = implode(',', $data['role_id']);
14048            if (count($data['role_id']) > 0) {
14049                $where .= " AND r.role_id IN ({$roleId})";
14050                $whereVisit .= " AND r.role_id IN ({$roleId}) ";
14051            }
14052        }
14053
14054        $groupByFilter = 2;
14055        if (isset($data['group_by']) && $data['group_by'] != null) {
14056            $groupByFilter = $data['group_by'];
14057        }
14058
14059        $groupBy = '1, 2, 3, q.commercial, budget_type';
14060
14061        if ($groupByFilter == 1) {
14062            $groupBy = '1, q.commercial, 2, 3, budget_type';
14063        }
14064
14065        if ($groupByFilter == 3) {
14066            $groupBy = '1, budget_type, q.commercial, 2, 3';
14067        }
14068
14069        $aggregatedBy = 1;
14070        $aggregatedCol = "LPAD(q.month, 2, 0) AS 'month', LPAD(q.week, 2, 0) AS 'week', ";
14071        $aggregatedByCalc = ' / 4';
14072        if (isset($data['aggregated_by']) && $data['aggregated_by'] != null) {
14073            $aggregatedBy = $data['aggregated_by'];
14074            if ($data['aggregated_by'] == 1) {
14075
14076                $groupBy = '1, 2, 3, q.commercial, budget_type';
14077
14078                if ($groupByFilter == 1) {
14079                    $groupBy = '1, q.commercial, 2, 3, budget_type';
14080                }
14081
14082                if ($groupByFilter == 3) {
14083                    $groupBy = '1, budget_type, q.commercial, 2, 3';
14084                }
14085
14086                $aggregatedCol = "LPAD(q.month, 2, 0) AS 'month', LPAD(q.week, 2, 0) AS 'week', ";
14087            } elseif ($data['aggregated_by'] == 2) {
14088                $groupBy = '1, 2, q.commercial, budget_type';
14089
14090                if ($groupByFilter == 1) {
14091                    $groupBy = '1, q.commercial, 2, budget_type';
14092                }
14093
14094                if ($groupByFilter == 3) {
14095                    $groupBy = '1, budget_type, q.commercial, 2';
14096                }
14097
14098                $aggregatedCol = "LPAD(q.month, 2, 0) AS 'month', NULL AS 'week',";
14099                $aggregatedByCalc = '';
14100            } elseif ($data['aggregated_by'] == 3) {
14101                $groupBy = '1, q.commercial, budget_type';
14102
14103                if ($groupByFilter == 3) {
14104                    $groupBy = '1, budget_type, q.commercial';
14105                }
14106
14107                $aggregatedCol = "NULL AS 'month', NULL AS 'week',";
14108                $aggregatedByCalc = ' * 12';
14109            }
14110        }
14111
14112        // GROUP BY for the visit/call (Embudo) subquery.
14113        //
14114        // That subquery selects a literal `NULL budget_type` - tbl_pipelines has
14115        // no budget type. Leaving `budget_type` in its `WITH ROLLUP` therefore
14116        // asked MySQL to build a super-aggregate over a column that is already
14117        // constant NULL, and ROLLUP does not skip such a level: it emitted the
14118        // detail row AND an identical-looking super-aggregate row for every
14119        // (year, month, week, commercial). The outer query groups on the same
14120        // key, so the two rows merged and every Venta/Servicio Llamada # and
14121        // Visita # came out at exactly 2x, with each pipeline id repeated twice
14122        // in the drill-down list. Embudo then de-duplicated them through
14123        // `id IN (...)` and showed half as many rows as the number claimed.
14124        //
14125        // (For "year -> budget type groups" budget_type sits second instead of
14126        // last, so there the collision landed on the year row instead - same
14127        // cause, same fix.)
14128        //
14129        // Dropping budget_type from this branch's ROLLUP leaves exactly the
14130        // levels the page needs - commercial, week, month, year - with no two
14131        // levels sharing a key.
14132        $groupByVisit = implode(', ', array_filter(
14133            array_map('trim', explode(',', $groupBy)),
14134            fn ($col) => $col !== 'budget_type'
14135        ));
14136
14137        $whereAcceptanceDate = $where;
14138        $whereCreatedAt = $where;
14139
14140        $isFy = true;
14141
14142        if ($companyId != 0) {
14143            $where .= " AND q.company_id = {$companyId} ";
14144            $whereCreatedAt .= " AND q.company_id = {$companyId} ";
14145            $whereAcceptanceDate .= " AND q.company_id = {$companyId} ";
14146            $whereVisit .= " AND q.company_id = {$companyId} ";
14147        } else {
14148            $where .= " AND q.company_id IN ({$this->companyId}) ";
14149            $whereCreatedAt .= " AND q.company_id IN ({$this->companyId}) ";
14150            $whereAcceptanceDate .= " AND q.company_id IN ({$this->companyId}) ";
14151            $whereVisit .= " AND q.company_id IN ({$this->companyId}) ";
14152        }
14153
14154        if (isset($data['campaign']) && $data['campaign'] != null) {
14155            $campaign = implode("','", $data['campaign']);
14156            if (count($data['campaign']) > 0) {
14157                $whereVisit .= " AND q.campaign IN ('{$campaign}')";
14158            }
14159        }
14160
14161        if (isset($data['ytd']) && $data['ytd'] != null && $data['ytd'] == true) {
14162            $isFy = false;
14163            $now = date('m-d');
14164
14165            $where .= " AND DATE({$fq}) BETWEEN DATE_FORMAT({$fq}, '%Y-01-01') AND DATE_FORMAT({$fq}, '%Y-{$now}') ";
14166            $whereCreatedAt .= " AND q.created_at BETWEEN DATE_FORMAT(q.created_at, '%Y-01-01') AND DATE_FORMAT(q.created_at, '%Y-{$now}') ";
14167            $whereAcceptanceDate .= " AND q.acceptance_date BETWEEN DATE_FORMAT(q.acceptance_date, '%Y-01-01') AND DATE_FORMAT(q.acceptance_date, '%Y-{$now}') ";
14168            $whereVisit .= " AND q.visit_date BETWEEN DATE_FORMAT(q.visit_date, '%Y-01-01') AND DATE_FORMAT(q.visit_date, '%Y-{$now}') ";
14169        }
14170
14171        if (isset($data['lfl']) && $data['lfl'] != null && $data['lfl'] == true) {
14172            $isFy = false;
14173            $lflArray = [];
14174            $ytdAcceptanceArray = [];
14175            $lflVisitArray = [];
14176            $lflCompanyIds = [];
14177            $lflCompanyIdsAcc = [];
14178            $lflCompanyIdsVisit = [];
14179            foreach ($dateLflArray as $k => $v) {
14180                if (empty($v)) {
14181                    continue; // no data in range: contributes no rows, and "AND ()" is a SQL error
14182                }
14183
14184                foreach ($dateLflArray[$k] as $item) {
14185                    $year = $item->year;
14186                    $min_date_like = $item->min_date_like;
14187                    $max_date_like = $item->max_date_like;
14188                    array_push($lflArray, "DATE_FORMAT({$fq}, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
14189                    array_push($ytdAcceptanceArray, "DATE_FORMAT(q.acceptance_date, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
14190                    array_push($lflVisitArray, "DATE_FORMAT(q.visit_date, '%Y-%m-%d') BETWEEN LEAST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}') AND GREATEST('{$year}-{$min_date_like}', '{$year}-{$max_date_like}')");
14191                }
14192
14193                $lflArray = implode(' OR ', $lflArray);
14194                array_push($lflCompanyIds, "q.company_id = {$k} AND ({$lflArray})");
14195                $lflArray = [];
14196
14197                $ytdAcceptanceArray = implode(' OR ', $ytdAcceptanceArray);
14198                array_push($lflCompanyIdsAcc, "q.company_id = {$k} AND ({$ytdAcceptanceArray})");
14199                $ytdAcceptanceArray = [];
14200
14201                $lflVisitArray = implode(' OR ', $lflVisitArray);
14202                array_push($lflCompanyIdsVisit, "q.company_id = {$k} AND ({$lflVisitArray})");
14203                $lflVisitArray = [];
14204            }
14205
14206            $lflCompanyIds = implode(' OR ', $lflCompanyIds);
14207            $where .= ' AND ('.($lflCompanyIds ?: '1=0').') ';
14208
14209            $lflCompanyIdsAcc = implode(' OR ', $lflCompanyIdsAcc);
14210            $whereAcceptanceDate .= ' AND ('.($lflCompanyIdsAcc ?: '1=0').') ';
14211
14212            // Same window, on visit_date, for the Llamadas/Visitas columns -
14213            // previously LFL left the Embudo branch completely unfiltered.
14214            $lflCompanyIdsVisit = implode(' OR ', $lflCompanyIdsVisit);
14215            if ($lflCompanyIdsVisit !== '') {
14216                $whereVisit .= " AND ({$lflCompanyIdsVisit}) ";
14217            }
14218        }
14219
14220        $orderBy = 'CASE WHEN q.commercial IS NULL OR q.budget_type IS NULL THEN q.priority END DESC, q.priority ASC,';
14221
14222        if (isset($data['order_by'])) {
14223            $col = $data['order_by']['column'];
14224            $sort = $data['order_by']['sort'];
14225
14226            if (! empty($sort) || $sort != null) {
14227                $orderBy = "CASE WHEN q.commercial IS NULL OR q.budget_type IS NULL THEN {$col} END DESC, {$col} {$sort},";
14228            }
14229        }
14230
14231        $visitTypes = TblVisitTypeGroups::orderByRaw('ISNULL(priority), priority ASC')->get();
14232
14233        $visitCols = '';
14234        $visitMainTableCols = '';
14235        $visitSubMainTableCols = '';
14236        $visitSubTableCols = '';
14237        $visitMainCols = '';
14238
14239        $visitCall = ['Visita', 'Llamada'];
14240
14241        foreach ($visitCall as $value) {
14242            foreach ($visitTypes as $item) {
14243                $visitTypeNames = $value.$item->visit_type_group_id;
14244                // COUNT/GROUP_CONCAT DISTINCT on the pipeline id, not on a
14245                // literal: the branch LEFT JOINs tbl_users on `q.commercial =
14246                // u.name`, so a commercial whose name matches more than one
14247                // user row (duplicated/legacy accounts across regions) fanned
14248                // the same pipeline out into several rows. The counter then
14249                // read higher than the number of rows Embudo shows for exactly
14250                // the same ids.
14251                $visitCols .= ",COUNT(DISTINCT CASE WHEN q.visit_date IS NOT NULL AND v.visit_type_group_id = {$item->visit_type_group_id} AND q.visit_call = '{$value}' THEN q.id END) AS 'total{$visitTypeNames}'";
14252                $visitCols .= ",GROUP_CONCAT(DISTINCT CASE WHEN q.visit_date IS NOT NULL AND v.visit_type_group_id = {$item->visit_type_group_id} AND q.visit_call = '{$value}' THEN q.id END) AS 'groupConcatIds{$visitTypeNames}'";
14253                $visitMainTableCols .= ",COALESCE(SUM(q.total{$visitTypeNames}), 0) AS 'total{$visitTypeNames}'";
14254                $visitMainTableCols .= ",GROUP_CONCAT(q.groupConcatIds{$visitTypeNames})  AS 'groupConcatIds{$visitTypeNames}'";
14255                $visitSubMainTableCols .= ",q.total{$visitTypeNames}";
14256                $visitSubMainTableCols .= ",q.groupConcatIds{$visitTypeNames}";
14257                $visitSubTableCols .= ",0 AS total{$visitTypeNames}";
14258                $visitSubTableCols .= ",NULL AS groupConcatIds{$visitTypeNames}";
14259                $visitMainCols .= ",COALESCE(SUM(q.total{$visitTypeNames}), 0) total{$visitTypeNames}";
14260                $visitMainCols .= ",GROUP_CONCAT(q.groupConcatIds{$visitTypeNames}) groupConcatIds{$visitTypeNames}";
14261            }
14262        }
14263
14264        $businessGoalsDefault = TblBusinessGoals::where('is_default', 1)->where('budget_type_group_id', 999999999)->first();
14265
14266        // FIRE-1743: `is_amount` still falls back to 1 (amount-based) so the
14267        // outer `SUM(is_amountIssue) > 0` predicate keeps working when the
14268        // system default row is missing. The objective fallbacks are gone on
14269        // purpose — see the SQL CASE statements below: if no per-user,
14270        // per-role or default row matches, the objective now returns NULL and
14271        // the `%` collapses to NULL, which the frontend renders as "-%"
14272        // instead of the previous explosive numbers (`revenue / 1 * 100`).
14273        $businessGoalsDefault->is_amount ??= 1;
14274
14275        $gO = '';
14276
14277        if ($groupByFilter != 3) {
14278            $gO = "ORDER BY
14279                        1 DESC,
14280                        2 ASC,
14281                        3 ASC,
14282                        q.commercial ASC,
14283                        {$orderBy}
14284                        DATE_FORMAT(q.namedate, '%e') ASC";
14285        } else {
14286            $gO = 'ORDER BY
14287                        1 DESC,
14288                        2 ASC,
14289                        3 ASC,
14290                        budget_type ASC,
14291                        q.commercial ASC';
14292        }
14293
14294        $query = "WITH business_goal_objective_users AS (
14295                        SELECT
14296                            bg.user_id,
14297                            bg.issue_objective,
14298                            bg.acceptance_objective,
14299                            bg.new_objective,
14300                            bg.is_amount
14301                        FROM tbl_business_goals bg
14302                        WHERE bg.budget_type_group_id = 999999999
14303                    ), business_goal_objective_roles AS (
14304                        SELECT
14305                            bg.role_id,
14306                            bg.issue_objective,
14307                            bg.acceptance_objective,
14308                            bg.new_objective,
14309                            bg.is_amount
14310                        FROM tbl_business_goals bg
14311                        WHERE bg.budget_type_group_id = 999999999
14312                    )
14313
14314                    SELECT
14315                        q.year,
14316                        {$aggregatedCol}
14317                        q.namedate created_at,
14318                        q.commercial,
14319                        q.budget_type,
14320                        COALESCE(SUM(q.issue_date), 0) totalIssue,
14321                        COALESCE(SUM(q.created_at), 0) totalCreatedAt,
14322                        GROUP_CONCAT(q.groupConcatIds) groupConcatIds,
14323                        CASE
14324                            WHEN SUM(q.is_amountIssue) > 0 THEN
14325                                (SUM(q.revenueIssue) / NULLIF(SUM(q.issueObjective), 0)) * 100
14326                            ELSE
14327                                (SUM(q.issue_date) / NULLIF(SUM(q.issueObjective), 0)) * 100
14328                        END AS totalIssueObjective,
14329                        CASE
14330                            WHEN (CASE
14331                                WHEN SUM(q.is_amountIssue) > 0 THEN
14332                                    (SUM(q.revenueIssue) / NULLIF(SUM(q.issueObjective), 0)) * 100
14333                                ELSE
14334                                    (SUM(q.issue_date) / NULLIF(SUM(q.issueObjective), 0)) * 100
14335                            END) BETWEEN 1 AND 70 THEN 'text-danger'
14336                            WHEN (CASE
14337                                WHEN SUM(q.is_amountIssue) > 0 THEN
14338                                    (SUM(q.revenueIssue) / NULLIF(SUM(q.issueObjective), 0)) * 100
14339                                ELSE
14340                                    (SUM(q.issue_date) / NULLIF(SUM(q.issueObjective), 0)) * 100
14341                            END) BETWEEN 70 AND 90 THEN 'text-warning'
14342                        END textIssueColor,
14343                        SUM(q.revenueIssue) revenueIssue,
14344                        CASE
14345                            WHEN SUM(q.is_amountIssue) > 0 THEN
14346                                (SUM(q.revenueIssue) / NULLIF(SUM(q.issueObjectiveMonthly), 0)) * 100
14347                            ELSE
14348                                (SUM(q.issue_date) / NULLIF(SUM(q.issueObjectiveMonthly), 0)) * 100
14349                        END AS totalIssueObjectiveMonthly,
14350                        CASE
14351                            WHEN SUM(q.is_amountIssue) > 0 THEN
14352                                (SUM(q.revenueIssue) / NULLIF(SUM(q.issueObjectiveYearly), 0)) * 100
14353                            ELSE
14354                                (SUM(q.issue_date) / NULLIF(SUM(q.issueObjectiveYearly), 0)) * 100
14355                        END AS totalIssueObjectiveYearly,
14356                        COALESCE(SUM(q.acceptance_date), 0) totalAcceptance,
14357                        GROUP_CONCAT(q.groupConcatCreatedAtIds) groupConcatCreatedAtIds,
14358                        SUM(q.totalIssueLessThan5) AS totalIssueLessThan5,
14359                        GROUP_CONCAT(q.groupConcatIdsIssueLessThan5) AS groupConcatIdsIssueLessThan5,
14360                        GROUP_CONCAT(q.groupConcatAcceptanceIds) groupConcatAcceptanceIds,
14361                        CASE
14362                            WHEN SUM(q.is_amountAcceptance) > 0 THEN
14363                                (SUM(q.revenueAcceptance) / NULLIF(SUM(q.acceptanceObjective), 0)) * 100
14364                            ELSE
14365                                (SUM(q.acceptance_date) / NULLIF(SUM(q.acceptanceObjective), 0)) * 100
14366                        END AS totalAcceptanceObjective,
14367                        CASE
14368                            WHEN SUM(q.is_amountAcceptance) > 0 THEN
14369                                (SUM(q.revenueAcceptance) / NULLIF(SUM(q.acceptanceObjectiveMonthly), 0)) * 100
14370                            ELSE
14371                                (SUM(q.acceptance_date) / NULLIF(SUM(q.acceptanceObjectiveMonthly), 0)) * 100
14372                        END AS totalAcceptanceObjectiveMonthly,
14373                        CASE
14374                            WHEN SUM(q.is_amountAcceptance) > 0 THEN
14375                                (SUM(q.revenueAcceptance) / NULLIF(SUM(q.acceptanceObjectiveYearly), 0)) * 100
14376                            ELSE
14377                                (SUM(q.acceptance_date) / NULLIF(SUM(q.acceptanceObjectiveYearly), 0)) * 100
14378                        END AS totalAcceptanceObjectiveYearly,
14379                        CASE
14380                            WHEN (CASE
14381                                WHEN SUM(q.is_amountAcceptance) > 0 THEN
14382                                    (SUM(q.revenueAcceptance) / NULLIF(SUM(q.acceptanceObjective), 0)) * 100
14383                                ELSE
14384                                    (SUM(q.acceptance_date) / NULLIF(SUM(q.acceptanceObjective), 0)) * 100
14385                            END) BETWEEN 1 AND 70 THEN 'text-danger'
14386                            WHEN (CASE
14387                                WHEN SUM(q.is_amountAcceptance) > 0 THEN
14388                                    (SUM(q.revenueAcceptance) / NULLIF(SUM(q.acceptanceObjective), 0)) * 100
14389                                ELSE
14390                                    (SUM(q.acceptance_date) / NULLIF(SUM(q.acceptanceObjective), 0)) * 100
14391                            END) BETWEEN 70 AND 90 THEN 'text-warning'
14392                        END textAcceptanceColor,
14393                        SUM(q.revenueAcceptance) revenueAcceptance,
14394                        COALESCE(SUM(q.totalRejected), 0) totalRejected,
14395                        GROUP_CONCAT(q.groupConcatRejectedIds) groupConcatRejectedIds,
14396                        SUM(q.revenueRejected) revenueRejected,
14397                        COALESCE(SUM(q.totalNew)) totalNew,
14398                        GROUP_CONCAT(q.groupConcatNewIds) groupConcatNewIds,
14399                        CASE
14400                            WHEN SUM(q.is_amountNew) > 0 THEN
14401                                (SUM(q.revenueNew) / NULLIF(SUM(q.newObjective), 0)) * 100
14402                            ELSE
14403                                (SUM(q.totalNew) / NULLIF(SUM(q.newObjective), 0)) * 100
14404                        END AS totalNewObjective,
14405                        CASE
14406                            WHEN SUM(q.is_amountNew) > 0 THEN
14407                                (SUM(q.revenueNew) / NULLIF(SUM(q.newObjectiveMonthly), 0)) * 100
14408                            ELSE
14409                                (SUM(q.totalNew) / NULLIF(SUM(q.newObjectiveMonthly), 0)) * 100
14410                        END AS totalNewObjectiveMonthly,
14411                        CASE
14412                            WHEN SUM(q.is_amountNew) > 0 THEN
14413                                (SUM(q.revenueNew) / NULLIF(SUM(q.newObjectiveYearly), 0)) * 100
14414                            ELSE
14415                                (SUM(q.totalNew) / NULLIF(SUM(q.newObjectiveYearly), 0)) * 100
14416                        END AS totalNewObjectiveYearly,
14417                        CASE
14418                            WHEN (CASE
14419                                WHEN SUM(q.is_amountNew) > 0 THEN
14420                                    (SUM(q.revenueNew) / NULLIF(SUM(q.newObjective), 0)) * 100
14421                                ELSE
14422                                    (SUM(q.totalNew) / NULLIF(SUM(q.newObjective), 0)) * 100
14423                            END) BETWEEN 1 AND 70 THEN 'text-danger'
14424                            WHEN (CASE
14425                                WHEN SUM(q.is_amountNew) > 0 THEN
14426                                    (SUM(q.revenueNew) / NULLIF(SUM(q.newObjective), 0)) * 100
14427                                ELSE
14428                                    (SUM(q.totalNew) / NULLIF(SUM(q.newObjective), 0)) * 100
14429                            END) BETWEEN 70 AND 90 THEN 'text-warning'
14430                        END textNewColor,
14431                        SUM(q.revenueNew) revenueNew,
14432                        COALESCE(SUM(q.totalVisit), 0) totalVisit,
14433                        GROUP_CONCAT(q.groupConcatVisitIds) groupConcatVisitIds,
14434                        COALESCE(SUM(q.totalCall), 0) totalCall,
14435                        GROUP_CONCAT(q.groupConcatCallIds) groupConcatCallIds,
14436                        SUM(q.is_amountIssue) AS is_amountIssue,
14437                        SUM(q.is_amountNew) AS is_amountNew,
14438                        SUM(q.is_amountAcceptance) AS is_amountAcceptance,
14439                        SUM(q.issueObjective) AS issueObjective,
14440                        SUM(q.issueObjectiveMonthly) AS issueObjectiveMonthly,
14441                        SUM(q.issueObjectiveYearly) AS issueObjectiveYearly,
14442                        SUM(q.newObjective) AS newObjective,
14443                        SUM(q.newObjectiveMonthly) AS newObjectiveMonthly,
14444                        SUM(q.newObjectiveYearly) AS newObjectiveYearly,
14445                        SUM(q.acceptanceObjective) AS acceptanceObjective,
14446                        SUM(q.acceptanceObjectiveMonthly) AS acceptanceObjectiveMonthly,
14447                        SUM(q.acceptanceObjectiveYearly) AS acceptanceObjectiveYearly
14448                        {$visitMainCols}
14449                    FROM
14450                    (
14451                        SELECT
14452                            q.year,
14453                            q.month,
14454                            q.week,
14455                            q.namedate,
14456                            SUM(q.issue_date) AS issue_date,
14457                            q.acceptance_date,
14458                            q.created_at,
14459                            q.commercial,
14460                            q.budget_type,
14461                            GROUP_CONCAT(q.groupConcatIds) AS groupConcatIds,
14462                            CASE
14463                                WHEN q.is_amountIssue > 0 THEN
14464                                    SUM(q.revenueIssue / q.issueObjective) * 100
14465                                ELSE
14466                                    SUM(q.issue_date / q.issueObjective) * 100
14467                                END
14468                            AS totalIssueObjective,
14469                            CASE
14470                                WHEN q.is_amountIssue > 0 THEN
14471                                    SUM(q.revenueIssue / q.issueObjectiveMonthly) * 100
14472                                ELSE
14473                                    SUM(q.issue_date / q.issueObjectiveMonthly) * 100
14474                                END
14475                            AS totalIssueObjectiveMonthly,
14476                            CASE
14477                                WHEN q.is_amountIssue > 0 THEN
14478                                    SUM(q.revenueIssue / q.issueObjectiveYearly) * 100
14479                                ELSE
14480                                    SUM(q.issue_date / q.issueObjectiveYearly) * 100
14481                                END
14482                            AS totalIssueObjectiveYearly,
14483                            SUM(q.revenueIssue) revenueIssue,
14484                            GROUP_CONCAT(q.groupConcatCreatedAtIds) AS groupConcatCreatedAtIds,
14485                            SUM(q.totalIssueLessThan5) totalIssueLessThan5,
14486                            GROUP_CONCAT(q.groupConcatIdsIssueLessThan5) groupConcatIdsIssueLessThan5,
14487                            GROUP_CONCAT(q.groupConcatAcceptanceIds) AS groupConcatAcceptanceIds,
14488                            SUM(q.acceptanceObjective) totalAcceptanceObjective,
14489                            SUM(q.acceptanceObjectiveMonthly) totalAcceptanceObjectiveMonthly,
14490                            SUM(q.acceptanceObjectiveYearly) totalAcceptanceObjectiveYearly,
14491                            q.revenueAcceptance,
14492                            SUM(q.totalRejected) AS totalRejected,
14493                            GROUP_CONCAT(q.groupConcatRejectedIds) AS groupConcatRejectedIds,
14494                            SUM(q.revenueRejected) revenueRejected,
14495                            SUM(q.totalNew) AS totalNew,
14496                            GROUP_CONCAT(q.groupConcatNewIds) AS groupConcatNewIds,
14497                            CASE
14498                                WHEN q.is_amountNew > 0 THEN
14499                                    SUM(q.revenueNew / q.newObjective) * 100
14500                                ELSE
14501                                    SUM(q.totalNew / q.newObjective) * 100
14502                                END
14503                            AS totalNewObjective,
14504                             CASE
14505                                WHEN q.is_amountNew > 0 THEN
14506                                    SUM(q.revenueNew / q.newObjectiveMonthly) * 100
14507                                ELSE
14508                                    SUM(q.totalNew / q.newObjectiveMonthly) * 100
14509                                END
14510                            AS totalNewObjectiveMonthly,
14511                             CASE
14512                                WHEN q.is_amountNew > 0 THEN
14513                                    SUM(q.revenueNew / q.newObjectiveYearly) * 100
14514                                ELSE
14515                                    SUM(q.totalNew / q.newObjectiveYearly) * 100
14516                                END
14517                            AS totalNewObjectiveYearly,
14518                            SUM(q.revenueNew) revenueNew,
14519                            q.totalVisit,
14520                            q.groupConcatVisitIds,
14521                            q.totalCall,
14522                            q.groupConcatCallIds,
14523                            q.priority,
14524                            SUM(q.is_amountIssue) AS is_amountIssue,
14525                            SUM(q.is_amountNew) AS is_amountNew,
14526                            SUM(q.is_amountAcceptance) AS is_amountAcceptance,
14527                            SUM(q.issueObjective) AS issueObjective,
14528                            SUM(q.issueObjectiveMonthly) AS issueObjectiveMonthly,
14529                            SUM(q.issueObjectiveYearly) AS issueObjectiveYearly,
14530                            SUM(q.newObjective) AS newObjective,
14531                            SUM(q.newObjectiveMonthly) AS newObjectiveMonthly,
14532                            SUM(q.newObjectiveYearly) AS newObjectiveYearly,
14533                            SUM(q.acceptanceObjective) AS acceptanceObjective,
14534                            SUM(q.acceptanceObjectiveMonthly) AS acceptanceObjectiveMonthly,
14535                            SUM(q.acceptanceObjectiveYearly) AS acceptanceObjectiveYearly
14536                            {$visitSubMainTableCols}
14537                        FROM (
14538                            SELECT
14539                                {$periodYear['sent_date']} 'year',
14540                                {$periodMonth['sent_date']} 'month',
14541                                WEEK(COALESCE(q.sent_date, q.issue_date), 3) 'week', -- FIRE-1202: ISO 8601, matches email's PHP date('W')
14542                                DATE_FORMAT(DATE_ADD(COALESCE(q.sent_date, q.issue_date), INTERVAL - WEEKDAY(COALESCE(q.sent_date, q.issue_date)) DAY), '%W, %M %e') namedate,
14543                                COUNT(CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN 1 END) issue_date,
14544                                0 acceptance_date,
14545                                0 created_at,
14546                                q.commercial,
14547                                btg.name budget_type,
14548                                GROUP_CONCAT(CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN q.id END) AS groupConcatIds,
14549
14550                                SUM(CASE WHEN COALESCE(q.sent_date, q.issue_date) IS NOT NULL THEN q.amount END) AS revenueIssue,
14551                                NULL groupConcatCreatedAtIds,
14552                                0 totalIssueLessThan5,
14553                                NULL groupConcatIdsIssueLessThan5,
14554                                NULL groupConcatAcceptanceIds,
14555
14556                                0 revenueAcceptance,
14557                                COUNT(CASE WHEN bs.name = 'Rechazado' THEN 1 END) AS totalRejected,
14558                                GROUP_CONCAT(DISTINCT CASE WHEN bs.name = 'Rechazado' THEN q.id END) AS groupConcatRejectedIds,
14559                                COALESCE(SUM(CASE WHEN bs.name = 'Rechazado' THEN q.amount END), 0) AS revenueRejected,
14560                                COUNT(CASE WHEN ct.name = 'Nuevo' THEN 1 END) AS totalNew,
14561                                GROUP_CONCAT(DISTINCT CASE WHEN ct.name = 'Nuevo' THEN q.id END) AS groupConcatNewIds,
14562
14563                                COALESCE(SUM(CASE WHEN ct.name = 'Nuevo' THEN q.amount END), 0) revenueNew,
14564                                0 totalVisit,
14565                                NULL groupConcatVisitIds,
14566                                0 totalCall,
14567                                NULL groupConcatCallIds,
14568                                btg.priority,
14569                                CAST(
14570                                    CASE
14571                                        WHEN bg.issue_objective IS NOT NULL THEN bg.is_amount
14572                                        WHEN bg1.issue_objective IS NOT NULL THEN bg1.is_amount
14573                                        WHEN bg.issue_objective IS NULL AND bg1.issue_objective IS NULL THEN {$businessGoalsDefault->is_amount}
14574                                    END
14575                                AS DOUBLE) AS is_amountIssue,
14576                                CAST(
14577                                    CASE
14578                                        WHEN bg.new_objective IS NOT NULL THEN bg.is_amount
14579                                        WHEN bg1.new_objective IS NOT NULL THEN bg1.is_amount
14580                                        WHEN bg.new_objective IS NULL AND bg1.new_objective IS NULL THEN {$businessGoalsDefault->is_amount}
14581                                    END
14582                                AS DOUBLE) AS is_amountNew,
14583                                0 is_amountAcceptance,
14584                                CAST(
14585                                    CASE
14586                                        WHEN bg.issue_objective IS NOT NULL THEN bg.issue_objective
14587                                        WHEN bg1.issue_objective IS NOT NULL THEN bg1.issue_objective
14588                                    END {$aggregatedByCalc}
14589                                AS DOUBLE) AS issueObjective,
14590                                CAST(
14591                                    CASE
14592                                        WHEN bg.issue_objective IS NOT NULL THEN bg.issue_objective
14593                                        WHEN bg1.issue_objective IS NOT NULL THEN bg1.issue_objective
14594                                    END
14595                                AS DOUBLE) AS issueObjectiveMonthly,
14596                                CAST(
14597                                    CASE
14598                                        WHEN bg.issue_objective IS NOT NULL THEN bg.issue_objective
14599                                        WHEN bg1.issue_objective IS NOT NULL THEN bg1.issue_objective
14600                                    END * ((MONTH(CURDATE()) - 1) + FLOOR((DAY(CURDATE()) - 1) / 7) / 4)
14601                                AS DOUBLE) AS issueObjectiveYearly,
14602                                CAST(
14603                                    CASE
14604                                        WHEN bg.new_objective IS NOT NULL THEN bg.new_objective
14605                                        WHEN bg1.new_objective IS NOT NULL THEN bg1.new_objective
14606                                    END {$aggregatedByCalc}
14607                                AS DOUBLE) AS newObjective,
14608                                CAST(
14609                                    CASE
14610                                        WHEN bg.new_objective IS NOT NULL THEN bg.new_objective
14611                                        WHEN bg1.new_objective IS NOT NULL THEN bg1.new_objective
14612                                    END
14613                                AS DOUBLE) AS newObjectiveMonthly,
14614                                CAST(
14615                                    CASE
14616                                        WHEN bg.new_objective IS NOT NULL THEN bg.new_objective
14617                                        WHEN bg1.new_objective IS NOT NULL THEN bg1.new_objective
14618                                    END * ((MONTH(CURDATE()) - 1) + FLOOR((DAY(CURDATE()) - 1) / 7) / 4)
14619                                AS DOUBLE) AS newObjectiveYearly,
14620                                0 acceptanceObjective,
14621                                0 acceptanceObjectiveMonthly,
14622                                0 acceptanceObjectiveYearly
14623                                {$visitSubTableCols}
14624                            FROM
14625                            tbl_quotations q
14626                                LEFT JOIN tbl_sources s ON s.source_id = q.source_id
14627                                LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
14628                                LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
14629                                LEFT JOIN tbl_budget_type_groups btg ON btg.budget_type_group_id = bt.budget_type_group_id
14630                                LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
14631                                LEFT JOIN tbl_users u ON q.commercial = u.name
14632                                LEFT JOIN tbl_roles r ON u.role_id = r.role_id
14633                                LEFT JOIN tbl_business_goals bg ON bg.budget_type_group_id = btg.budget_type_group_id AND bg.user_id = u.id
14634                                LEFT JOIN tbl_business_goals bg1 ON bg1.budget_type_group_id = btg.budget_type_group_id AND bg1.role_id = r.role_id
14635                                LEFT JOIN tbl_business_goals bgde ON bgde.budget_type_group_id = btg.budget_type_group_id AND bgde.is_default = 1
14636                                LEFT JOIN business_goal_objective_users bgou ON bgou.user_id = u.id
14637                                LEFT JOIN business_goal_objective_roles bgor ON bgor.role_id = r.role_id
14638                            WHERE
14639                                q.budget_type_id != 7
14640                                AND q.budget_type_id IS NOT NULL
14641                                AND q.for_add = 0
14642                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
14643                                AND bt.include = 1
14644                                AND (q.commercial IS NOT NULL AND q.commercial != '')
14645                                AND u.is_active = 1
14646                                {$where}
14647                                {$whereYear}
14648                            GROUP BY
14649                                {$groupBy}
14650                        ) q
14651                        GROUP BY
14652                            {$groupBy} WITH ROLLUP
14653
14654                        UNION ALL
14655
14656                        SELECT
14657                            q.year,
14658                            q.month,
14659                            q.week,
14660                            q.namedate,
14661                            q.issue_date,
14662                            SUM(q.acceptance_date) AS acceptance_date,
14663                            q.created_at,
14664                            q.commercial,
14665                            q.budget_type,
14666                            q.groupConcatIds,
14667                            q.issueObjective totalIssueObjective,
14668                            q.issueObjectiveMonthly totalIssueObjectiveMonthly,
14669                            q.issueObjectiveYearly totalIssueObjectiveYearly,
14670                            q.revenueIssue,
14671                            q.groupConcatCreatedAtIds,
14672                            q.totalIssueLessThan5,
14673                            q.groupConcatIdsIssueLessThan5,
14674                            GROUP_CONCAT(q.groupConcatAcceptanceIds) AS groupConcatAcceptanceIds,
14675                            CASE
14676                                WHEN q.is_amountAcceptance > 0 THEN
14677                                    SUM(q.revenueAcceptance / q.acceptanceObjective) * 100
14678                                ELSE
14679                                    SUM(q.acceptance_date / q.acceptanceObjective) * 100
14680                                END
14681                            AS totalAcceptanceObjective,
14682                            CASE
14683                                WHEN q.is_amountAcceptance > 0 THEN
14684                                    SUM(q.revenueAcceptance / q.acceptanceObjectiveMonthly) * 100
14685                                ELSE
14686                                    SUM(q.acceptance_date / q.acceptanceObjectiveMonthly) * 100
14687                                END
14688                            AS totalAcceptanceObjectiveMonthly,
14689                            CASE
14690                                WHEN q.is_amountAcceptance > 0 THEN
14691                                    SUM(q.revenueAcceptance / q.acceptanceObjectiveYearly) * 100
14692                                ELSE
14693                                    SUM(q.acceptance_date / q.acceptanceObjectiveYearly) * 100
14694                                END
14695                            AS totalAcceptanceObjectiveYearly,
14696                            SUM(q.revenueAcceptance) revenueAcceptance,
14697                            q.totalRejected,
14698                            q.groupConcatRejectedIds,
14699                            q.revenueRejected,
14700                            q.totalNew,
14701                            q.groupConcatNewIds,
14702                            q.newObjective totalNewObjective,
14703                            q.newObjectiveMonthly totalNewObjectiveMonthly,
14704                            q.newObjectiveYearly totalNewObjectiveYearly,
14705                            q.revenueNew,
14706                            q.totalVisit,
14707                            q.groupConcatVisitIds,
14708                            q.totalCall,
14709                            q.groupConcatCallIds,
14710                            q.priority,
14711                            SUM(q.is_amountIssue) AS is_amountIssue,
14712                            q.is_amountNew,
14713                            q.is_amountAcceptance,
14714                            SUM(q.issueObjective) AS issueObjective,
14715                            SUM(q.issueObjectiveMonthly) AS issueObjectiveMonthly,
14716                            SUM(q.issueObjectiveYearly) AS issueObjectiveYearly,
14717                            SUM(q.newObjective) AS newObjective,
14718                            SUM(q.newObjectiveMonthly) AS newObjectiveMonthly,
14719                            SUM(q.newObjectiveYearly) AS newObjectiveYearly,
14720                            SUM(q.acceptanceObjective) AS acceptanceObjective,
14721                            SUM(q.acceptanceObjectiveMonthly) AS acceptanceObjectiveMonthly,
14722                            SUM(q.acceptanceObjectiveYearly) AS acceptanceObjectiveYearly
14723                            {$visitSubMainTableCols}
14724                        FROM (
14725                            SELECT
14726                                {$periodYear['acceptance_date']} 'year',
14727                                {$periodMonth['acceptance_date']} 'month',
14728                                WEEK(q.acceptance_date, 3) 'week', -- FIRE-1202: ISO 8601, matches email's PHP date('W')
14729                                DATE_FORMAT(DATE_ADD(q.acceptance_date, INTERVAL - WEEKDAY(q.acceptance_date) DAY), '%W, %M %e') namedate,
14730                                0 issue_date,
14731                                -- Aceptado = acceptance_date AND the status still says so.
14732                                -- acceptance_date is never cleared when a budget leaves
14733                                -- Aceptado: the AI duplicate detector and the Replace flow
14734                                -- move it to 20 (Rechazado-duplicado) (see
14735                                -- setSolicitudDuplicity / linkReplacedQuote) and a G3W sync
14736                                -- can flip the status while writing back the same
14737                                -- `aceptacion` date (PresupuestosService::syncModifiedBudgetById).
14738                                -- Keyed on the date alone, those rejected budgets kept
14739                                -- counting here and showed up in the drill-down list.
14740                                -- excludeReplacedQuotesSql() does not cover them: it only
14741                                -- drops status-20 rows that also carry a replaced_quotes link,
14742                                -- so AI-flagged duplicates survived it.
14743                                -- Matches AnalyticsRedesign (accepted_count) and
14744                                -- Notifications::send_weekly_commercial_report.
14745                                COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND bs.name = 'Aceptado' THEN 1 END) acceptance_date,
14746                                0 created_at,
14747                                q.commercial,
14748                                btg.name budget_type,
14749                                NULL groupConcatIds,
14750
14751                                0 revenueIssue,
14752                                NULL groupConcatCreatedAtIds,
14753                                0 totalIssueLessThan5,
14754                                NULL groupConcatIdsIssueLessThan5,
14755                                GROUP_CONCAT(DISTINCT CASE WHEN q.acceptance_date IS NOT NULL AND bs.name = 'Aceptado' THEN q.id END) AS groupConcatAcceptanceIds,
14756
14757                                COALESCE(SUM(CASE WHEN q.acceptance_date IS NOT NULL AND bs.name = 'Aceptado' THEN q.amount END), 0) AS revenueAcceptance,
14758                                0 totalRejected,
14759                                NULL groupConcatRejectedIds,
14760                                0 revenueRejected,
14761                                0 totalNew,
14762                                NULL groupConcatNewIds,
14763                                NULL totalNewObjective,
14764                                NULL totalNewObjectiveMonthly,
14765                                NULL totalNewObjectiveYearly,
14766                                0 revenueNew,
14767                                0 totalVisit,
14768                                NULL groupConcatVisitIds,
14769                                0 totalCall,
14770                                NULL groupConcatCallIds,
14771                                btg.priority,
14772                                0 is_amountIssue,
14773                                0 is_amountNew,
14774                                CAST(
14775                                    CASE
14776                                        WHEN bg.acceptance_objective IS NOT NULL THEN bg.is_amount
14777                                        WHEN bg1.acceptance_objective IS NOT NULL THEN bg1.is_amount
14778                                        WHEN bg.acceptance_objective IS NULL AND bg1.acceptance_objective IS NULL THEN {$businessGoalsDefault->is_amount}
14779                                    END
14780                                AS DOUBLE) AS is_amountAcceptance,
14781                                0 issueObjective,
14782                                0 issueObjectiveMonthly,
14783                                0 issueObjectiveYearly,
14784                                0 newObjective,
14785                                0 newObjectiveMonthly,
14786                                0 newObjectiveYearly,
14787                                CAST(
14788                                    CASE
14789                                        WHEN bg.acceptance_objective IS NOT NULL THEN bg.acceptance_objective
14790                                        WHEN bg1.acceptance_objective IS NOT NULL THEN bg1.acceptance_objective
14791                                    END {$aggregatedByCalc}
14792                                AS DOUBLE) AS acceptanceObjective,
14793                                CAST(
14794                                    CASE
14795                                        WHEN bg.acceptance_objective IS NOT NULL THEN bg.acceptance_objective
14796                                        WHEN bg1.acceptance_objective IS NOT NULL THEN bg1.acceptance_objective
14797                                    END
14798                                AS DOUBLE) AS acceptanceObjectiveMonthly,
14799                                CAST(
14800                                    CASE
14801                                        WHEN bg.acceptance_objective IS NOT NULL THEN bg.acceptance_objective
14802                                        WHEN bg1.acceptance_objective IS NOT NULL THEN bg1.acceptance_objective
14803                                    END * ((MONTH(CURDATE()) - 1) + FLOOR((DAY(CURDATE()) - 1) / 7) / 4)
14804                                AS DOUBLE) AS acceptanceObjectiveYearly
14805                                {$visitSubTableCols}
14806                            FROM
14807                            tbl_quotations q
14808                                LEFT JOIN tbl_sources s ON s.source_id = q.source_id
14809                                LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
14810                                LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
14811                                LEFT JOIN tbl_budget_type_groups btg ON btg.budget_type_group_id = bt.budget_type_group_id
14812                                LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
14813                                LEFT JOIN tbl_users u ON q.commercial = u.name
14814                                LEFT JOIN tbl_roles r ON u.role_id = r.role_id
14815                                LEFT JOIN tbl_business_goals bg ON bg.budget_type_group_id = btg.budget_type_group_id AND bg.user_id = u.id
14816                                LEFT JOIN tbl_business_goals bg1 ON bg1.budget_type_group_id = btg.budget_type_group_id AND bg1.role_id = r.role_id
14817                                LEFT JOIN tbl_business_goals bgde ON bgde.budget_type_group_id = btg.budget_type_group_id AND bgde.is_default = 1
14818                                LEFT JOIN business_goal_objective_users bgou ON bgou.user_id = u.id
14819                                LEFT JOIN business_goal_objective_roles bgor ON bgor.role_id = r.role_id
14820                            WHERE
14821                                q.budget_type_id != 7
14822                                AND q.budget_type_id IS NOT NULL
14823                                AND q.for_add = 0
14824                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
14825                                AND bt.include = 1
14826                                AND (q.commercial IS NOT NULL AND q.commercial != '')
14827                                AND u.is_active = 1
14828                                -- Same rule as the SELECT above, applied here too so a
14829                                -- period whose only acceptance-dated budget is now rejected
14830                                -- drops out instead of rendering an all-zero row. This
14831                                -- sub-query feeds the acceptance columns only — every other
14832                                -- column it selects is a literal 0/NULL — so narrowing it
14833                                -- cannot affect emitidos / rechazados / nuevos.
14834                                AND bs.name = 'Aceptado'
14835                                {$whereAcceptanceDate}
14836                                {$whereYearIssueDate}
14837                            GROUP BY
14838                                {$groupBy}
14839                        ) q
14840                        GROUP BY
14841                            {$groupBy} WITH ROLLUP
14842
14843                        UNION ALL
14844
14845                        SELECT
14846                            q.year,
14847                            q.month,
14848                            q.week,
14849                            q.namedate,
14850                            q.issue_date,
14851                            q.acceptance_date,
14852                            SUM(q.created_at) AS created_at,
14853                            q.commercial,
14854                            q.budget_type,
14855                            q.groupConcatIds,
14856                            q.issueObjective totalIssueObjective,
14857                            q.issueObjectiveMonthly totalIssueObjectiveMonthly,
14858                            q.issueObjectiveYearly totalIssueObjectiveYearly,
14859                            q.revenueIssue,
14860                            GROUP_CONCAT(q.groupConcatCreatedAtIds) AS groupConcatCreatedAtIds,
14861                            SUM(q.totalIssueLessThan5) AS totalIssueLessThan5,
14862                            GROUP_CONCAT(q.groupConcatIdsIssueLessThan5) AS groupConcatIdsIssueLessThan5,
14863                            NULL groupConcatAcceptanceIds,
14864                            0 totalAcceptanceObjective,
14865                            0 totalAcceptanceObjectiveMonthly,
14866                            0 totalAcceptanceObjectiveYearly,
14867                            SUM(q.revenueAcceptance) revenueAcceptance,
14868                            q.totalRejected,
14869                            q.groupConcatRejectedIds,
14870                            q.revenueRejected,
14871                            q.totalNew,
14872                            q.groupConcatNewIds,
14873                            q.newObjective totalNewObjective,
14874                            q.newObjectiveMonthly totalNewObjectiveMonthly,
14875                            q.newObjectiveYearly totalNewObjectiveYearly,
14876                            q.revenueNew,
14877                            q.totalVisit,
14878                            q.groupConcatVisitIds,
14879                            q.totalCall,
14880                            q.groupConcatCallIds,
14881                            q.priority,
14882                            SUM(q.is_amountIssue) AS is_amountIssue,
14883                            q.is_amountNew,
14884                            q.is_amountAcceptance,
14885                            SUM(q.issueObjective) AS issueObjective,
14886                            SUM(q.issueObjectiveMonthly) AS issueObjectiveMonthly,
14887                            SUM(q.issueObjectiveYearly) AS issueObjectiveYearly,
14888                            SUM(q.newObjective) AS newObjective,
14889                            SUM(q.newObjectiveMonthly) AS newObjectiveMonthly,
14890                            SUM(q.newObjectiveYearly) AS newObjectiveYearly,
14891                            SUM(q.acceptanceObjective) AS acceptanceObjective,
14892                            SUM(q.acceptanceObjectiveMonthly) AS acceptanceObjectiveMonthly,
14893                            SUM(q.acceptanceObjectiveYearly) AS acceptanceObjectiveYearly
14894                            {$visitSubMainTableCols}
14895                        FROM (
14896                            SELECT
14897                                {$periodYear['created_at']} 'year',
14898                                {$periodMonth['created_at']} 'month',
14899                                WEEK(q.created_at, 3) 'week', -- FIRE-1202: ISO 8601, matches email's PHP date('W')
14900                                DATE_FORMAT(DATE_ADD(q.created_at, INTERVAL - WEEKDAY(q.created_at) DAY), '%W, %M %e') namedate,
14901                                0 issue_date,
14902                                0 acceptance_date,
14903                                COUNT(CASE WHEN q.created_at IS NOT NULL THEN 1 END) created_at,
14904                                q.commercial,
14905                                btg.name budget_type,
14906                                NULL groupConcatIds,
14907
14908                                0 revenueIssue,
14909                                GROUP_CONCAT(CASE WHEN q.created_at IS NOT NULL THEN q.id END) AS groupConcatCreatedAtIds,
14910                                COUNT(CASE WHEN ABS(DATEDIFF(q.created_at, q.issue_date)) < 5 THEN 1 END) AS totalIssueLessThan5,
14911                                GROUP_CONCAT(CASE WHEN ABS(DATEDIFF(q.created_at, q.issue_date)) < 5 THEN q.id END) AS groupConcatIdsIssueLessThan5,
14912                                NULL groupConcatAcceptanceIds,
14913
14914                                0 AS revenueAcceptance,
14915                                0 totalRejected,
14916                                NULL groupConcatRejectedIds,
14917                                0 revenueRejected,
14918                                0 totalNew,
14919                                NULL groupConcatNewIds,
14920                                NULL totalNewObjective,
14921                                NULL totalNewObjectiveMonthly,
14922                                NULL totalNewObjectiveYearly,
14923                                0 revenueNew,
14924                                0 totalVisit,
14925                                NULL groupConcatVisitIds,
14926                                0 totalCall,
14927                                NULL groupConcatCallIds,
14928                                btg.priority,
14929                                0 is_amountIssue,
14930                                0 is_amountNew,
14931                                0 is_amountAcceptance,
14932                                0 issueObjective,
14933                                0 issueObjectiveMonthly,
14934                                0 issueObjectiveYearly,
14935                                0 newObjective,
14936                                0 newObjectiveMonthly,
14937                                0 newObjectiveYearly,
14938                                0 acceptanceObjective,
14939                                0 acceptanceObjectiveMonthly,
14940                                0 acceptanceObjectiveYearly
14941                                {$visitSubTableCols}
14942                            FROM
14943                            tbl_quotations q
14944                                LEFT JOIN tbl_sources s ON s.source_id = q.source_id
14945                                LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
14946                                LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
14947                                LEFT JOIN tbl_budget_type_groups btg ON btg.budget_type_group_id = bt.budget_type_group_id
14948                                LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
14949                                LEFT JOIN tbl_users u ON q.commercial = u.name
14950                                LEFT JOIN tbl_roles r ON u.role_id = r.role_id
14951                            WHERE
14952                                q.budget_type_id != 7
14953                                AND q.budget_type_id IS NOT NULL
14954                                AND q.for_add = 0
14955                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
14956                                AND bt.include = 1
14957                                AND (q.commercial IS NOT NULL AND q.commercial != '')
14958                                AND u.is_active = 1
14959                                {$whereCreatedAt}
14960                                {$whereYearIssueDate}
14961                            GROUP BY
14962                                {$groupBy}
14963                        ) q
14964                        GROUP BY
14965                            {$groupBy} WITH ROLLUP
14966
14967                        UNION ALL
14968
14969                        SELECT
14970                            {$periodYear['visit_date']} YEAR,
14971                            {$periodMonth['visit_date']} MONTH,
14972                            WEEK(q.visit_date, 3) WEEK, -- FIRE-1202: ISO 8601, matches email's PHP date('W')
14973                            DATE_FORMAT(DATE_ADD(visit_date, INTERVAL - WEEKDAY(q.visit_date) DAY), '%W, %M %e') namedate,
14974                            0 issue_date,
14975                            0 acceptance_date,
14976                            0 created_at,
14977                            commercial,
14978                            NULL budget_type,
14979                            NULL groupConcatIds,
14980                            NULL totalIssueObjective,
14981                            NULL totalIssueObjectiveMonthly,
14982                            NULL totalIssueObjectiveYearly,
14983                            0 revenueIssue,
14984                            NULL groupConcatCreatedAtIds,
14985                            0 totalIssueLessThan5,
14986                            NULL groupConcatIdsIssueLessThan5,
14987                            NULL groupConcatAcceptanceIds,
14988                            NULL totalAcceptanceObjective,NULL totalAcceptanceObjectiveMonthly,
14989                            NULL totalAcceptanceObjectiveYearly,
14990                            0 revenueAcceptance,
14991                            0 totalRejected,
14992                            NULL groupConcatRejectedIds,
14993                            0 revenueRejected,
14994                            0 totalNew,
14995                            NULL groupConcatNewIds,
14996                            NULL totalNewObjective,NULL totalNewObjectiveMonthly,
14997                            NULL totalNewObjectiveYearly,
14998                            0 revenueNew,
14999                            COUNT(DISTINCT CASE WHEN q.visit_date IS NOT NULL AND q.visit_call = 'Visita' THEN q.id END) totalVisit,
15000                            GROUP_CONCAT(DISTINCT CASE WHEN q.visit_date IS NOT NULL AND q.visit_call = 'Visita' THEN q.id END) AS groupConcatVisitIds,
15001                            COUNT(DISTINCT CASE WHEN q.visit_date IS NOT NULL AND q.visit_call = 'Llamada' THEN q.id END) totalCall,
15002                            GROUP_CONCAT(DISTINCT CASE WHEN q.visit_date IS NOT NULL AND q.visit_call = 'Llamada' THEN q.id END) AS groupConcatCallIds,
15003                            0 priority,
15004                            0 is_amountIssue,
15005                            0 is_amountNew,
15006                            0 is_amountAcceptance,
15007                            0 issueObjective,
15008                            0 issueObjectiveMonthly,
15009                            0 issueObjectiveYearly,
15010                            0 newObjective,
15011                            0 newObjectiveMontly,
15012                            0 newObjectiveYearly,
15013                            0 acceptanceObjective,
15014                            0 acceptanceObjectiveMonthly,
15015                            0 acceptanceObjectiveYearly
15016                            {$visitCols}
15017                        FROM
15018                            tbl_pipelines q
15019                        LEFT JOIN tbl_users u ON q.commercial = u.name
15020                        LEFT JOIN tbl_roles r ON u.role_id = r.role_id
15021                        LEFT JOIN tbl_visit_types v ON q.visit_type_id = v.visit_type_id
15022                        WHERE q.visit_date IS NOT NULL
15023                            {$whereVisit}
15024                            {$whereYearVisit}
15025                        GROUP BY
15026                            {$groupByVisit}
15027                             WITH ROLLUP
15028                    ) q
15029                    WHERE
15030                        q.year NOT IN (2021, 2022)
15031                    GROUP BY
15032                        {$groupBy}
15033                    {$gO}";
15034
15035        // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
15036        // Note: cache the post-processed (parsed) result, matching the prior behaviour.
15037        $result = ResultCache::remember('quotations', $query, 600, function () use ($query, $groupByFilter, $aggregatedBy) {
15038            // Every drill-down link on this page (Presupuestos, Llamadas,
15039            // Visitas) carries a GROUP_CONCAT of row ids, nested up to three
15040            // levels for the year/month/week rollups. MySQL's default
15041            // group_concat_max_len is 1024 bytes and truncates SILENTLY, so a
15042            // cell showing e.g. 400 visits handed Embudo ~140 ids - and the
15043            // last one was usually a half-written id that matched the wrong
15044            // pipeline. Raise it for this connection before the query runs.
15045            DB::statement('SET SESSION group_concat_max_len = 1000000');
15046
15047            $rows = DB::select($query);
15048            $structureData = new StructureData;
15049
15050            return $structureData->parse($rows, $groupByFilter, $aggregatedBy);
15051        });
15052
15053        // FIRE-1743 commit 7: the SQL still uses SUM(objective) per-quotation for
15054        // the rollup rows (year/month/week/commercial totals across budget_types),
15055        // which multiplies the goal by the number of quotations. That is why
15056        // Adolfo's year rollup came out as ~1% instead of ~147%.
15057        //
15058        // Rather than surgically split the 700-line SQL into aggregate vs
15059        // specific columns (high risk of breaking the 4 UNION-ed sub-queries),
15060        // we recompute the rollup % here in PHP against the commercial's
15061        // Default btg goal from tbl_business_goals (user Default → role Default,
15062        // no fallback to system Default per Ricardo's policy).
15063        //
15064        // Formula:
15065        //   year rollup    → revenue_YTD / (default_monthly × ((MONTH-1) + CEIL(DAY/7)/4)) × 100
15066        //   month rollup   → revenue_month / default_monthly × 100
15067        //   week rollup    → revenue_week / (default_monthly / 4) × 100
15068        //
15069        // Leaf rows (specific budget_type inside a week) already come out
15070        // correctly from the SQL because the SUM there is one row × per-btg
15071        // goal — no multiplication issue.
15072        $this->applyCommercialRollupObjectives($result, $groupByFilter, $aggregatedBy);
15073
15074        return response([
15075            'message' => 'OK',
15076            'data' => $result,
15077        ]);
15078
15079        // } catch (\Exception $e) {
15080        //     return response(['message' => 'KO', 'error' => $e->getMessage()]);
15081        // }
15082    }
15083
15084    /**
15085     * FIRE-1743 commit 7: overwrite the % on rollup rows (year / month / week /
15086     * commercial) so they compare against the commercial's Default btg goal
15087     * (user Default first, then role Default; no system fallback), pro-rated to
15088     * the appropriate time window.
15089     *
15090     * The specific-btg leaf rows are left alone — the SQL already handles those
15091     * correctly since they read a single per-btg goal.
15092     */
15093    private function applyCommercialRollupObjectives(array &$result, int $groupByFilter, int $aggregatedBy): void
15094    {
15095        // 1. Build map of commercial name → Default goal (issue / acceptance /
15096        //    new + is_amount). Cascade user Default → role Default. No system
15097        //    Default fallback (matches the SQL cascade removal for the leaf).
15098        $goalsByCommercial = $this->loadCommercialDefaultGoals();
15099
15100        // 2. YTD multiplier: months completed since Jan 1 + fraction of current
15101        //    month by FLOOR((day-1) / 7) / 4 — only fully-completed 7-day chunks
15102        //    of the current month count. Matches Duarte's expected calc for
15103        //    Alberto (Sales specialist, monthly goal 200 pptos): on 2026-08-20
15104        //    this yields 7 + 2/4 = 7.5, so YTD goal = 200 × 7.5 = 1500 pptos.
15105        //    Must match the SQL formula used for the per-btg leaf's yearly
15106        //    column (see Quotations.php:13748).
15107        $today = date_create();
15108        $monthsCompleted = (int) $today->format('n') - 1;
15109        $dayOfMonth = (int) $today->format('j');
15110        $weeksCompletedInCurrentMonth = (int) floor(($dayOfMonth - 1) / 7);
15111        $ytdMultiplier = $monthsCompleted + $weeksCompletedInCurrentMonth / 4;
15112
15113        // 3. Walk the tree carrying "current commercial goal" as we descend.
15114        //    Group_by=1 nests months/weeks INSIDE the commercial node
15115        //    (year → commercial → months → weeks → btg). Those inner nodes
15116        //    don't have a `commercial` field themselves — the parent
15117        //    commercial node does — so without goal propagation the recursion
15118        //    would skip them and they'd keep the SQL's broken SUM(objective).
15119        //    See Alberto Centella (Sales specialist) month 03: total 208
15120        //    against monthly goal 200 must render 104%, not the 28% the SQL
15121        //    produced by summing per-quotation goals.
15122        foreach ($result as &$yearData) {
15123            $this->rewriteRollupNode($yearData, $goalsByCommercial, $ytdMultiplier, 'year', null);
15124        }
15125    }
15126
15127    private function loadCommercialDefaultGoals(): array
15128    {
15129        // Per-metric structure: each of issue / acceptance / new tracks its own
15130        // value AND its own is_amount (the mode € vs #). is_amount lives on the
15131        // ROW that supplied the value. This matters because a user's provisioned
15132        // Default row (from provisionMissingCommercialGoals) has is_amount = 1
15133        // with NULL objectives, while their role's Default may be is_amount = 0
15134        // with real values. Without per-metric tracking, we'd inherit user's
15135        // is_amount = 1 (€ path) but role's count value → % ~50× wrong.
15136        //
15137        // Example: Alberto (Sales specialist, role Default acceptance = 200
15138        // count-based). His user Default row provisions with is_amount = 1
15139        // and NULL acceptance. The naive "one is_amount per commercial"
15140        // approach would keep is_amount = 1 and divide revenue (€) by 200 —
15141        // instead of dividing count by 200 as Duarte expects.
15142        $emptyMetric = ['value' => null, 'is_amount' => null];
15143        $emptyEntry = [
15144            'issue' => $emptyMetric,
15145            'acceptance' => $emptyMetric,
15146            'new' => $emptyMetric,
15147        ];
15148
15149        $map = [];
15150
15151        // Layer 1: user's Default btg row (budget_type_group_id = 999999999).
15152        $userGoals = DB::table('tbl_business_goals as bg')
15153            ->join('tbl_users as u', 'u.id', '=', 'bg.user_id')
15154            ->where('bg.budget_type_group_id', 999999999)
15155            ->where('u.is_active', 1)
15156            ->select('u.name as commercial', 'bg.issue_objective', 'bg.acceptance_objective', 'bg.new_objective', 'bg.is_amount')
15157            ->get();
15158
15159        foreach ($userGoals as $g) {
15160            $entry = $emptyEntry;
15161            $isAmount = (int) ($g->is_amount ?? 1);
15162            // Convention (see Commit 5 provisioning): a stored 0 means the goal
15163            // was never really set — the field was provisioned as a placeholder
15164            // and left untouched. Treat 0 the same as NULL when building the
15165            // cascade so a legacy 0-valued row can't shadow a role-Default
15166            // that actually has a real value.
15167            if ($g->issue_objective !== null && (float) $g->issue_objective > 0) {
15168                $entry['issue'] = ['value' => (float) $g->issue_objective, 'is_amount' => $isAmount];
15169            }
15170            if ($g->acceptance_objective !== null && (float) $g->acceptance_objective > 0) {
15171                $entry['acceptance'] = ['value' => (float) $g->acceptance_objective, 'is_amount' => $isAmount];
15172            }
15173            if ($g->new_objective !== null && (float) $g->new_objective > 0) {
15174                $entry['new'] = ['value' => (float) $g->new_objective, 'is_amount' => $isAmount];
15175            }
15176            $map[$g->commercial] = $entry;
15177        }
15178
15179        // Layer 2: role's Default btg — per-metric cascade. Each metric picks
15180        // up the role's value only when the user didn't supply one, and
15181        // inherits the role's is_amount alongside.
15182        $roleGoals = DB::table('tbl_business_goals as bg')
15183            ->join('tbl_users as u', 'u.role_id', '=', 'bg.role_id')
15184            ->where('bg.budget_type_group_id', 999999999)
15185            ->where('bg.is_commercial_type', 1)
15186            ->where('u.is_active', 1)
15187            ->select('u.name as commercial', 'bg.issue_objective', 'bg.acceptance_objective', 'bg.new_objective', 'bg.is_amount')
15188            ->get();
15189
15190        foreach ($roleGoals as $g) {
15191            $entry = $map[$g->commercial] ?? $emptyEntry;
15192            $isAmount = (int) ($g->is_amount ?? 1);
15193            // Same rule as the user layer: 0 acts as unset, so a role Default
15194            // row with real positive values wins over a user Default placeholder
15195            // even when both exist.
15196            if ($entry['issue']['value'] === null && $g->issue_objective !== null && (float) $g->issue_objective > 0) {
15197                $entry['issue'] = ['value' => (float) $g->issue_objective, 'is_amount' => $isAmount];
15198            }
15199            if ($entry['acceptance']['value'] === null && $g->acceptance_objective !== null && (float) $g->acceptance_objective > 0) {
15200                $entry['acceptance'] = ['value' => (float) $g->acceptance_objective, 'is_amount' => $isAmount];
15201            }
15202            if ($entry['new']['value'] === null && $g->new_objective !== null && (float) $g->new_objective > 0) {
15203                $entry['new'] = ['value' => (float) $g->new_objective, 'is_amount' => $isAmount];
15204            }
15205            $map[$g->commercial] = $entry;
15206        }
15207
15208        return $map;
15209    }
15210
15211    /**
15212     * Recursively rewrite the % on any node whose scope is at year / month /
15213     * week / commercial rollup level. The level determines whether the
15214     * denominator is YTD, monthly or weekly.
15215     *
15216     * `$scope` classifies the current node:
15217     *   - 'year'          — top level, aggregate across the whole year
15218     *   - 'month'         — within a year, aggregate across the whole month
15219     *   - 'week'          — within a month, aggregate across the whole week
15220     *   - 'commercial'    — one commercial's aggregate (level determined by parent chain)
15221     */
15222    private function rewriteRollupNode(array &$node, array $goalsByCommercial, float $ytdMultiplier, string $scope, ?array $inheritedGoal): void
15223    {
15224        // Skip budget_type LEAF rows — StructureData::parse tags them with a
15225        // `name` field (the budget_type name). Their % comes from the SQL and
15226        // is already correct (one per-btg goal, no SUM multiplication).
15227        // Only rewrite rollup nodes (commercial / week / month / year level).
15228        $isBudgetTypeLeaf = isset($node['name']) && ! isset($node['commercials'])
15229            && ! isset($node['months']) && ! isset($node['weeks']) && ! isset($node['budget_types']);
15230
15231        // Pick the goal to use for this node. A node with its own `commercial`
15232        // field looks up the goal fresh (also becomes the inherited goal for
15233        // its descendants). A node without `commercial` inherits from the
15234        // ancestor commercial — this is what fixes group_by=1 months and
15235        // weeks nested inside a commercial: they don't carry the commercial
15236        // name themselves, but they belong to their parent's goal.
15237        $activeGoal = $inheritedGoal;
15238        if (! $isBudgetTypeLeaf && isset($node['commercial']) && is_string($node['commercial'])) {
15239            $activeGoal = $goalsByCommercial[$node['commercial']] ?? null;
15240        }
15241
15242        if (! $isBudgetTypeLeaf && $activeGoal !== null) {
15243            $this->overwriteObjectiveColumns($node, $activeGoal, $ytdMultiplier, $scope);
15244        }
15245
15246        // Recurse into known child collections. Each has an implicit scope.
15247        // The `commercials` collection breaks inheritance (its children look
15248        // up their own goal); everything else propagates the current goal so
15249        // months / weeks under a commercial keep the right divisor.
15250        foreach ([
15251            'commercials' => [$scope, null],
15252            'months' => ['month', $activeGoal],
15253            'weeks' => ['week', $activeGoal],
15254            'budget_types' => [$scope, $activeGoal],
15255        ] as $childKey => [$childScope, $childInherited]) {
15256            if (isset($node[$childKey]) && is_array($node[$childKey])) {
15257                foreach ($node[$childKey] as &$child) {
15258                    if (is_array($child)) {
15259                        $this->rewriteRollupNode($child, $goalsByCommercial, $ytdMultiplier, $childScope, $childInherited);
15260                    }
15261                }
15262                unset($child);
15263            }
15264        }
15265    }
15266
15267    private function overwriteObjectiveColumns(array &$node, array $goal, float $ytdMultiplier, string $scope): void
15268    {
15269        foreach (['issue', 'acceptance', 'new'] as $metric) {
15270            // Per-metric goal + is_amount (see loadCommercialDefaultGoals).
15271            $monthlyGoal = $goal[$metric]['value'] ?? null;
15272            $isAmount = $goal[$metric]['is_amount'] ?? null;
15273            $useAmount = $isAmount === 1;
15274            $columnMap = [
15275                'issue' => ['num_amount' => 'revenueIssue', 'num_count' => 'totalIssue', 'weekly' => 'totalIssueObjective', 'monthly' => 'totalIssueObjectiveMonthly', 'yearly' => 'totalIssueObjectiveYearly', 'color' => 'textIssueColor'],
15276                'acceptance' => ['num_amount' => 'revenueAcceptance', 'num_count' => 'totalAcceptance', 'weekly' => 'totalAcceptanceObjective', 'monthly' => 'totalAcceptanceObjectiveMonthly', 'yearly' => 'totalAcceptanceObjectiveYearly', 'color' => 'textAcceptanceColor'],
15277                'new' => ['num_amount' => 'revenueNew', 'num_count' => 'totalNew', 'weekly' => 'totalNewObjective', 'monthly' => 'totalNewObjectiveMonthly', 'yearly' => 'totalNewObjectiveYearly', 'color' => 'textNewColor'],
15278            ][$metric];
15279
15280            if ($monthlyGoal === null || $monthlyGoal <= 0) {
15281                // No goal → all % columns render as -% on the FE.
15282                $node[$columnMap['weekly']] = null;
15283                $node[$columnMap['monthly']] = null;
15284                $node[$columnMap['yearly']] = null;
15285                $node[$columnMap['color']] = null;
15286
15287                continue;
15288            }
15289
15290            $numerator = $useAmount
15291                ? (float) ($node[$columnMap['num_amount']] ?? 0)
15292                : (float) ($node[$columnMap['num_count']] ?? 0);
15293
15294            $denominatorByScope = [
15295                'year' => $monthlyGoal * $ytdMultiplier,
15296                'month' => $monthlyGoal,
15297                'week' => $monthlyGoal / 4,
15298                'commercial' => $monthlyGoal * $ytdMultiplier,
15299            ];
15300
15301            $denominator = $denominatorByScope[$scope] ?? ($monthlyGoal * $ytdMultiplier);
15302            $pct = ($denominator > 0) ? ($numerator / $denominator) * 100 : null;
15303
15304            // The FE reads one of totalIssueObjective / …Monthly / …Yearly
15305            // depending on the row's tree depth. We set all three to the same
15306            // computed value so the render is consistent regardless of which
15307            // field the template picks at that level.
15308            $node[$columnMap['weekly']] = $pct;
15309            $node[$columnMap['monthly']] = $pct;
15310            $node[$columnMap['yearly']] = $pct;
15311
15312            // Match the SQL color thresholds (see totalIssueObjective CASE at
15313            // Quotations.php:13478-13490): red 1-70%, orange 70-90%, else null.
15314            if ($pct === null) {
15315                $node[$columnMap['color']] = null;
15316            } elseif ($pct >= 1 && $pct < 70) {
15317                $node[$columnMap['color']] = 'text-danger';
15318            } elseif ($pct >= 70 && $pct < 90) {
15319                $node[$columnMap['color']] = 'text-warning';
15320            } else {
15321                $node[$columnMap['color']] = null;
15322            }
15323        }
15324    }
15325
15326    public function list_quotations_deleted($companyId): ResponseFactory|HttpResponse
15327    {
15328
15329        try {
15330
15331            $companyId = addslashes((string) $companyId);
15332            $where = '';
15333
15334            if ($companyId != 0) {
15335                $where = " a.company_id = {$companyId} ";
15336            } else {
15337                $where = " a.company_id IN ({$this->companyId})";
15338            }
15339
15340            $query = "SELECT
15341                        a.id,
15342                        a.quote_id,
15343                        a.internal_quote_id,
15344                        a.company_id,
15345                        b.name company_name,
15346                        a.client,
15347                        c.name client_type,
15348                        c.customer_type_id,
15349                        s.name segment,
15350                        s.segment_id,
15351                        a.request_date,
15352                        a.visit_date,
15353                        a.issue_date,
15354                        a.acceptance_date,
15355                        a.internal_quote_id,
15356                        DATE_FORMAT(a.request_date, '%d/%m/%Y') request_date_translate,
15357                        DATE_FORMAT(a.issue_date, '%d/%m/%Y') issue_date_translate,
15358                        DATE_FORMAT(a.acceptance_date, '%d/%m/%Y') acceptance_date_translate,
15359                        DATE_FORMAT(a.last_follow_up_date, '%d/%m/%Y') last_follow_up_date_translate,
15360                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
15361                        DATE_FORMAT(a.accepted_at, '%d/%m/%Y') accepted_at_translate,
15362                        a.phone_number,
15363                        a.email,
15364                        a.send_channel,
15365                        a.direccion_postal,
15366                        COALESCE(a.sent_date, a.issue_date),
15367                        a.duration,
15368                        a.order_number,
15369                        d.name 'type',
15370                        d.budget_type_id,
15371                        e.name 'status',
15372                        e.budget_status_id,
15373                        f.name as source,
15374                        f.source_id,
15375                        a.codigo_id,
15376                        co.name AS codigo,
15377                        a.amount,
15378                        g.name reason_for_not_following_up,
15379                        a.reason_for_not_following_up_id,
15380                        a.reason_for_rejection_id,
15381                        a.last_follow_up_date,
15382                        a.last_follow_up_comment,
15383                        CASE WHEN a.reason_for_rejection_id IS NULL THEN a.reason_for_rejection ELSE h.name END reason_for_rejection,
15384                        a.commercial,
15385                        a.user_commercial_by_g3w,
15386                        a.user_create_by_g3w,
15387                        a.created_by,
15388                        a.created_at,
15389                        a.updated_by,
15390                        a.updated_at,
15391                        a.total_sent,
15392                        a.has_attachment,
15393                        a.for_approval,
15394                        a.approval_type,
15395                        a.requires_technical_office,
15396                        a.box_work_g3w,
15397                        a.people_assigned_to_the_job,
15398                        a.duration_of_job_in_days,
15399                        a.estimated_cost_of_materials,
15400                        a.budget_margin_enabled,
15401                        a.labor_manual_override,
15402                        a.question_enabled,
15403                        a.cost_of_labor,
15404                        a.total_cost_of_job,
15405                        a.invoice_margin invoice_margin,
15406                        a.margin_for_the_company margin_for_the_company,
15407                        a.margin_on_invoice_per_day_per_worker,
15408                        a.revenue_per_date_per_worked,
15409                        a.commission_cost,
15410                        a.commission_pct,
15411                        a.gross_margin,
15412                        a.labor_percentage,
15413                        a.question_ids,
15414                        a.question_ids_no,
15415                        a.approved_at,
15416                        a.approved_by,
15417                        a.rejected_at,
15418                        a.rejected_by,
15419                        a.approved_at_v2,
15420                        a.approved_by_v2,
15421                        a.rejected_at_v2,
15422                        a.rejected_by_v2,
15423                        a.accepted_at,
15424                        a.accepted_by,
15425                        a.is_validated,
15426                        a.maintenance_potential,
15427                        a.coverage_contract_signed,
15428                        a.resource_id,
15429                        a.x_status,
15430                        a.likehood,
15431                        a.sync_import,
15432                        a.sync_import_edited,
15433                        a.g3w_warning,
15434                        a.g3w_warning_fields
15435                    FROM tbl_quotations_deleted a
15436                    LEFT JOIN tbl_companies b ON a.company_id = b.company_id
15437                    LEFT JOIN tbl_customer_types c ON a.customer_type_id = c.customer_type_id
15438                    LEFT JOIN tbl_segments s ON a.segment_id = s.segment_id
15439                    LEFT JOIN tbl_budget_types d ON a.budget_type_id = d.budget_type_id
15440                    LEFT JOIN tbl_budget_status e ON a.budget_status_id = e.budget_status_id
15441                    LEFT JOIN tbl_sources f ON a.source_id = f.source_id
15442                    LEFT JOIN tbl_source_codigos co ON a.codigo_id = co.id
15443                    LEFT JOIN tbl_reason_for_not_following_up g ON a.reason_for_not_following_up_id = g.reason_for_not_following_up_id
15444                    LEFT JOIN tbl_reason_for_rejection h ON a.reason_for_rejection_id = h.reason_for_rejection_id
15445                    WHERE {$where}
15446                    ORDER BY a.updated_at DESC";
15447
15448            $result = DB::select($query);
15449
15450            return response([
15451                'message' => 'OK',
15452                'data' => $result,
15453            ]);
15454        } catch (\Exception $e) {
15455            report(AppException::fromException($e, 'LIST_QUOTATIONS_DELETED_EXCEPTION'));
15456
15457            return response(['message' => 'KO', 'error' => $e->getMessage()]);
15458        }
15459    }
15460
15461    public function delete_sengrid($id): ResponseFactory|HttpResponse
15462    {
15463
15464        try {
15465
15466            $id = addslashes((string) $id);
15467
15468            $order = TblQuotations::where('id', $id)->first();
15469
15470            if ($order) {
15471                if ($order->x_message_id != null) {
15472                    TblSendgridWebhook::where('quotation_id', $id)->where('x_message_id', $order->x_message_id)->delete();
15473
15474                    TblQuotations::where('id', $id)->update(
15475                        [
15476                            'x_message_id' => null,
15477                            'x_status' => null,
15478                        ]
15479                    );
15480
15481                    // FIRE-1145: was Cache::flush() — delete_sengrid clears email status shown in list_quotations.
15482                    ResultCache::forgetDomain('quotations');
15483                }
15484            }
15485
15486            return response([
15487                'message' => 'OK',
15488            ]);
15489
15490        } catch (\Exception $e) {
15491            report(AppException::fromException($e, 'DELETE_SENDGRID_EXCEPTION'));
15492
15493            return response(['message' => 'KO', 'error' => $e->getMessage()]);
15494        }
15495    }
15496
15497    public function download_productivity_commercial(Request $request): ResponseFactory|HttpResponse
15498    {
15499
15500        try {
15501
15502            ini_set('max_execution_time', 123456);
15503
15504            $data = $request->all();
15505
15506            $result = $this->list_quotation_analytics_commercial_productivity($request);
15507            $result = $result->original['data'];
15508
15509            $spreadsheet = new Spreadsheet;
15510            $worksheet = new Worksheet($spreadsheet, 'Inputs');
15511            $spreadsheet->addSheet($worksheet, 0);
15512            $col = range('A', 'Z');
15513
15514            for ($i = 0; $i < 26; $i++) {
15515                $worksheet->getColumnDimension($col[$i])->setAutoSize(true);
15516                if ($i != 1) {
15517                    $worksheet->getStyle($col[$i])
15518                        ->getAlignment()
15519                        ->setHorizontal(Alignment::HORIZONTAL_CENTER);
15520                }
15521            }
15522
15523            $l = 1;
15524            $worksheet->setCellValue('A'.$l, 'Años');
15525
15526            if ($data['group_by'] == 1) {
15527                $worksheet->setCellValue('B'.$l, 'Comercials');
15528                $worksheet->setCellValue('C'.$l, 'Meses');
15529                $worksheet->setCellValue('D'.$l, 'Semanas');
15530            } else {
15531                $worksheet->setCellValue('B'.$l, 'Meses');
15532                $worksheet->setCellValue('C'.$l, 'Semanas');
15533                $worksheet->setCellValue('D'.$l, 'Comercials');
15534            }
15535
15536            $worksheet->setCellValue('E'.$l, 'Categorías de presupuesto');
15537            $worksheet->setCellValue('F'.$l, 'Presupuestos emitidos (#)');
15538            $worksheet->setCellValue('G'.$l, 'Presupuestos emitidos (€)');
15539            $worksheet->setCellValue('H'.$l, 'Presupuestos emitidos (Objetivo)');
15540            $worksheet->setCellValue('I'.$l, 'Presupuestos aceptados (#)');
15541            $worksheet->setCellValue('J'.$l, 'Presupuestos aceptados (€)');
15542            $worksheet->setCellValue('K'.$l, 'Presupuestos aceptados (Objetivo)');
15543            $worksheet->setCellValue('L'.$l, 'Presupuestos rechazados (#)');
15544            $worksheet->setCellValue('M'.$l, 'Presupuestos rechazados (€)');
15545            $worksheet->setCellValue('N'.$l, 'Presupuestos emitidos a nuevos clientes (#)');
15546            $worksheet->setCellValue('O'.$l, 'Presupuestos emitidos a nuevos clientes (€)');
15547            $worksheet->setCellValue('P'.$l, 'Presupuestos emitidos a nuevos clientes (Objetivo)');
15548            $worksheet->setCellValue('Q'.$l, 'Venta (Llamada #)');
15549            $worksheet->setCellValue('R'.$l, 'Venta (Visita #)');
15550            $worksheet->setCellValue('S'.$l, 'Servicio (Llamada #)');
15551            $worksheet->setCellValue('T'.$l, 'Servicio (Visita #)');
15552
15553            $l++;
15554
15555            foreach ($result as $item) {
15556
15557                $worksheet->setCellValue('A'.$l, $item['year']);
15558                $worksheet->setCellValue('F'.$l, $item['totalIssue']);
15559                $worksheet->setCellValue('G'.$l, $item['revenueIssue']);
15560                $worksheet->setCellValue('H'.$l, '-');
15561
15562                $worksheet->setCellValue('I'.$l, $item['totalAcceptance']);
15563                $worksheet->setCellValue('J'.$l, $item['revenueAcceptance']);
15564                $worksheet->setCellValue('K'.$l, '-');
15565
15566                $worksheet->setCellValue('L'.$l, $item['totalRejected']);
15567                $worksheet->setCellValue('M'.$l, $item['revenueRejected']);
15568
15569                $worksheet->setCellValue('N'.$l, $item['totalNew']);
15570                $worksheet->setCellValue('O'.$l, $item['revenueNew']);
15571                $worksheet->setCellValue('P'.$l, '-');
15572
15573                $worksheet->setCellValue('Q'.$l, $item['totalLlamada1']);
15574                $worksheet->setCellValue('R'.$l, $item['totalVisita1']);
15575
15576                $worksheet->setCellValue('S'.$l, $item['totalLlamada2']);
15577                $worksheet->setCellValue('T'.$l, $item['totalVisita2']);
15578
15579                $l++;
15580
15581                if ($data['group_by'] == 1) {
15582
15583                    if (count($item['commercials']) > 0) {
15584
15585                        foreach ($item['commercials'] as $c) {
15586                            $worksheet->setCellValue('A'.$l, $item['year']);
15587
15588                            $worksheet->setCellValue('B'.$l, $c['commercial']);
15589                            $worksheet->setCellValue('F'.$l, $c['totalIssue']);
15590                            $worksheet->setCellValue('G'.$l, $c['revenueIssue']);
15591                            $worksheet->setCellValue('H'.$l, $c['totalIssueObjectiveYearly']);
15592
15593                            $worksheet->setCellValue('I'.$l, $c['totalAcceptance']);
15594                            $worksheet->setCellValue('J'.$l, $c['revenueAcceptance']);
15595                            $worksheet->setCellValue('K'.$l, $c['totalAcceptanceObjectiveYearly']);
15596
15597                            $worksheet->setCellValue('L'.$l, $c['totalRejected']);
15598                            $worksheet->setCellValue('M'.$l, $c['revenueRejected']);
15599
15600                            $worksheet->setCellValue('N'.$l, $c['totalNew']);
15601                            $worksheet->setCellValue('O'.$l, $c['revenueNew']);
15602                            $worksheet->setCellValue('P'.$l, $c['totalNewObjectiveYearly']);
15603
15604                            $worksheet->setCellValue('Q'.$l, $c['totalLlamada1']);
15605                            $worksheet->setCellValue('R'.$l, $c['totalVisita1']);
15606
15607                            $worksheet->setCellValue('S'.$l, $c['totalLlamada2']);
15608                            $worksheet->setCellValue('T'.$l, $c['totalVisita2']);
15609                            $l++;
15610
15611                            if (isset($c['budget_types']) && count($c['budget_types']) > 0) {
15612                                foreach ($c['budget_types'] as $b) {
15613                                    $worksheet->setCellValue('A'.$l, $item['year']);
15614                                    $worksheet->setCellValue('B'.$l, $c['commercial']);
15615
15616                                    $worksheet->setCellValue('E'.$l, $b['name']);
15617                                    $worksheet->setCellValue('F'.$l, $b['totalIssue']);
15618                                    $worksheet->setCellValue('G'.$l, $b['revenueIssue']);
15619                                    $worksheet->setCellValue('H'.$l, $b['totalIssueObjective']);
15620
15621                                    $worksheet->setCellValue('I'.$l, $b['totalAcceptance']);
15622                                    $worksheet->setCellValue('J'.$l, $b['revenueAcceptance']);
15623                                    $worksheet->setCellValue('K'.$l, $b['totalAcceptanceObjective']);
15624
15625                                    $worksheet->setCellValue('L'.$l, $b['totalRejected']);
15626                                    $worksheet->setCellValue('M'.$l, $b['revenueRejected']);
15627
15628                                    $worksheet->setCellValue('N'.$l, $b['totalNew']);
15629                                    $worksheet->setCellValue('O'.$l, $b['revenueNew']);
15630                                    $worksheet->setCellValue('P'.$l, $b['totalNewObjective']);
15631
15632                                    $worksheet->setCellValue('Q'.$l, $b['totalLlamada1']);
15633                                    $worksheet->setCellValue('R'.$l, $b['totalVisita1']);
15634
15635                                    $worksheet->setCellValue('S'.$l, $b['totalLlamada2']);
15636                                    $worksheet->setCellValue('T'.$l, $b['totalVisita2']);
15637                                    $l++;
15638                                }
15639                            }
15640
15641                            if (isset($c['months']) && count($c['months']) > 0) {
15642                                foreach ($c['months'] as $m) {
15643                                    $worksheet->setCellValue('A'.$l, $item['year']);
15644                                    $worksheet->setCellValue('B'.$l, $c['commercial']);
15645
15646                                    $worksheet->setCellValue('C'.$l, $m['month']);
15647                                    $worksheet->setCellValue('F'.$l, $m['totalIssue']);
15648                                    $worksheet->setCellValue('G'.$l, $m['revenueIssue']);
15649                                    $worksheet->setCellValue('H'.$l, $m['totalIssueObjectiveMonthly']);
15650
15651                                    $worksheet->setCellValue('I'.$l, $m['totalAcceptance']);
15652                                    $worksheet->setCellValue('J'.$l, $m['revenueAcceptance']);
15653                                    $worksheet->setCellValue('K'.$l, $m['totalAcceptanceObjectiveMonthly']);
15654
15655                                    $worksheet->setCellValue('L'.$l, $m['totalRejected']);
15656                                    $worksheet->setCellValue('M'.$l, $m['revenueRejected']);
15657
15658                                    $worksheet->setCellValue('N'.$l, $m['totalNew']);
15659                                    $worksheet->setCellValue('O'.$l, $m['revenueNew']);
15660                                    $worksheet->setCellValue('P'.$l, $m['totalNewObjectiveMonthly']);
15661
15662                                    $worksheet->setCellValue('Q'.$l, $m['totalLlamada1']);
15663                                    $worksheet->setCellValue('R'.$l, $m['totalVisita1']);
15664
15665                                    $worksheet->setCellValue('S'.$l, $m['totalLlamada2']);
15666                                    $worksheet->setCellValue('T'.$l, $m['totalVisita2']);
15667                                    $l++;
15668
15669                                    if (isset($m['weeks']) && count(@$m['weeks']) > 0 && count(@$m['weeks']) != 1) {
15670                                        foreach ($m['weeks'] as $w) {
15671                                            $worksheet->setCellValue('A'.$l, $item['year']);
15672                                            $worksheet->setCellValue('B'.$l, $c['commercial']);
15673                                            $worksheet->setCellValue('C'.$l, $m['month']);
15674
15675                                            $worksheet->setCellValue('D'.$l, $w['created_at']);
15676                                            $worksheet->setCellValue('F'.$l, $w['totalIssue']);
15677                                            $worksheet->setCellValue('G'.$l, $w['revenueIssue']);
15678                                            $worksheet->setCellValue('H'.$l, $w['totalIssueObjective']);
15679
15680                                            $worksheet->setCellValue('I'.$l, $w['totalAcceptance']);
15681                                            $worksheet->setCellValue('J'.$l, $w['revenueAcceptance']);
15682                                            $worksheet->setCellValue('K'.$l, $w['totalAcceptanceObjective']);
15683
15684                                            $worksheet->setCellValue('L'.$l, $w['totalRejected']);
15685                                            $worksheet->setCellValue('M'.$l, $w['revenueRejected']);
15686
15687                                            $worksheet->setCellValue('N'.$l, $w['totalNew']);
15688                                            $worksheet->setCellValue('O'.$l, $w['revenueNew']);
15689                                            $worksheet->setCellValue('P'.$l, $w['totalNewObjective']);
15690
15691                                            $worksheet->setCellValue('Q'.$l, $w['totalLlamada1']);
15692                                            $worksheet->setCellValue('R'.$l, $w['totalVisita1']);
15693
15694                                            $worksheet->setCellValue('S'.$l, $w['totalLlamada2']);
15695                                            $worksheet->setCellValue('T'.$l, $w['totalVisita2']);
15696                                            $l++;
15697
15698                                            if (count($w['budget_types']) > 0) {
15699                                                foreach ($w['budget_types'] as $b) {
15700                                                    $worksheet->setCellValue('A'.$l, $item['year']);
15701                                                    $worksheet->setCellValue('B'.$l, $c['commercial']);
15702                                                    $worksheet->setCellValue('C'.$l, $m['month']);
15703
15704                                                    $worksheet->setCellValue('E'.$l, $b['name']);
15705                                                    $worksheet->setCellValue('F'.$l, $b['totalIssue']);
15706                                                    $worksheet->setCellValue('G'.$l, $b['revenueIssue']);
15707                                                    $worksheet->setCellValue('H'.$l, $b['totalIssueObjective']);
15708
15709                                                    $worksheet->setCellValue('I'.$l, $b['totalAcceptance']);
15710                                                    $worksheet->setCellValue('J'.$l, $b['revenueAcceptance']);
15711                                                    $worksheet->setCellValue('K'.$l, $b['totalAcceptanceObjective']);
15712
15713                                                    $worksheet->setCellValue('L'.$l, $b['totalRejected']);
15714                                                    $worksheet->setCellValue('M'.$l, $b['revenueRejected']);
15715
15716                                                    $worksheet->setCellValue('N'.$l, $b['totalNew']);
15717                                                    $worksheet->setCellValue('O'.$l, $b['revenueNew']);
15718                                                    $worksheet->setCellValue('P'.$l, $b['totalNewObjective']);
15719
15720                                                    $worksheet->setCellValue('Q'.$l, $b['totalLlamada1']);
15721                                                    $worksheet->setCellValue('R'.$l, $b['totalVisita1']);
15722
15723                                                    $worksheet->setCellValue('S'.$l, $b['totalLlamada2']);
15724                                                    $worksheet->setCellValue('T'.$l, $b['totalVisita2']);
15725                                                    $l++;
15726                                                }
15727                                            }
15728                                        }
15729                                    } elseif (isset($m['weeks']) && count(@$m['weeks']) == 1) {
15730                                        foreach ($m['weeks'] as $w) {
15731                                            if (count($w['budget_types']) > 0) {
15732                                                foreach ($w['budget_types'] as $b) {
15733                                                    $worksheet->setCellValue('A'.$l, $item['year']);
15734                                                    $worksheet->setCellValue('B'.$l, $c['commercial']);
15735                                                    $worksheet->setCellValue('C'.$l, $m['month']);
15736
15737                                                    $worksheet->setCellValue('E'.$l, $b['name']);
15738                                                    $worksheet->setCellValue('F'.$l, $b['totalIssue']);
15739                                                    $worksheet->setCellValue('G'.$l, $b['revenueIssue']);
15740                                                    $worksheet->setCellValue('H'.$l, $b['totalIssueObjective']);
15741
15742                                                    $worksheet->setCellValue('I'.$l, $b['totalAcceptance']);
15743                                                    $worksheet->setCellValue('J'.$l, $b['revenueAcceptance']);
15744                                                    $worksheet->setCellValue('K'.$l, $b['totalAcceptanceObjective']);
15745
15746                                                    $worksheet->setCellValue('L'.$l, $b['totalRejected']);
15747                                                    $worksheet->setCellValue('M'.$l, $b['revenueRejected']);
15748
15749                                                    $worksheet->setCellValue('N'.$l, $b['totalNew']);
15750                                                    $worksheet->setCellValue('O'.$l, $b['revenueNew']);
15751                                                    $worksheet->setCellValue('P'.$l, $b['totalNewObjective']);
15752
15753                                                    $worksheet->setCellValue('Q'.$l, $b['totalLlamada1']);
15754                                                    $worksheet->setCellValue('R'.$l, $b['totalVisita1']);
15755
15756                                                    $worksheet->setCellValue('S'.$l, $b['totalLlamada2']);
15757                                                    $worksheet->setCellValue('T'.$l, $b['totalVisita2']);
15758                                                    $l++;
15759                                                }
15760                                            }
15761                                        }
15762
15763                                    }
15764                                }
15765                            }
15766                        }
15767                    }
15768                } else {
15769
15770                    if (isset($item['months']) && count($item['months']) > 0) {
15771                        foreach ($item['months'] as $m) {
15772                            $worksheet->setCellValue('A'.$l, $item['year']);
15773                            $worksheet->setCellValue('B'.$l, $m['month']);
15774                            $worksheet->setCellValue('F'.$l, $m['totalIssue']);
15775                            $worksheet->setCellValue('G'.$l, $m['revenueIssue']);
15776                            $worksheet->setCellValue('H'.$l, '-');
15777
15778                            $worksheet->setCellValue('I'.$l, $m['totalAcceptance']);
15779                            $worksheet->setCellValue('J'.$l, $m['revenueAcceptance']);
15780                            $worksheet->setCellValue('K'.$l, '-');
15781
15782                            $worksheet->setCellValue('L'.$l, $m['totalRejected']);
15783                            $worksheet->setCellValue('M'.$l, $m['revenueRejected']);
15784
15785                            $worksheet->setCellValue('N'.$l, $m['totalNew']);
15786                            $worksheet->setCellValue('O'.$l, $m['revenueNew']);
15787                            $worksheet->setCellValue('P'.$l, '-');
15788
15789                            $worksheet->setCellValue('Q'.$l, $m['totalLlamada1']);
15790                            $worksheet->setCellValue('R'.$l, $m['totalVisita1']);
15791
15792                            $worksheet->setCellValue('S'.$l, $m['totalLlamada2']);
15793                            $worksheet->setCellValue('T'.$l, $m['totalVisita2']);
15794                            $l++;
15795
15796                            if (isset($m['weeks']) && count(@$m['weeks']) > 0) {
15797                                foreach ($m['weeks'] as $w) {
15798                                    $worksheet->setCellValue('A'.$l, $item['year']);
15799                                    $worksheet->setCellValue('B'.$l, $m['month']);
15800
15801                                    $worksheet->setCellValue('C'.$l, $w['created_at']);
15802                                    $worksheet->setCellValue('F'.$l, $w['totalIssue']);
15803                                    $worksheet->setCellValue('G'.$l, $w['revenueIssue']);
15804                                    $worksheet->setCellValue('H'.$l, '-');
15805
15806                                    $worksheet->setCellValue('I'.$l, $w['totalAcceptance']);
15807                                    $worksheet->setCellValue('J'.$l, $w['revenueAcceptance']);
15808                                    $worksheet->setCellValue('K'.$l, '-');
15809
15810                                    $worksheet->setCellValue('L'.$l, $w['totalRejected']);
15811                                    $worksheet->setCellValue('M'.$l, $w['revenueRejected']);
15812
15813                                    $worksheet->setCellValue('N'.$l, $w['totalNew']);
15814                                    $worksheet->setCellValue('O'.$l, $w['revenueNew']);
15815                                    $worksheet->setCellValue('P'.$l, '-');
15816
15817                                    $worksheet->setCellValue('Q'.$l, $w['totalLlamada1']);
15818                                    $worksheet->setCellValue('R'.$l, $w['totalVisita1']);
15819
15820                                    $worksheet->setCellValue('S'.$l, $w['totalLlamada2']);
15821                                    $worksheet->setCellValue('T'.$l, $w['totalVisita2']);
15822                                    $l++;
15823
15824                                    if (count($w['commercials']) > 0) {
15825                                        foreach ($w['commercials'] as $c) {
15826                                            $worksheet->setCellValue('A'.$l, $item['year']);
15827                                            $worksheet->setCellValue('B'.$l, $m['month']);
15828
15829                                            $worksheet->setCellValue('D'.$l, $c['commercial']);
15830                                            $worksheet->setCellValue('F'.$l, $c['totalIssue']);
15831                                            $worksheet->setCellValue('G'.$l, $c['revenueIssue']);
15832                                            $worksheet->setCellValue('H'.$l, $c['totalIssueObjective']);
15833
15834                                            $worksheet->setCellValue('I'.$l, $c['totalAcceptance']);
15835                                            $worksheet->setCellValue('J'.$l, $c['revenueAcceptance']);
15836                                            $worksheet->setCellValue('K'.$l, $c['totalAcceptanceObjective']);
15837
15838                                            $worksheet->setCellValue('L'.$l, $c['totalRejected']);
15839                                            $worksheet->setCellValue('M'.$l, $c['revenueRejected']);
15840
15841                                            $worksheet->setCellValue('N'.$l, $c['totalNew']);
15842                                            $worksheet->setCellValue('O'.$l, $c['revenueNew']);
15843                                            $worksheet->setCellValue('P'.$l, $c['totalNewObjective']);
15844
15845                                            $worksheet->setCellValue('Q'.$l, $c['totalLlamada1']);
15846                                            $worksheet->setCellValue('R'.$l, $c['totalVisita1']);
15847
15848                                            $worksheet->setCellValue('S'.$l, $c['totalLlamada2']);
15849                                            $worksheet->setCellValue('T'.$l, $c['totalVisita2']);
15850                                            $l++;
15851
15852                                            if (count($c['budget_types']) > 0) {
15853                                                foreach ($c['budget_types'] as $b) {
15854                                                    $worksheet->setCellValue('A'.$l, $item['year']);
15855                                                    $worksheet->setCellValue('B'.$l, $m['month']);
15856                                                    $worksheet->setCellValue('D'.$l, $c['commercial']);
15857
15858                                                    $worksheet->setCellValue('E'.$l, $b['name']);
15859                                                    $worksheet->setCellValue('F'.$l, $b['totalIssue']);
15860                                                    $worksheet->setCellValue('G'.$l, $b['revenueIssue']);
15861                                                    $worksheet->setCellValue('H'.$l, $b['totalIssueObjective']);
15862
15863                                                    $worksheet->setCellValue('I'.$l, $b['totalAcceptance']);
15864                                                    $worksheet->setCellValue('J'.$l, $b['revenueAcceptance']);
15865                                                    $worksheet->setCellValue('K'.$l, $b['totalAcceptanceObjective']);
15866
15867                                                    $worksheet->setCellValue('L'.$l, $b['totalRejected']);
15868                                                    $worksheet->setCellValue('M'.$l, $b['revenueRejected']);
15869
15870                                                    $worksheet->setCellValue('N'.$l, $b['totalNew']);
15871                                                    $worksheet->setCellValue('O'.$l, $b['revenueNew']);
15872                                                    $worksheet->setCellValue('P'.$l, $b['totalNewObjective']);
15873
15874                                                    $worksheet->setCellValue('Q'.$l, $b['totalLlamada1']);
15875                                                    $worksheet->setCellValue('R'.$l, $b['totalVisita1']);
15876
15877                                                    $worksheet->setCellValue('S'.$l, $b['totalLlamada2']);
15878                                                    $worksheet->setCellValue('T'.$l, $b['totalVisita2']);
15879                                                    $l++;
15880                                                }
15881                                            }
15882                                        }
15883                                    }
15884                                }
15885                            }
15886
15887                            if (count($m['commercials']) > 0) {
15888                                foreach ($m['commercials'] as $c) {
15889                                    $worksheet->setCellValue('A'.$l, $item['year']);
15890                                    $worksheet->setCellValue('B'.$l, $m['month']);
15891
15892                                    $worksheet->setCellValue('D'.$l, $c['commercial']);
15893                                    $worksheet->setCellValue('F'.$l, $c['totalIssue']);
15894                                    $worksheet->setCellValue('G'.$l, $c['revenueIssue']);
15895                                    $worksheet->setCellValue('H'.$l, $c['totalIssueObjectiveYearly']);
15896
15897                                    $worksheet->setCellValue('I'.$l, $c['totalAcceptance']);
15898                                    $worksheet->setCellValue('J'.$l, $c['revenueAcceptance']);
15899                                    $worksheet->setCellValue('K'.$l, $c['totalAcceptanceObjectiveYearly']);
15900
15901                                    $worksheet->setCellValue('L'.$l, $c['totalRejected']);
15902                                    $worksheet->setCellValue('M'.$l, $c['revenueRejected']);
15903
15904                                    $worksheet->setCellValue('N'.$l, $c['totalNew']);
15905                                    $worksheet->setCellValue('O'.$l, $c['revenueNew']);
15906                                    $worksheet->setCellValue('P'.$l, $c['totalNewObjectiveYearly']);
15907
15908                                    $worksheet->setCellValue('Q'.$l, $c['totalLlamada1']);
15909                                    $worksheet->setCellValue('R'.$l, $c['totalVisita1']);
15910
15911                                    $worksheet->setCellValue('S'.$l, $c['totalLlamada2']);
15912                                    $worksheet->setCellValue('T'.$l, $c['totalVisita2']);
15913                                    $l++;
15914
15915                                    if (count($c['budget_types']) > 0) {
15916                                        foreach ($c['budget_types'] as $b) {
15917                                            $worksheet->setCellValue('A'.$l, $item['year']);
15918                                            $worksheet->setCellValue('B'.$l, $m['month']);
15919                                            $worksheet->setCellValue('D'.$l, $c['commercial']);
15920
15921                                            $worksheet->setCellValue('E'.$l, $b['name']);
15922                                            $worksheet->setCellValue('F'.$l, $b['totalIssue']);
15923                                            $worksheet->setCellValue('G'.$l, $b['revenueIssue']);
15924                                            $worksheet->setCellValue('H'.$l, $b['totalIssueObjective']);
15925
15926                                            $worksheet->setCellValue('I'.$l, $b['totalAcceptance']);
15927                                            $worksheet->setCellValue('J'.$l, $b['revenueAcceptance']);
15928                                            $worksheet->setCellValue('K'.$l, $b['totalAcceptanceObjective']);
15929
15930                                            $worksheet->setCellValue('L'.$l, $b['totalRejected']);
15931                                            $worksheet->setCellValue('M'.$l, $b['revenueRejected']);
15932
15933                                            $worksheet->setCellValue('N'.$l, $b['totalNew']);
15934                                            $worksheet->setCellValue('O'.$l, $b['revenueNew']);
15935                                            $worksheet->setCellValue('P'.$l, $b['totalNewObjective']);
15936
15937                                            $worksheet->setCellValue('Q'.$l, $b['totalLlamada1']);
15938                                            $worksheet->setCellValue('R'.$l, $b['totalVisita1']);
15939
15940                                            $worksheet->setCellValue('S'.$l, $b['totalLlamada2']);
15941                                            $worksheet->setCellValue('T'.$l, $b['totalVisita2']);
15942                                            $l++;
15943                                        }
15944                                    }
15945                                }
15946                            }
15947                        }
15948                    }
15949
15950                    if (count($item['commercials']) > 0) {
15951                        foreach ($item['commercials'] as $c) {
15952                            $worksheet->setCellValue('A'.$l, $item['year']);
15953
15954                            $worksheet->setCellValue('D'.$l, $c['commercial']);
15955                            $worksheet->setCellValue('F'.$l, $c['totalIssue']);
15956                            $worksheet->setCellValue('G'.$l, $c['revenueIssue']);
15957                            $worksheet->setCellValue('H'.$l, $c['totalIssueObjectiveYearly']);
15958
15959                            $worksheet->setCellValue('I'.$l, $c['totalAcceptance']);
15960                            $worksheet->setCellValue('J'.$l, $c['revenueAcceptance']);
15961                            $worksheet->setCellValue('K'.$l, $c['totalAcceptanceObjectiveYearly']);
15962
15963                            $worksheet->setCellValue('L'.$l, $c['totalRejected']);
15964                            $worksheet->setCellValue('M'.$l, $c['revenueRejected']);
15965
15966                            $worksheet->setCellValue('N'.$l, $c['totalNew']);
15967                            $worksheet->setCellValue('O'.$l, $c['revenueNew']);
15968                            $worksheet->setCellValue('P'.$l, $c['totalNewObjectiveYearly']);
15969
15970                            $worksheet->setCellValue('Q'.$l, $c['totalLlamada1']);
15971                            $worksheet->setCellValue('R'.$l, $c['totalVisita1']);
15972
15973                            $worksheet->setCellValue('S'.$l, $c['totalLlamada2']);
15974                            $worksheet->setCellValue('T'.$l, $c['totalVisita2']);
15975                            $l++;
15976
15977                            if (count($c['budget_types']) > 0) {
15978                                foreach ($c['budget_types'] as $b) {
15979                                    $worksheet->setCellValue('A'.$l, $item['year']);
15980                                    $worksheet->setCellValue('D'.$l, $c['commercial']);
15981
15982                                    $worksheet->setCellValue('E'.$l, $b['name']);
15983                                    $worksheet->setCellValue('F'.$l, $b['totalIssue']);
15984                                    $worksheet->setCellValue('G'.$l, $b['revenueIssue']);
15985                                    $worksheet->setCellValue('H'.$l, $b['totalIssueObjective']);
15986
15987                                    $worksheet->setCellValue('I'.$l, $b['totalAcceptance']);
15988                                    $worksheet->setCellValue('J'.$l, $b['revenueAcceptance']);
15989                                    $worksheet->setCellValue('K'.$l, $b['totalAcceptanceObjective']);
15990
15991                                    $worksheet->setCellValue('L'.$l, $b['totalRejected']);
15992                                    $worksheet->setCellValue('M'.$l, $b['revenueRejected']);
15993
15994                                    $worksheet->setCellValue('N'.$l, $b['totalNew']);
15995                                    $worksheet->setCellValue('O'.$l, $b['revenueNew']);
15996                                    $worksheet->setCellValue('P'.$l, $b['totalNewObjective']);
15997
15998                                    $worksheet->setCellValue('Q'.$l, $b['totalLlamada1']);
15999                                    $worksheet->setCellValue('R'.$l, $b['totalVisita1']);
16000
16001                                    $worksheet->setCellValue('S'.$l, $b['totalLlamada2']);
16002                                    $worksheet->setCellValue('T'.$l, $b['totalVisita2']);
16003                                    $l++;
16004                                }
16005                            }
16006                        }
16007                    }
16008                }
16009
16010                $l++;
16011            }
16012
16013            if ($data['group_by'] == 1) {
16014                if ($data['aggregated_by'] == 3) {
16015                    $worksheet->removeColumn('C');
16016                    $worksheet->removeColumn('C');
16017                } elseif ($data['aggregated_by'] == 2) {
16018                    $worksheet->removeColumn('D');
16019                }
16020            } else {
16021                if ($data['aggregated_by'] == 3) {
16022                    $worksheet->removeColumn('B');
16023                    $worksheet->removeColumn('B');
16024                } elseif ($data['aggregated_by'] == 2) {
16025                    $worksheet->removeColumn('C');
16026                }
16027            }
16028
16029            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
16030            ob_start();
16031            $writer->save('php://output');
16032            $file = ob_get_contents();
16033            ob_end_clean();
16034
16035            return response($file);
16036
16037        } catch (\Exception $e) {
16038            report(AppException::fromException($e, 'DOWNLOAD_PRODUCTIVITY_COMMERCIAL_EXCEPTION'));
16039
16040            return response(['message' => 'KO', 'error' => $e->getMessage()]);
16041        }
16042
16043    }
16044
16045    public function update_commercial_numbers($companyId): void
16046    {
16047        $phpBinary = '/usr/bin/php';
16048
16049        $artisanPath = escapeshellarg(base_path('artisan'));
16050
16051        $command = sprintf(
16052            '%s %s update:commercial-numbers %s > /dev/null 2>&1 &',
16053            $phpBinary,
16054            $artisanPath,
16055            $companyId
16056        );
16057
16058        exec($command, $output, $returnVar);
16059    }
16060
16061    public function list_quotation_analytics_by_service_type(Request $request): ResponseFactory|HttpResponse
16062    {
16063
16064        try {
16065
16066            $data = $request->all();
16067
16068            // Every filter below is interpolated into a ~17 KB SQL string that
16069            // reuses $where in four UNION branches, so inputs are validated and
16070            // cast here rather than bound. Anything malformed is a 422, not SQL.
16071            $invalid = fn (string $field) => response(['message' => 'KO', 'error' => "Invalid {$field}"], 422);
16072
16073            $companyIdRaw = (string) ($data['company_id'] ?? '0');
16074            if (! ctype_digit($companyIdRaw)) {
16075                return $invalid('company_id');
16076            }
16077            $companyId = (int) $companyIdRaw;
16078
16079            foreach (['start_date', 'end_date'] as $dateField) {
16080                if (! empty($data[$dateField]) && ! preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $data[$dateField])) {
16081                    return $invalid($dateField);
16082                }
16083            }
16084
16085            $where = '';
16086
16087            if ($companyId != 0) {
16088                $where .= " AND c.company_id = {$companyId} ";
16089            } elseif ($this->companyId !== '') {
16090                $where .= " AND c.company_id IN ({$this->companyId}) ";
16091            } else {
16092                // A user with no companies used to produce "IN ()" — a SQL
16093                // error the page rendered as two empty tables.
16094                return response(['message' => 'OK', 'data' => []]);
16095            }
16096
16097            $col = '1';
16098
16099            if (isset($data['data_to_display']) && $data['data_to_display'] != null) {
16100                if ($data['data_to_display'] == 1) {
16101                    $col = '1';
16102                }
16103
16104                if ($data['data_to_display'] == 2) {
16105                    $col = 'q.amount';
16106                }
16107            }
16108
16109            if (isset($data['approvals'])) {
16110                $approvals = (int) $data['approvals'];
16111
16112                if ($approvals == 2) {
16113                    $where .= ' AND q.for_approval != 1 ';
16114                }
16115
16116                if ($approvals == 3) {
16117                    $where .= ' AND q.for_approval > 0 ';
16118                }
16119
16120                if ($approvals == 4) {
16121                    $where .= ' AND q.approved_by IS NOT NULL';
16122                }
16123
16124                if ($approvals == 5) {
16125                    $where .= ' AND q.for_approval = 2 AND q.approved_by IS NULL';
16126                }
16127
16128                if ($approvals == 6) {
16129                    $where .= ' AND q.approved_by IS NOT NULL AND q.approved_by_v2 IS NOT NULL';
16130                }
16131
16132                if ($approvals == 7) {
16133                    $where .= ' AND q.for_approval = 3 AND q.approved_by IS NOT NULL AND q.approved_by_v2 IS NULL';
16134                }
16135
16136                if ($approvals == 8) {
16137                    $where .= ' AND q.for_approval = 3 AND q.approved_by IS NULL AND q.approved_by_v2 IS NOT NULL';
16138                }
16139
16140                if ($approvals == 9) {
16141                    $where .= ' AND q.for_approval = 3 AND q.approved_by IS NULL AND q.approved_by_v2 IS NULL';
16142                }
16143            }
16144
16145            if (isset($data['role_id']) && $data['role_id'] != null) {
16146                if (! is_array($data['role_id'])) {
16147                    return $invalid('role_id');
16148                }
16149                $roleIds = implode(',', array_map('intval', $data['role_id']));
16150                if (count($data['role_id']) > 0) {
16151                    $where .= " AND u.role_id IN ({$roleIds}, 999999999)";
16152                }
16153            }
16154
16155            if (isset($data['client_type']) && $data['client_type'] != null) {
16156                $where .= ' AND q.customer_type_id = '.(int) $data['client_type'];
16157            }
16158
16159            $weekDay = '- WEEKDAY(q.date)';
16160
16161            if (isset($data['start_of_the_week']) && $data['start_of_the_week'] != null) {
16162                $weekDay = match ($data['start_of_the_week']) {
16163                    0 => '- WEEKDAY(q.date)',
16164                    1 => '(1 - WEEKDAY(q.date))',
16165                    2 => '(2 - WEEKDAY(q.date))',
16166                    3 => '(3 - WEEKDAY(q.date))',
16167                    4 => '(4 - WEEKDAY(q.date))',
16168                    default => '- WEEKDAY(q.date)',
16169                };
16170            }
16171
16172            $whereDates = '';
16173
16174            if ((isset($data['start_date']) && $data['start_date'] != null) && (isset($data['end_date']) && $data['end_date'] != null)) {
16175                $whereDates = " AND DATE(q.date) BETWEEN '{$data['start_date']}' AND '{$data['end_date']}' ";
16176            }
16177
16178            $query = "SELECT
16179                        q.region,
16180                        YEAR(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) 'year',
16181                        LPAD(MONTH(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)), 2, 0) 'month',
16182                        LPAD(WEEK(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)), 2, 0) 'week',
16183                        DATE_FORMAT(DATE_ADD(q.date, INTERVAL {$weekDay} DAY), '%W, %M %e') namedate,
16184
16185                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' THEN q.id END) AS groupConcatIdsTotalEnviado,
16186                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END), 0) AS totalIssueEnviado,
16187
16188                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN q.id END) AS groupConcatIdsMantenimientoEnviado,
16189                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN {$col} END), 0) totalMantenimientoEnviado,
16190                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalMantenimientoPercentageEnviado,
16191
16192                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN q.id END) AS groupConcatIdsCorrectivosEnviado,
16193                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN {$col} END), 0) totalCorrectivosEnviado,
16194                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalCorrectivosPercentageEnviado,
16195
16196                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN q.id END) AS groupConcatIdsObrasEnviado,
16197                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN {$col} END), 0) totalObrasEnviado,
16198                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalObrasPercentageEnviado,
16199
16200                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN q.id END) AS groupConcatIdsOtrosEnviado,
16201                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END), 0) totalOtrosEnviado,
16202                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalOtrosPercentageEnviado,
16203
16204                        CASE
16205                            WHEN SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16206                            ELSE SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.s1 ELSE 0 END)
16207                                / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END)
16208                        END AS weightedAverageMarginForTheCompanyEnviado,
16209                        CASE
16210                            WHEN SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16211                            ELSE SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.s2 ELSE 0 END)
16212                                / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END)
16213                        END AS weightedAverageInvoiceEnviado,
16214
16215                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' THEN q.id END) AS groupConcatIdsTotalAceptado,
16216                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END), 0) AS totalIssueAceptado,
16217
16218                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN q.id END) AS groupConcatIdsMantenimientoAceptado,
16219                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN {$col} END), 0) totalMantenimientoAceptado,
16220                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalMantenimientoPercentageAceptado,
16221
16222                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN q.id END) AS groupConcatIdsCorrectivosAceptado,
16223                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN {$col} END), 0) totalCorrectivosAceptado,
16224                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalCorrectivosPercentageAceptado,
16225
16226                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN q.id END) AS groupConcatIdsObrasAceptado,
16227                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN {$col} END), 0) totalObrasAceptado,
16228                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalObrasPercentageAceptado,
16229
16230                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN q.id END) AS groupConcatIdsOtrosAceptado,
16231                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END), 0) totalOtrosAceptado,
16232                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalOtrosPercentageAceptado,
16233
16234                        CASE
16235                            WHEN SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16236                            ELSE SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.s1 ELSE 0 END)
16237                                / SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END)
16238                        END AS weightedAverageMarginForTheCompanyAceptado,
16239                        CASE
16240                            WHEN SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16241                            ELSE SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.s2 ELSE 0 END)
16242                                / SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END)
16243                        END AS weightedAverageInvoiceAceptado,
16244
16245                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' THEN 1 END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalIssuePercentage,
16246                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN {$col} END) * 100, 0) totalMantenimientoPercentage,
16247                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN {$col} END) * 100, 0) totalCorrectivosPercentage,
16248                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN {$col} END) * 100, 0) totalObrasPercentage,
16249                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) * 100 , 0) totalOtrosPercentage,
16250
16251                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL THEN {$col} END) * 100, 0) totalIssuePercentageLead,
16252                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id = 3 THEN {$col} END) * 100, 0) totalMantenimientoPercentageLead,
16253                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id = 5 THEN {$col} END) * 100, 0) totalCorrectivosPercentageLead,
16254                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id = 4 THEN {$col} END) * 100, 0) totalObrasPercentageLead,
16255                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) * 100 , 0) totalOtrosPercentageLead
16256                    FROM
16257                    (
16258                        SELECT
16259                            c.region,
16260                            COALESCE(q.sent_date, q.issue_date) AS DATE,
16261                            'issue' AS date_type,
16262                            q.acceptance_date,
16263                            q.issue_date,
16264                            COALESCE(q.sent_date, q.issue_date) AS sent_or_issue_date,
16265                            q.id,
16266                            q.margin_for_the_company,
16267                            CASE
16268                                WHEN bt.budget_type_group_id = 4
16269                                AND q.budget_margin_enabled > 0
16270                                AND q.budget_margin_enabled IS NOT NULL
16271                                AND q.margin_for_the_company <> 0
16272                            THEN q.margin_for_the_company * q.amount
16273                            END s1,
16274                            q.invoice_margin,
16275                            CASE
16276                                WHEN bt.budget_type_group_id = 4
16277                                AND q.budget_margin_enabled > 0
16278                                AND q.budget_margin_enabled IS NOT NULL
16279                                AND q.invoice_margin <> 0
16280                            THEN q.invoice_margin * q.amount
16281                            END s2,
16282                            q.budget_type_id,
16283                            q.budget_status_id,
16284                            q.amount,
16285                            bt.budget_type_group_id,
16286                            q.budget_margin_enabled
16287                        FROM
16288                            tbl_quotations q
16289                        JOIN tbl_companies c
16290                            ON c.company_id = q.company_id
16291                        LEFT JOIN tbl_budget_types bt
16292                            ON q.budget_type_id = bt.budget_type_id
16293                        LEFT JOIN tbl_users u
16294                            ON u.name = q.created_by
16295                        LEFT JOIN tbl_roles r
16296                            ON r.role_id = u.role_id
16297                        WHERE
16298                            COALESCE(q.sent_date, q.issue_date) IS NOT NULL
16299                            AND q.for_add = 0
16300                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
16301                            AND (q.commercial IS NOT NULL AND q.commercial != '')
16302                            AND q.budget_type_id != 7
16303                            AND q.budget_type_id IS NOT NULL
16304                            {$where}
16305
16306                        UNION ALL
16307
16308                        SELECT
16309                            c.region,
16310                            q.acceptance_date AS DATE,
16311                            'acceptance' AS date_type,
16312                            q.acceptance_date,
16313                            q.issue_date,
16314                            COALESCE(q.sent_date, q.issue_date) AS sent_or_issue_date,
16315                            q.id,
16316                            q.margin_for_the_company,
16317                            CASE
16318                                WHEN bt.budget_type_group_id = 4
16319                                AND q.budget_margin_enabled > 0
16320                                AND q.budget_margin_enabled IS NOT NULL
16321                                AND q.margin_for_the_company > 0
16322                            THEN q.margin_for_the_company * q.amount
16323                            END s1,
16324                            q.invoice_margin,
16325                            CASE
16326                                WHEN bt.budget_type_group_id = 4
16327                                AND q.budget_margin_enabled <> 0
16328                                AND q.budget_margin_enabled IS NOT NULL
16329                                AND q.invoice_margin <> 0
16330                            THEN q.invoice_margin * q.amount
16331                            END s2,
16332                            q.budget_type_id,
16333                            q.budget_status_id,
16334                            q.amount,
16335                            bt.budget_type_group_id,
16336                            q.budget_margin_enabled
16337                        FROM
16338                            tbl_quotations q
16339                        JOIN tbl_companies c
16340                            ON c.company_id = q.company_id
16341                        LEFT JOIN tbl_budget_types bt
16342                            ON q.budget_type_id = bt.budget_type_id
16343                        LEFT JOIN tbl_users u
16344                            ON u.name = q.created_by
16345                        LEFT JOIN tbl_roles r
16346                            ON r.role_id = u.role_id
16347                        WHERE
16348                            q.acceptance_date IS NOT NULL
16349                            AND q.for_add = 0
16350                            AND q.budget_type_id IS NOT NULL
16351                            AND q.budget_type_id != 7
16352                            AND q.acceptance_date != '0000-00-00 00:00:00'
16353                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
16354                            {$where}
16355                    ) AS q
16356                    WHERE q.date != '0000-00-00 00:00:00' {$whereDates}
16357                    GROUP BY
16358                        q.region,
16359                        YEAR(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)),
16360                        MONTH(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)),
16361                        WEEK(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) WITH ROLLUP
16362                    ORDER BY
16363                        q.region IS NULL,
16364                        q.region,
16365                        CASE WHEN q.region IS NOT NULL
16366                            AND YEAR(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) IS NULL
16367                            AND MONTH(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) IS NULL
16368                            AND WEEK(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) IS NULL
16369                        THEN 0
16370                        ELSE 1 END,
16371                    YEAR DESC,
16372                    MONTH ASC,
16373                    WEEK ASC";
16374
16375            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
16376            $result = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
16377
16378            $query = "SELECT
16379                        q.region,
16380                        YEAR(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) 'year',
16381                        LPAD(MONTH(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)), 2, 0) 'month',
16382                        LPAD(WEEK(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)), 2, 0) 'week',
16383                        DATE_FORMAT(DATE_ADD(q.date, INTERVAL {$weekDay} DAY), '%W, %M %e') namedate,
16384
16385                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' THEN q.id END) AS groupConcatIdsTotalEnviado,
16386                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END), 0) AS totalIssueEnviado,
16387
16388                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN q.id END) AS groupConcatIdsMantenimientoEnviado,
16389                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN {$col} END), 0) totalMantenimientoEnviado,
16390                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalMantenimientoPercentageEnviado,
16391
16392                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN q.id END) AS groupConcatIdsCorrectivosEnviado,
16393                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN {$col} END), 0) totalCorrectivosEnviado,
16394                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalCorrectivosPercentageEnviado,
16395
16396                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN q.id END) AS groupConcatIdsObrasEnviado,
16397                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN {$col} END), 0) totalObrasEnviado,
16398                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalObrasPercentageEnviado,
16399
16400                        GROUP_CONCAT(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN q.id END) AS groupConcatIdsOtrosEnviado,
16401                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END), 0) totalOtrosEnviado,
16402                        COALESCE(SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalOtrosPercentageEnviado,
16403
16404                        CASE
16405                            WHEN SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16406                            ELSE SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.s1 ELSE 0 END)
16407                                / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END)
16408                        END AS weightedAverageMarginForTheCompanyEnviado,
16409                        CASE
16410                            WHEN SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16411                            ELSE SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.s2 ELSE 0 END)
16412                                / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END)
16413                        END AS weightedAverageInvoiceEnviado,
16414
16415                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' THEN q.id END) AS groupConcatIdsTotalAceptado,
16416                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END), 0) AS totalIssueAceptado,
16417
16418                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN q.id END) AS groupConcatIdsMantenimientoAceptado,
16419                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN {$col} END), 0) totalMantenimientoAceptado,
16420                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalMantenimientoPercentageAceptado,
16421
16422                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN q.id END) AS groupConcatIdsCorrectivosAceptado,
16423                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN {$col} END), 0) totalCorrectivosAceptado,
16424                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalCorrectivosPercentageAceptado,
16425
16426                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN q.id END) AS groupConcatIdsObrasAceptado,
16427                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN {$col} END), 0) totalObrasAceptado,
16428                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalObrasPercentageAceptado,
16429
16430                        GROUP_CONCAT(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN q.id END) AS groupConcatIdsOtrosAceptado,
16431                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END), 0) totalOtrosAceptado,
16432                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) * 100, 0) totalOtrosPercentageAceptado,
16433
16434                        CASE
16435                            WHEN SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16436                            ELSE SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.s1 ELSE 0 END)
16437                                / SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.margin_for_the_company <> 0 THEN q.amount ELSE 0 END)
16438                        END AS weightedAverageMarginForTheCompanyAceptado,
16439                        CASE
16440                            WHEN SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END) = 0 THEN 0
16441                            ELSE SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.s2 ELSE 0 END)
16442                                / SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 AND q.budget_margin_enabled > 0 AND q.invoice_margin <> 0 THEN q.amount ELSE 0 END)
16443                        END AS weightedAverageInvoiceAceptado,
16444
16445                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' THEN {$col} END) * 100, 0) totalIssuePercentage,
16446                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 3 THEN {$col} END) * 100, 0) totalMantenimientoPercentage,
16447                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 5 THEN {$col} END) * 100, 0) totalCorrectivosPercentage,
16448                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id = 4 THEN {$col} END) * 100, 0) totalObrasPercentage,
16449                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) * 100 , 0) totalOtrosPercentage,
16450
16451                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL THEN {$col} END) * 100, 0) totalIssuePercentageLead,
16452                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id = 3 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id = 3 THEN {$col} END) * 100, 0) totalMantenimientoPercentageLead,
16453                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id = 5 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id = 5 THEN {$col} END) * 100, 0) totalCorrectivosPercentageLead,
16454                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id = 4 THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id = 4 THEN {$col} END) * 100, 0) totalObrasPercentageLead,
16455                        COALESCE(SUM(CASE WHEN q.date_type = 'acceptance' AND q.sent_or_issue_date IS NOT NULL AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) / SUM(CASE WHEN q.date_type = 'issue' AND q.acceptance_date IS NOT NULL AND q.budget_type_group_id IN (6, 7, 8) THEN {$col} END) * 100 , 0) totalOtrosPercentageLead
16456                    FROM
16457                    (
16458                        SELECT
16459                            'Total Grupo FIRE' region,
16460                            COALESCE(q.sent_date, q.issue_date) AS DATE,
16461                            'issue' AS date_type,
16462                            q.acceptance_date,
16463                            q.issue_date,
16464                            COALESCE(q.sent_date, q.issue_date) AS sent_or_issue_date,
16465                            q.id,
16466                            q.margin_for_the_company,
16467                            CASE
16468                                WHEN bt.budget_type_group_id = 4
16469                                AND q.budget_margin_enabled > 0
16470                                AND q.budget_margin_enabled IS NOT NULL
16471                                AND q.margin_for_the_company <> 0
16472                            THEN q.margin_for_the_company * q.amount
16473                            END s1,
16474                            q.invoice_margin,
16475                            CASE
16476                                WHEN bt.budget_type_group_id = 4
16477                                AND q.budget_margin_enabled > 0
16478                                AND q.budget_margin_enabled IS NOT NULL
16479                                AND q.invoice_margin <> 0
16480                            THEN q.invoice_margin * q.amount
16481                            END s2,
16482                            q.budget_type_id,
16483                            q.budget_status_id,
16484                            q.amount,
16485                            bt.budget_type_group_id,
16486                            q.budget_margin_enabled
16487                        FROM
16488                            tbl_quotations q
16489                        JOIN tbl_companies c
16490                            ON c.company_id = q.company_id
16491                        LEFT JOIN tbl_budget_types bt
16492                            ON q.budget_type_id = bt.budget_type_id
16493                        LEFT JOIN tbl_users u
16494                            ON u.name = q.created_by
16495                        LEFT JOIN tbl_roles r
16496                            ON r.role_id = u.role_id
16497                        WHERE
16498                            COALESCE(q.sent_date, q.issue_date) IS NOT NULL
16499                            AND q.for_add = 0
16500                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
16501                            AND (q.commercial IS NOT NULL AND q.commercial != '')
16502                            AND q.budget_type_id != 7
16503                            AND q.budget_type_id IS NOT NULL
16504                            {$where}
16505
16506                        UNION ALL
16507
16508                        SELECT
16509                            'Total Grupo FIRE' region,
16510                            q.acceptance_date AS DATE,
16511                            'acceptance' AS date_type,
16512                            q.acceptance_date,
16513                            q.issue_date,
16514                            COALESCE(q.sent_date, q.issue_date) AS sent_or_issue_date,
16515                            q.id,
16516                            q.margin_for_the_company,
16517                            CASE
16518                                WHEN bt.budget_type_group_id = 4
16519                                AND q.budget_margin_enabled > 0
16520                                AND q.budget_margin_enabled IS NOT NULL
16521                                AND q.margin_for_the_company <> 0
16522                            THEN q.margin_for_the_company * q.amount
16523                            END s1,
16524                            q.invoice_margin,
16525                            CASE
16526                                WHEN bt.budget_type_group_id = 4
16527                                AND q.budget_margin_enabled > 0
16528                                AND q.budget_margin_enabled IS NOT NULL
16529                                AND q.invoice_margin <> 0
16530                            THEN q.invoice_margin * q.amount
16531                            END s2,
16532                            q.budget_type_id,
16533                            q.budget_status_id,
16534                            q.amount,
16535                            bt.budget_type_group_id,
16536                            q.budget_margin_enabled
16537                        FROM
16538                            tbl_quotations q
16539                        JOIN tbl_companies c
16540                            ON c.company_id = q.company_id
16541                        LEFT JOIN tbl_budget_types bt
16542                            ON q.budget_type_id = bt.budget_type_id
16543                        LEFT JOIN tbl_users u
16544                            ON u.name = q.created_by
16545                        LEFT JOIN tbl_roles r
16546                            ON r.role_id = u.role_id
16547                        WHERE
16548                            q.acceptance_date IS NOT NULL
16549
16550                            AND q.for_add = 0
16551                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
16552                            AND (q.commercial IS NOT NULL AND q.commercial != '')
16553                            AND q.budget_type_id != 7
16554                            AND q.budget_type_id IS NOT NULL
16555                            {$where}
16556                    ) AS q
16557                    WHERE q.date != '0000-00-00 00:00:00' {$whereDates}
16558                    GROUP BY
16559                        q.region,
16560                        YEAR(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)),
16561                        MONTH(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)),
16562                        WEEK(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) WITH ROLLUP
16563                    ORDER BY
16564                        q.region IS NULL,
16565                        q.region,
16566                        CASE WHEN q.region IS NOT NULL
16567                            AND YEAR(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) IS NULL
16568                            AND MONTH(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) IS NULL
16569                            AND WEEK(DATE_ADD(q.date, INTERVAL {$weekDay} DAY)) IS NULL
16570                        THEN 0
16571                        ELSE 1 END,
16572                    YEAR DESC,
16573                    MONTH ASC,
16574                    WEEK ASC";
16575
16576            // FIRE-1145: domain-tagged cache (was Cache::get/put + Cache::flush()).
16577            $totalGroup = ResultCache::remember('quotations', $query, 600, fn () => DB::select($query));
16578
16579            array_pop($result);
16580            $merged = array_merge($result, $totalGroup);
16581
16582            return response([
16583                'message' => 'OK',
16584                'data' => $merged,
16585            ]);
16586
16587        } catch (\Exception $e) {
16588            report(AppException::fromException($e, 'LIST_QUOTATIONS_ANALYTICS_BY_SERVICE_TYPE_EXCEPTION'));
16589
16590            return response(['message' => 'KO', 'error' => $e->getMessage()]);
16591        }
16592
16593    }
16594
16595    public function getIdsFromInternalQuoteIds($ids)
16596    {
16597        $idsArray = array_filter(explode(',', (string) $ids), is_numeric(...));
16598
16599        return TblQuotations::whereIn('internal_quote_id', $idsArray)
16600            ->pluck('id')
16601            ->toArray();
16602    }
16603
16604    public function checkQuotationExistByInternalQuoteId(Request $request): ResponseFactory|HttpResponse
16605    {
16606        try {
16607            $idsString = $request->all()['ids'];
16608            $ids = explode(',', (string) $idsString);
16609            $region = urldecode((string) request()->header('Region'));
16610            $company = TblCompanies::where('region', $region)->first();
16611
16612            if (! $company) {
16613                // A bad Region header is the caller's mistake, not a server
16614                // fault: 404, and not reported to Sentry (PHP-LARAVEL-1D/1F).
16615                return response(['message' => 'KO', 'error' => 'Region no encontrada'], 404);
16616            }
16617
16618            $companyId = $company->company_id;
16619
16620            $idsChecked = [];
16621
16622            // FIRE-1476: CLM (22) merged into Madrid — single-company lookup.
16623            foreach ($ids as $id) {
16624                $quote = TblQuotations::where('internal_quote_id', $id)->where('company_id', $companyId)->first();
16625                $idsChecked[$id] = $quote ? $quote->id : null;
16626            }
16627
16628            return response([
16629                'message' => 'OK',
16630                'data' => $idsChecked,
16631            ]);
16632
16633        } catch (\Exception $e) {
16634            report(AppException::fromException($e, 'CHECK_QUOTATION_EXIST_BY_INTERNAL_QUOTE_ID_EXCEPTION'));
16635
16636            return response(['message' => 'KO', 'error' => $e->getMessage()]);
16637        }
16638
16639    }
16640
16641    public function addUpdateLog($id, $userId, $field, $oldData, $newData, int $category = 4): void
16642    {
16643        $categoryOptions = [
16644            'Crear solicitud',
16645            'Modificacion de solicitud',
16646            'Creacion presupuesto',
16647            'Solicitud a presupuesto',
16648            'Modificacion de presupuesto',
16649            'Accion del presupuesto',
16650            'Eliminacion del presupuesto',
16651            'Convertir presupuesto a trabajo',
16652        ];
16653
16654        if ($field === 'amount') {
16655            $oldData = (float) $oldData;
16656            $newData = (float) $newData;
16657        }
16658
16659        if (
16660            ($oldData === $newData && ! is_null($oldData)) ||
16661            $field === 'updated_at' ||
16662            $field === 'created_at' ||
16663            $field === 'last_follow_up_comment' ||
16664            $field === 'reason_for_rejection_id' ||
16665            $field === 'for_add' ||
16666            $field === 'has_attachment' ||
16667            $field === 'question_ids' ||
16668            $field === 'question_ids_no' ||
16669            $field === 'x_message_id' ||
16670            $field === 'from_company_id' ||
16671            $field === 'type_by_g3w' ||
16672            $field === 'user_create_by_g3w' ||
16673            $field === 'user_commercial_by_g3w' ||
16674            $field === 'user_technical_by_g3w' ||
16675            $field === 'user_responsible_by_g3w' ||
16676            $field === 'resource_id' ||
16677            $field === 'y_message_id' ||
16678            $field === 'y_status' ||
16679            $field === 'sync_import_edited' ||
16680            $field === 'updated_by' ||
16681            $field === 'likehood' ||
16682            $field === 'g3w_warning' ||
16683            $field === 'gross_margin' ||
16684            $field === 'duration' ||
16685            ($field === 'budget_type_id' && is_null($oldData) && is_null($newData)) ||
16686            ($field === 'margin_on_invoice_per_day_per_worker' && $newData === 0)
16687        ) {
16688            return;
16689        }
16690
16691        $oldRegister = null;
16692        $newRegister = null;
16693
16694        if (! is_null($oldData) || ! is_null($newData)) {
16695            switch ($field) {
16696                case 'company_id':
16697                    $oldRegister = TblCompanies::where('company_id', $oldData)->first();
16698                    $newRegister = TblCompanies::where('company_id', $newData)->first();
16699                    break;
16700                case 'customer_type_id':
16701                    $oldRegister = TblCustomerTypes::where('customer_type_id', $oldData)->first();
16702                    $newRegister = TblCustomerTypes::where('customer_type_id', $newData)->first();
16703                    break;
16704                case 'segment_id':
16705                    $oldRegister = TblSegments::where('segment_id', $oldData)->first();
16706                    $newRegister = TblSegments::where('segment_id', $newData)->first();
16707                    break;
16708                case 'budget_type_id':
16709                    $oldRegister = TblBudgetTypes::where('budget_type_id', $oldData)->first();
16710                    $newRegister = TblBudgetTypes::where('budget_type_id', $newData)->first();
16711                    break;
16712                case 'budget_status_id':
16713                    $oldRegister = TblBudgetStatus::where('budget_status_id', $oldData)->first();
16714                    $newRegister = TblBudgetStatus::where('budget_status_id', $newData)->first();
16715                    break;
16716                case 'source_id':
16717                    $oldRegister = TblSources::where('source_id', $oldData)->first();
16718                    $newRegister = TblSources::where('source_id', $newData)->first();
16719                    break;
16720            }
16721        }
16722
16723        $finalOld = $oldRegister ? $oldRegister->name : ($oldData ?? 'N/A');
16724        $finalNew = $newRegister ? $newRegister->name : ($newData ?? 'N/A');
16725
16726        if (is_numeric($userId)) {
16727            // Sentry perf (updateQuotation N+1): one log row per changed field,
16728            // each re-reading the same user. Look the name up once per instance.
16729            $userName = $this->logUserNames[(string) $userId] ??= (function () use ($userId) {
16730                $userObj = TblUsers::where('id', $userId)->first();
16731
16732                return $userObj ? $userObj->name : "Usuario desconocido ($userId)";
16733            })();
16734        } else {
16735            $userName = $userId;
16736        }
16737
16738        TblQuotationsLog::create([
16739            'category' => $categoryOptions[$category] ?? 'Otros',
16740            'quotation_id' => $id,
16741            'user' => $userName,
16742            'field' => $field,
16743            'old_value' => $finalOld,
16744            'new_value' => $finalNew,
16745        ]);
16746    }
16747
16748    public function setSolicitudDuplicity(Request $request): ResponseFactory|HttpResponse
16749    {
16750        // A missing key used to surface as an undefined-index 500.
16751        foreach (['type', 'quoteId', 'companyId'] as $required) {
16752            if (! $request->filled($required)) {
16753                return response(['message' => 'KO', 'error' => "Missing {$required}"], 422);
16754            }
16755        }
16756
16757        try {
16758            $type = $request->input('type');
16759            $quoteId = $request->input('quoteId');
16760            $companyId = $request->input('companyId');
16761
16762            $quote = TblQuotations::where('quote_id', $quoteId)->where('company_id', $companyId)->first();
16763
16764            if (! $quote) {
16765                // Unknown quote is the caller's mistake, not a server fault:
16766                // 404, and not reported to Sentry.
16767                return response(['message' => 'KO', 'error' => 'Quote no encontrada'], 404);
16768            }
16769
16770            $newIdSolicitudDuplicityValue = null;
16771
16772            if ($type === 'reject') {
16773                $quote->budget_status_id = 20;
16774                $newIdSolicitudDuplicityValue = 'R'.$quote->id_solicitud_duplicity;
16775            }
16776
16777            $this->addUpdateLog($quote->id, 'IA', 'id_solicitud_duplicity', $quote->id_solicitud_duplicity, $newIdSolicitudDuplicityValue);
16778
16779            $quote->id_solicitud_duplicity = $newIdSolicitudDuplicityValue;
16780
16781            $quote->save();
16782
16783            return response([
16784                'message' => 'OK',
16785                'data' => $quote,
16786            ]);
16787
16788        } catch (\Exception $e) {
16789            report(AppException::fromException($e, 'SET_SOLICITUD_DUPLICITY_EXCEPTION'));
16790
16791            return response(['message' => 'KO', 'error' => $e->getMessage()]);
16792        }
16793    }
16794
16795    public function getQuoteIdOfDuplicityById($id): ResponseFactory|HttpResponse
16796    {
16797        try {
16798            // PHP-LARAVEL-5: the FE used to hit this for every quotation it
16799            // opened, including the ones with no duplicity id at all, which
16800            // arrives here as the literal string "null". Guard anyway so a
16801            // cached client can't put it back into Sentry.
16802            if (blank($id) || in_array(strtolower((string) $id), ['null', 'undefined', '0'], true)) {
16803                return response(['message' => 'KO', 'error' => 'Quote no encontrada']);
16804            }
16805
16806            // FIRE-1253: id_solicitud_duplicity has two historical storage
16807            // shapes (internal id, quote_id string) because the AWS Lambda
16808            // checkduplicate writer has been inconsistent. Match either so
16809            // the banner resolves for both, regardless of the target's
16810            // current status / quote_id.
16811            $quote = TblQuotations::where('id', $id)
16812                ->orWhere('quote_id', $id)
16813                ->first();
16814
16815            if (! $quote) {
16816                // PHP-LARAVEL-5 / FIRE-1156: ~40 % of id_solicitud_duplicity
16817                // values point at rows that no longer exist, so a miss is an
16818                // expected outcome, not an exception. The FE renders its
16819                // "(no encontrado)" banner off this KO; reporting it produced
16820                // 3.7k Sentry events in 14d with 0 users affected.
16821                return response(['message' => 'KO', 'error' => 'Quote no encontrada']);
16822            }
16823
16824            return response([
16825                'message' => 'OK',
16826                'data' => $quote,
16827            ]);
16828
16829        } catch (\Exception $e) {
16830            report(AppException::fromException($e, 'GET_QUOTE_ID_OF_DUPLICITY_BY_QUOTE_ID_EXCEPTION'));
16831
16832            return response(['message' => 'KO', 'error' => $e->getMessage()]);
16833        }
16834    }
16835
16836    /* =====================================================================
16837     |  Replace quotation (sustitutos)
16838     * ===================================================================== */
16839
16840    /**
16841     * Resolve a pasted Quote # to a replaceable quotation inside one company.
16842     *
16843     * Backs the live check under the "Quote #" input on the add-quote form, and
16844     * is reused by create_quotation at save time so the UI and the write path
16845     * can never disagree about what counts as a valid target.
16846     *
16847     * Always HTTP 200 with message OK/KO — "no such quote" is an expected
16848     * answer to this question, not an error (see PHP-LARAVEL-5).
16849     */
16850    public function findQuotationForReplacement(Request $request): ResponseFactory|HttpResponse
16851    {
16852        try {
16853            $data = $request->all();
16854            $quoteId = trim((string) ($data['quote_id'] ?? ''));
16855            $companyId = (int) ($data['company_id'] ?? 0);
16856
16857            if ($quoteId === '' || $companyId <= 0) {
16858                return response(['message' => 'KO', 'error' => 'missing_params']);
16859            }
16860
16861            $quote = $this->resolveReplaceableQuote($quoteId, $companyId);
16862
16863            if (! $quote) {
16864                return response(['message' => 'KO', 'error' => 'not_found']);
16865            }
16866
16867            // Already superseded by something else — offering it again would
16868            // silently re-point the link and un-reject the first replacement.
16869            $existing = ReplacedQuote::where('old_quotation_id', $quote->id)->first();
16870
16871            if ($existing) {
16872                $by = TblQuotations::where('id', $existing->new_quotation_id)->first();
16873
16874                return response([
16875                    'message' => 'KO',
16876                    'error' => 'already_replaced',
16877                    'data' => [
16878                        'replaced_by_id' => $by->id ?? null,
16879                        'replaced_by_quote_id' => $by->quote_id ?? null,
16880                    ],
16881                ]);
16882            }
16883
16884            return response([
16885                'message' => 'OK',
16886                'data' => [
16887                    'id' => $quote->id,
16888                    'quote_id' => $quote->quote_id,
16889                    'client' => $quote->client,
16890                    'amount' => $quote->amount,
16891                    'budget_status_id' => $quote->budget_status_id,
16892                ],
16893            ]);
16894        } catch (\Exception $e) {
16895            report(AppException::fromException($e, 'FIND_QUOTATION_FOR_REPLACEMENT_EXCEPTION'));
16896
16897            return response(['message' => 'KO', 'error' => $e->getMessage()]);
16898        }
16899    }
16900
16901    /**
16902     * The single definition of "this Quote # can be replaced", shared by the
16903     * UI check and the save path.
16904     *
16905     * for_add = 0 only: 1 is a reserved-but-unfilled number and 2 is a row
16906     * already deleted via merge — neither is a real quote a client ever saw.
16907     */
16908    private function resolveReplaceableQuote(string $quoteId, int $companyId): ?TblQuotations
16909    {
16910        return TblQuotations::whereRaw('TRIM(LOWER(quote_id)) = ?', [mb_strtolower(trim($quoteId))])
16911            ->where('company_id', $companyId)
16912            ->where('for_add', 0)
16913            ->first();
16914    }
16915
16916    /**
16917     * Link a freshly created quote to the one it replaces, and retire the old
16918     * one: status 20 (Rechazado-duplicado) plus an audit-log entry.
16919     *
16920     * Re-validates rather than trusting the form — the tab may have sat open
16921     * while someone else replaced the same quote. Returns the link row, or null
16922     * when the target stopped being valid, in which case the new quote is still
16923     * saved and simply carries no replacement.
16924     */
16925    private function linkReplacedQuote(
16926        TblQuotations $newQuote,
16927        string $oldQuoteId,
16928        int $companyId,
16929        ?string $updatedBy
16930    ): ?ReplacedQuote {
16931        $old = $this->resolveReplaceableQuote($oldQuoteId, $companyId);
16932
16933        if (! $old || (int) $old->id === (int) $newQuote->id) {
16934            return null;
16935        }
16936
16937        if (ReplacedQuote::where('old_quotation_id', $old->id)->exists()) {
16938            return null;
16939        }
16940
16941        $link = ReplacedQuote::create([
16942            'new_quotation_id' => $newQuote->id,
16943            'old_quotation_id' => $old->id,
16944            'company_id' => $companyId,
16945            'created_by' => $updatedBy,
16946        ]);
16947
16948        // Audit the status change on the OLD quote before writing it, so the
16949        // log shows the transition rather than 20 → 20.
16950        $this->addUpdateLog(
16951            $old->id,
16952            $updatedBy ?? 'system',
16953            'budget_status_id',
16954            $old->budget_status_id,
16955            self::STATUS_REJECTED_DUPLICATE
16956        );
16957
16958        // And record what replaced it — the status alone does not say by whom.
16959        $this->addUpdateLog(
16960            $old->id,
16961            $updatedBy ?? 'system',
16962            'replaced_by',
16963            null,
16964            $newQuote->quote_id
16965        );
16966
16967        $old->budget_status_id = self::STATUS_REJECTED_DUPLICATE;
16968        $old->save();
16969
16970        return $link;
16971    }
16972
16973    /**
16974     * Drop quotes superseded via "Replace quotation" from a report query.
16975     *
16976     * Both halves are required: status 20 alone is also set by the AI
16977     * duplicate detector on quotes nobody replaced, and a replaced_quotes row
16978     * alone would hide a quote whose status was later moved back by hand.
16979     *
16980     * Assumes the quotations table is aliased `q`. Table existence is checked
16981     * so environments without the migration keep rendering their reports.
16982     */
16983    private function excludeReplacedQuotesSql(): string
16984    {
16985        try {
16986            if (! Schema::hasTable('replaced_quotes')) {
16987                return '';
16988            }
16989        } catch (\Throwable $e) {
16990            return '';
16991        }
16992
16993        return ' AND NOT (q.budget_status_id = '.self::STATUS_REJECTED_DUPLICATE
16994            .' AND EXISTS (SELECT 1 FROM replaced_quotes rq WHERE rq.old_quotation_id = q.id)) ';
16995    }
16996
16997    /**
16998     * Both directions of the replacement link for one quotation.
16999     *
17000     * Called when the edit/view modal opens, the same way the duplicity banner
17001     * is resolved, because editMode() is handed a table row rather than
17002     * re-fetching the quote.
17003     *
17004     *   replaced_by - this quote was superseded by that one (drives the yellow
17005     *                 banner and the read-only lockdown)
17006     *   replaces    - this quote superseded that one
17007     */
17008    public function getQuoteReplacementLinks($id): ResponseFactory|HttpResponse
17009    {
17010        try {
17011            if (blank($id) || ! is_numeric($id)) {
17012                return response(['message' => 'OK', 'data' => ['replaced_by' => null, 'replaces' => null]]);
17013            }
17014
17015            $id = (int) $id;
17016
17017            $brief = function (?int $quotationId): ?array {
17018                if (! $quotationId) {
17019                    return null;
17020                }
17021                $q = TblQuotations::where('id', $quotationId)->first();
17022
17023                return $q ? ['id' => $q->id, 'quote_id' => $q->quote_id] : null;
17024            };
17025
17026            $replacedBy = ReplacedQuote::where('old_quotation_id', $id)->first();
17027            $replaces = ReplacedQuote::where('new_quotation_id', $id)->first();
17028
17029            return response([
17030                'message' => 'OK',
17031                'data' => [
17032                    'replaced_by' => $brief($replacedBy->new_quotation_id ?? null),
17033                    'replaces' => $brief($replaces->old_quotation_id ?? null),
17034                ],
17035            ]);
17036        } catch (\Exception $e) {
17037            report(AppException::fromException($e, 'GET_QUOTE_REPLACEMENT_LINKS_EXCEPTION'));
17038
17039            return response(['message' => 'KO', 'error' => $e->getMessage()]);
17040        }
17041    }
17042
17043    public function download_s3_files(Request $request)
17044    {
17045        ini_set('max_execution_time', 123456);
17046
17047        try {
17048
17049            $data = $request->all();
17050            $zipName = 'files_'.time().'.zip';
17051
17052            $r = new Request([
17053                'filterModel' => $data['filterModel'] ?? [],
17054                'sortModel' => $data['sortModel'] ?? [],
17055                'start' => 0,
17056                'end' => 999999999,
17057                'company_id' => $data['company_id'],
17058                'user_id' => $data['user_id'],
17059                'ids' => $data['ids'],
17060                'searchText' => $data['searchText'] ?? '',
17061                'ids_not_in' => $data['ids_not_in'],
17062            ]);
17063
17064            $result = $this->list_orders_table($r);
17065            $result = $result->original['data'];
17066            $orderIds = array_column($result, 'id');
17067
17068            $files = TblFiles::whereIn('quotation_id', $orderIds)->where('is_internal', null)->get();
17069            if ($files->isEmpty()) {
17070                return response(['message' => 'KO', 'error' => 'No files found']);
17071            }
17072
17073            $tempDir = storage_path('app/temp');
17074
17075            if (! file_exists($tempDir)) {
17076                mkdir($tempDir, 0755, true);
17077            }
17078
17079            $zipPath = $tempDir.'/'.$zipName;
17080
17081            $zip = new ZipArchive;
17082            if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
17083                return response(['message' => 'KO', 'error' => 'Could not create ZIP file']);
17084            }
17085
17086            foreach ($files as $file) {
17087                $filePath = 'uploads/'.$file->filename;
17088
17089                if (Storage::disk('s3')->exists($filePath)) {
17090                    $contents = Storage::disk('s3')->get($filePath);
17091                    $zip->addFromString(basename($filePath), $contents);
17092                }
17093            }
17094
17095            $zip->close();
17096
17097            if (! file_exists($zipPath)) {
17098                return response(['message' => 'KO', 'error' => 'ZIP file creation failed'], 500);
17099            }
17100
17101            $content = file_get_contents($zipPath);
17102
17103            unlink($zipPath);
17104
17105            return response($content, 200, [
17106                'Content-Type' => 'application/zip',
17107                'Content-Disposition' => 'attachment; filename="'.$zipName.'"',
17108            ]);
17109        } catch (\Exception $e) {
17110            /** @disregard P1014 */
17111            $e->exceptionCode = 'DOWNLOAD_S3_FILES_EXCEPTION';
17112            report($e);
17113
17114            return response(['message' => 'KO', 'error' => $e->getMessage()]);
17115        }
17116    }
17117
17118    /**
17119     * FIRE-976: Return budget status and amount by Gestiona internal_quote_id + Region.
17120     * If the quotation doesn't exist locally, syncs it from Gestiona first.
17121     */
17122    public function getQuotationStatusByInternalId(Request $request, $id): ResponseFactory|HttpResponse
17123    {
17124        try {
17125            $region = urldecode((string) $request->header('Region'));
17126            if ($region === 'Catalunya') {
17127                $region = 'Cataluña';
17128            }
17129
17130            $company = TblCompanies::where('region', $region)->first();
17131            if (! $company) {
17132                return response(['message' => 'KO', 'error' => 'Region not found'], 404);
17133            }
17134
17135            $companyId = $company->company_id;
17136
17137            $quotation = $this->findQuotationByInternalId($id, $companyId);
17138
17139            // Found locally — return Titan data
17140            if ($quotation) {
17141                $statusName = null;
17142                if ($quotation->budget_status_id) {
17143                    $status = TblBudgetStatus::where('budget_status_id', $quotation->budget_status_id)->first();
17144                    $statusName = $status?->name;
17145                }
17146
17147                return response([
17148                    'message' => 'OK',
17149                    'data' => [
17150                        'internal_quote_id' => $quotation->internal_quote_id,
17151                        'amount' => $quotation->amount,
17152                        'budget_status_id' => $quotation->budget_status_id,
17153                        'budget_status' => $statusName,
17154                    ],
17155                ]);
17156            }
17157
17158            // Not found locally — try syncing from Gestiona
17159            $presupuestosService = app(PresupuestosService::class);
17160            $syncResult = $presupuestosService->syncById($id, $region);
17161
17162            if (! empty($syncResult['success'])) {
17163                // Sync succeeded — return freshly created Titan data
17164                $quotation = $this->findQuotationByInternalId($id, $companyId);
17165                if ($quotation) {
17166                    $statusName = null;
17167                    if ($quotation->budget_status_id) {
17168                        $status = TblBudgetStatus::where('budget_status_id', $quotation->budget_status_id)->first();
17169                        $statusName = $status?->name;
17170                    }
17171
17172                    return response([
17173                        'message' => 'OK',
17174                        'data' => [
17175                            'internal_quote_id' => $quotation->internal_quote_id,
17176                            'amount' => $quotation->amount,
17177                            'budget_status_id' => $quotation->budget_status_id,
17178                            'budget_status' => $statusName,
17179                        ],
17180                    ]);
17181                }
17182            }
17183
17184            // Sync failed — try to return raw Gestiona data with normalized status
17185            $gestionaResult = $presupuestosService->fetchFromGestiona($id, $region);
17186
17187            if (! empty($gestionaResult['success'])) {
17188                return response([
17189                    'message' => 'OK',
17190                    'data' => $gestionaResult['data'],
17191                    'source' => 'gestiona',
17192                ]);
17193            }
17194
17195            return response(['message' => 'KO', 'error' => 'Quotation not found'], 404);
17196        } catch (\Exception $e) {
17197            report(AppException::fromException($e, 'GET_QUOTATION_STATUS_BY_INTERNAL_ID_EXCEPTION'));
17198
17199            return response(['message' => 'KO', 'error' => $e->getMessage()], 500);
17200        }
17201    }
17202
17203    /**
17204     * FIRE-976: Find a quotation by internal_quote_id + company_id, with 18/22 fallback.
17205     */
17206    private function findQuotationByInternalId($id, int $companyId)
17207    {
17208        // FIRE-1476: CLM (22) merged into Madrid — single-company lookup.
17209        return TblQuotations::where('internal_quote_id', $id)
17210            ->where('company_id', $companyId)
17211            ->first();
17212    }
17213}