Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 976
0.00% covered (danger)
0.00%
0 / 45
CRAP
0.00% covered (danger)
0.00%
0 / 1
Notifications
0.00% covered (danger)
0.00%
0 / 976
0.00% covered (danger)
0.00%
0 / 45
32220
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 list_notifications
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 update_notifications
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 send_follow_up_notification
0.00% covered (danger)
0.00%
0 / 151
0.00% covered (danger)
0.00%
0 / 1
272
 send_request
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 send_g3w_warning
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 send_request_notification
0.00% covered (danger)
0.00%
0 / 137
0.00% covered (danger)
0.00%
0 / 1
272
 get_cc_bcc
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 delete_notifications
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 list_notification_logs
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 delete_notification_logs
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 get_cc_g3w
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_g3w
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_g3w
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_g3w
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 get_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 send_executive
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 send_executive_report
0.00% covered (danger)
0.00%
0 / 186
0.00% covered (danger)
0.00%
0 / 1
240
 get_executive_reports
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 1
30
 currency
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 update_notification_settings
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_notification_settings
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 send_report_logs
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
12
 get_emails_acceptance_notifications
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 create_to_email_acceptance
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 delete_to_email_acceptance
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_to_email_acceptance
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 create_cc_email_acceptance
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 delete_cc_email_acceptance
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_email_acceptance
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 list_last_follow_up_date
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 update_last_follow_up_date_working_days
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 update_last_follow_up_date
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
30
 delete_last_follow_up_date
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblNotifications;
6use App\Models\TblCompanies;
7use App\Models\TblCompanyUsers;
8use App\Models\TblUsers;
9use App\Models\TblCcBccNotifications;
10use App\Models\TblNotificationLogs;
11use App\Models\TblCcBccRequestNotifications;
12use App\Models\TblCcG3WEmailReminders;
13use App\Models\TblCcBccExecutiveNotifications;
14use App\Models\TblNotificationSettings;
15use App\Models\TblToAcceptanceNotifications;
16use App\Models\TblCcAcceptanceNotifications;
17use App\Models\TblLastFollowUpDate;
18use Illuminate\Http\Request;
19use Illuminate\Support\Facades\DB;
20use Illuminate\Support\Facades\App;
21use Illuminate\Support\Facades\Storage;
22use Illuminate\Support\Facades\Log;
23use Illuminate\Support\Facades\Artisan;
24use SendGrid\Mail\Mail;
25
26class Notifications extends Controller
27{
28    public function __construct(){
29        $this->locale = @getallheaders()['Locale-ID'];
30        $this->userId = @getallheaders()['User-ID'];
31        $this->region = @getallheaders()['Region'];
32        
33        App::setLocale($this->locale);
34
35        $this->companyIds = array();
36
37        if($this->region != null && $this->region != "" && $this->region != "All"){
38            $this->region = urldecode($this->region);
39
40            $query = "SELECT 
41                        b.company_id
42                    FROM 
43                        tbl_company_users a 
44                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
45                    WHERE 
46                        a.user_id = {$this->userId}
47                        AND b.region = '{$this->region}'";
48            
49            $this->companyIds = DB::select($query);
50
51            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
52        }else{
53            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
54        }
55        
56        $this->companyId = implode(',', $this->companyIds);
57    }
58
59    function list_notifications(Request $request){
60
61        try {
62            
63            $data = $request->all();
64            $userId = addslashes($data['user_id']);
65
66            $query = "SELECT
67                        notification_id,
68                        user_id,
69                        REPLACE(content, '<br>', '') content,
70                        link,
71                        is_open,
72                        created_by,
73                        created_at,
74                        updated_by,
75                        updated_at,
76                        CASE
77                            WHEN TIMESTAMPDIFF(SECOND, created_at, NOW()) < 60 THEN
78                                CASE
79                                    WHEN TIMESTAMPDIFF(SECOND, created_at, NOW()) = 1 THEN '1 second ago'
80                                    ELSE CONCAT(TIMESTAMPDIFF(SECOND, created_at, NOW()), ' seconds ago')
81                                END
82                            WHEN TIMESTAMPDIFF(MINUTE, created_at, NOW()) < 60 THEN
83                                CASE
84                                    WHEN TIMESTAMPDIFF(MINUTE, created_at, NOW()) = 1 THEN '1 minute ago'
85                                    ELSE CONCAT(TIMESTAMPDIFF(MINUTE, created_at, NOW()), ' minutes ago')
86                                END
87                            WHEN TIMESTAMPDIFF(HOUR, created_at, NOW()) < 24 THEN
88                                CASE
89                                    WHEN TIMESTAMPDIFF(HOUR, created_at, NOW()) = 1 THEN '1 hour ago'
90                                    ELSE CONCAT(TIMESTAMPDIFF(HOUR, created_at, NOW()), ' hours ago')
91                                END
92                            WHEN TIMESTAMPDIFF(DAY, created_at, NOW()) < 7 THEN
93                                CASE
94                                    WHEN TIMESTAMPDIFF(DAY, created_at, NOW()) = 1 THEN '1 day ago'
95                                    ELSE CONCAT(TIMESTAMPDIFF(DAY, created_at, NOW()), ' days ago')
96                                END
97                            WHEN TIMESTAMPDIFF(WEEK, created_at, NOW()) < 4 THEN
98                                CASE
99                                    WHEN TIMESTAMPDIFF(WEEK, created_at, NOW()) = 1 THEN '1 week ago'
100                                    ELSE CONCAT(TIMESTAMPDIFF(WEEK, created_at, NOW()), ' weeks ago')
101                                END
102                            WHEN TIMESTAMPDIFF(MONTH, created_at, NOW()) < 12 THEN
103                                CASE
104                                    WHEN TIMESTAMPDIFF(MONTH, created_at, NOW()) = 1 THEN '1 month ago'
105                                    ELSE CONCAT(TIMESTAMPDIFF(MONTH, created_at, NOW()), ' months ago')
106                                END
107                            ELSE
108                                CASE
109                                    WHEN TIMESTAMPDIFF(YEAR, created_at, NOW()) = 1 THEN '1 year ago'
110                                    ELSE CONCAT(TIMESTAMPDIFF(YEAR, created_at, NOW()), ' years ago')
111                                END
112                        END AS formatted_created_at
113                    FROM
114                        tbl_notifications
115                    WHERE user_id = {$userId}
116                    ORDER BY
117                        created_at DESC";
118
119            $result = DB::select($query);
120
121            $totalOpenNotification = 0;
122            foreach ($result as $item) {
123                if($item->is_open > 0){
124                    $totalOpenNotification++;
125                }
126            }
127            
128            return response([
129                'message' => 'OK', 
130                'data' => $result,
131                'total' => $totalOpenNotification
132            ]);
133
134        } catch (\Exception $e) {
135            return response(['message' => 'KO', 'error' => $e->getMessage()]);
136        }
137
138
139    }
140
141    function update_notifications(Request $request, $notificationId){
142
143        try {
144            
145            $data = $request->all();
146
147            if($notificationId == 999999999){
148                TblNotifications::where('user_id', $data['user_id'])->update(array(
149                    'is_open' => null
150                ));   
151            }else{
152                TblNotifications::where('notification_id', $notificationId)->update(array(
153                    'is_open' => null,
154                    'updated_at' => date('Y-m-d H:i:s'),
155                    'updated_by' => $data['updated_by']
156                ));
157            }
158
159            $r = new Request([
160                'user_id' => $data['user_id']
161            ]);
162
163            $result = $this->list_notifications($r);
164            
165            return $result;
166
167        } catch (\Exception $e) {
168            return response(['message' => 'KO', 'error' => $e->getMessage()]);
169        }
170    }
171
172    function send_follow_up_notification($userId = null){
173
174        try {
175
176            if($userId != null){
177                $this->userId = $userId;
178                $this->locale = 'es';
179                App::setLocale($this->locale);
180            }
181
182            $users = TblUsers::get();
183            $body = "";
184            $allTotalFollowUps = 0;
185            $totalOrders = 0;
186            $totalCompanies = 0;
187            foreach ($users as $user) {
188                $userCompanies = TblCompanyUsers::where('user_id', $user->id)->get();
189
190                $body .= __('language.send_follow_up_notification.body_hello');
191                $body = str_replace('{{username}}', $user->name, $body);
192                
193                $body .= __('language.send_follow_up_notification.body_message');
194                
195                $hasFollowUp = false;
196                $companyCcIds = array();
197                foreach ($userCompanies as $userCompany) {
198                    
199                    $companyId = $userCompany->company_id;
200                    $company = TblCompanies::where('company_id', $companyId)->first();
201
202                    if($company->is_send_follow_up > 0){
203                        $toEmail = $user->email;
204        
205                        $query = "SELECT 
206                                    id,
207                                    quote_id,
208                                    amount,
209                                    DATE_FORMAT(last_follow_up_date, '%d/%m/%Y') last_follow_up_date,
210                                    commercial 
211                                FROM 
212                                    tbl_quotations 
213                                WHERE 
214                                    last_follow_up_date < NOW() 
215                                    AND email IS NOT NULL 
216                                    AND email <> ''
217                                    AND NOT EXISTS (
218                                    SELECT 
219                                        1 
220                                    FROM 
221                                        tbl_blocked_domains bd 
222                                    WHERE 
223                                        email LIKE CONCAT('%', bd.domain, '%') 
224                                        AND bd.company_id = company_id
225                                    )
226                                    AND last_follow_up_date IS NOT NULL
227                                    AND reason_for_not_following_up_id IS NULL
228                                    AND last_follow_up_date > 0
229                                    AND last_follow_up_date < NOW()
230                                    AND total_sent < 3
231                                    AND for_add = 0
232                                    AND company_id = {$companyId}
233                                    AND commercial IS NOT NULL 
234                                    AND commercial = '{$user->name}'
235                                    AND budget_status_id = 2
236                                ORDER BY last_follow_up_date ASC, CAST(amount AS DOUBLE) DESC";
237    
238                        $result = DB::select($query);
239    
240                        $totalFolloUps = count($result);
241    
242                        if($totalFolloUps > 0){
243                            $allTotalFollowUps = $allTotalFollowUps + $totalFolloUps;
244                            array_push($companyCcIds, $companyId);
245
246                            $hasFollowUp = true;
247                            $body .= __('language.send_follow_up_notification.body_company_message');
248                            $body = str_replace('{{total}}', $totalFolloUps, $body);
249                            $body = str_replace('{{company}}', $company->name, $body);
250    
251                            $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Enviado&last_follow_up_date=1&company_id={$companyId}";
252                            $body = str_replace('{{click}}', $clickhRef, $body);
253    
254                            $ul = "<ul>";
255    
256                            $list = "";
257                            $totalAmount = 0;
258                            for ($i = 0; $i < $totalFolloUps; $i++) { 
259                                $li = __('language.send_follow_up_notification.body_due');
260    
261                                $id = $result[$i]->id;
262                                $date = $result[$i]->last_follow_up_date;
263                                $quoteId = $result[$i]->quote_id;
264                                $totalAmount = $totalAmount + $result[$i]->amount;
265                                $amount = $this->currency($result[$i]->amount, 1);
266    
267                                $url = env('URL') . "orders/{$id}?company_id={$companyId}";
268                                $href = "<a href='{$url}'>{$quoteId}</a>";
269    
270                                $li = str_replace('{{quote_id}}', $href, $li);
271                                $li = str_replace('{{amount}}', $amount, $li);
272                                $list .= str_replace('{{date}}', $date, $li);
273                            }
274                            $ul .= $list;
275                            $ul .= "</ul>";
276    
277                            $totalAmount = $this->currency($totalAmount, 1);
278                            $body = str_replace('{{amount}}', $totalAmount, $body);
279    
280                            $content = $body . $ul;
281    
282                            $body .= $ul;
283
284                        }else{
285                            continue;
286                        }
287                    }else{
288                        continue;
289                    }
290                }
291                
292                if($hasFollowUp){
293
294                    $body = str_replace('{{totalOrders}}', $allTotalFollowUps, $body);
295                    $body = str_replace('{{totalCompanies}}', count($companyCcIds), $body);
296
297                    $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Enviado&last_follow_up_date=1&company_id=0";
298                    $body = str_replace('{{clickAll}}', $clickhRef, $body);
299
300                    $imgpathS = \File::get(public_path('sendfollowups.png'));
301                    $img = "<br><img src='cid:sendfollowups' />";
302                    $body .= $img;
303
304                    $imgpath = \File::get(public_path('fireservicetitan.png'));
305                    $body .= "<br><p>Fire Service Titan</p>";
306                    $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
307                    
308                    $html = '<!DOCTYPE html>';
309                    $html .= '<html>';
310                    $html .= '<head>';
311                    $html .= '<meta charset="UTF-8">';
312                    $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
313                    $html .= '</head>';
314                    $html .= '<body>';
315                    $html .= $body;
316                    $html .= '</body>';
317                    $html .= '</html>';
318
319                    $dateNow = date_create(date('Y-m-d'));
320                    $dateNow = date_format($dateNow,"d/m/Y");
321
322                    $subject = __('language.send_follow_up_notification.subject');
323                    $subject = str_replace('{{dateNow}}', $dateNow, $subject);
324
325                    if($toEmail != null){
326                        $email = new \SendGrid\Mail\Mail(); 
327                        $sentBy = 'System';
328
329                        $email->setFrom('fire@fire.es', 'Fire Service Titan');
330                        $email->setSubject($subject);
331
332                        $userAdmin = TblUsers::where('id', $this->userId)->first();
333                        $sentBy = $userAdmin->name;
334
335                        if(env('SENDGRID_STAGING')){
336                            $toEmail = $userAdmin->email;
337                            $sentBy = $userAdmin->name;
338                            $user->id = $this->userId;
339                        }else{
340                            $companyCcIds = array_values(array_unique($companyCcIds));
341                            $ccBcc = TblCcBccNotifications::whereIn('company_id', $companyCcIds)->get();                            
342
343                            $inCc = array();
344
345                            if(count($ccBcc) > 0){
346                                foreach ($ccBcc as $data) {
347                                    if($data->email != $toEmail && !in_array($data->email, $inCc)){
348                                        $email->addCc($data->email);
349                                        array_push($inCc, $data->email);
350                                    }
351                                }
352                            }
353                        }
354
355                        $email->addTo($toEmail);
356                        $email->addContent("text/html", $html);
357
358                        $email->addAttachment(
359                            $imgpath,
360                            "image/png",
361                            "fireservicetitan.png",
362                            "inline",
363                            "fireservicetitan"
364                        );
365
366                        $email->addAttachment(
367                            $imgpathS,
368                            "image/png",
369                            "sendfollowups.png",
370                            "inline",
371                            "sendfollowups"
372                        );
373
374                        $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
375
376                        $response = $sendgrid->send($email);
377                        if ($response->statusCode() == 202) {
378                            Log::channel('email_log')->info('ID: '. $toEmail .' - TO FOLLOW UP EMAIL NOTIFICATION SENT');
379                            
380                            TblNotifications::create(
381                                array(
382                                    'user_id' => $user->id,
383                                    'content' => $content,
384                                    'is_open' => 1,
385                                    'created_by' => 'System',
386                                )
387                            );
388
389                            TblNotificationLogs::create(
390                                array(
391                                    'commercial' => $user->name,
392                                    'total_follow_ups' => $allTotalFollowUps,
393                                    'created_by' => $sentBy
394                                )
395                            );
396                            
397                        } else {
398                            $error = true;
399                            Log::channel('email_log')->error('ID: '. $toEmail .' - ' . $response->body());
400                        }
401
402                        $body = "";
403                        $content = "";
404                    }
405                }
406
407                $hasFollowUp = false;
408                $body = "";
409                $content = "";
410                $allTotalFollowUps = 0;
411            }
412
413            return response([
414                'message' => 'OK'
415            ]);
416
417        } catch (\Exception $e) {
418            return response(['message' => 'KO', 'error' => $e->getMessage()]);
419        }
420    }
421
422    function send_request($companyId){
423
424        try {
425
426            $companyId = addslashes($companyId);
427
428            $user = array('commercial');
429            
430            foreach ($user as $col) {
431                $this->send_request_notification($companyId, $col);
432            }
433
434            return response([
435                'message' => 'OK'
436            ]);
437            
438        } catch (\Exception $e) {
439            return response(['message' => 'KO', 'error' => $e->getMessage()]);
440        }
441
442    }
443
444    function send_g3w_warning($companyId){
445
446        try {
447
448            $companyId = addslashes($companyId);
449            
450            $userAdmin = TblUsers::where('id', $this->userId)->first();
451
452            if(env('SENDGRID_STAGING')){                
453                Artisan::call('send:g3w-email-reminders', [
454                    'sent_by' => $userAdmin->name,
455                    'email' => $userAdmin->email,
456                    'company_id' => $companyId
457                ]);
458            }else{
459                Artisan::call('send:g3w-email-reminders', [
460                    'sent_by' => $userAdmin->name,
461                    'email' => null,
462                    'company_id' => $companyId
463                ]);
464            }
465            
466            $output = Artisan::output();
467        
468            return response([
469                'message' => 'OK'
470            ]);
471
472        } catch (\Exception $e) {
473            return response(['message' => 'KO', 'error' => $e->getMessage()]);
474        }
475
476    }
477
478    function send_request_notification($userId = null){
479
480        try {
481
482            if($userId != null){
483                $this->userId = $userId;
484                $this->locale = 'es';
485                App::setLocale($this->locale);
486            }
487
488            $users = TblUsers::get();
489            $body = "";
490            $allTotalRequest = 0;
491            
492            foreach ($users as $user) {
493                $userCompanies = TblCompanyUsers::where('user_id', $user->id)->get();
494
495                $body .= __('language.send_request_notification.body_hello');
496                $body = str_replace('{{username}}', $user->name, $body);
497                $body .= __('language.send_request_notification.body_intro');
498
499                $hasRequest = false;
500                $companyCcIds = array();
501                foreach ($userCompanies as $userCompany) {
502                    
503                    $companyId = $userCompany->company_id;
504                    $company = TblCompanies::where('company_id', $companyId)->first();
505
506                    if($company->is_send_request > 0){
507                        $toEmail = $user->email;
508        
509                        $query = "SELECT 
510                                    id,
511                                    quote_id,
512                                    DATE_FORMAT(created_at, '%d/%m/%Y') created_at,
513                                    commercial,
514                                    created_by
515                                FROM 
516                                    tbl_quotations 
517                                WHERE 
518                                    company_id = {$companyId}
519                                    AND budget_status_id IN (6)
520                                    AND commercial = '{$user->name}'";
521    
522                        $result = DB::select($query);
523    
524                        $totalRequest = count($result);
525    
526                        if($totalRequest > 0){
527                            $allTotalRequest = $allTotalRequest + $totalRequest;
528                            $hasRequest = true;
529                            array_push($companyCcIds, $companyId);
530
531                            $body .= __('language.send_request_notification.body_message_commercial');
532                            $body = str_replace('{{total}}', $totalRequest, $body);
533                            $body = str_replace('{{company}}', $company->name, $body);
534    
535                            $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Solicitud&company_id={$companyId}";
536                            $body = str_replace('{{click}}', $clickhRef, $body);
537    
538                            $ul = "<ul>";
539    
540                            $list = "";
541                            $totalAmount = 0;
542                            for ($i = 0; $i < $totalRequest; $i++) { 
543                                $li = __('language.send_request_notification.body_due');
544
545                                $id = $result[$i]->id;
546                                $date = $result[$i]->created_at;
547                                $quoteId = $result[$i]->quote_id;
548
549                                $url = env('URL') . "orders/{$id}?company_id={$companyId}";
550                                $href = "<a href='{$url}'>{$quoteId}</a>";
551
552                                $li = str_replace('{{quote_id}}', $href, $li);
553                                $list .= str_replace('{{date}}', $date, $li);
554                            }
555                            $ul .= $list;
556                            $ul .= "</ul>";
557    
558                            $totalAmount = $this->currency($totalAmount, 1);
559                            $body = str_replace('{{amount}}', $totalAmount, $body);
560    
561                            $content = $body . $ul;
562    
563                            $body .= $ul;
564
565                        }else{
566                            continue;
567                        }
568                    }else{
569                        continue;
570                    }
571                }
572
573                if($hasRequest){
574
575                    $body = str_replace('{{totalOrders}}', $allTotalRequest, $body);
576                    $body = str_replace('{{totalCompanies}}', count($companyCcIds), $body);
577
578                    $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Solicitud&company_id=0";
579                    $body = str_replace('{{clickAll}}', $clickhRef, $body);
580
581                    $imgpath = \File::get(public_path('fireservicetitan.png'));
582
583                    $body .= "<br><p>Fire Service Titan</p>";
584                    $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
585                    
586                    $html = '<!DOCTYPE html>';
587                    $html .= '<html>';
588                    $html .= '<head>';
589                    $html .= '<meta charset="UTF-8">';
590                    $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
591                    $html .= '</head>';
592                    $html .= '<body>';
593                    $html .= $body;
594                    $html .= '</body>';
595                    $html .= '</html>';
596
597                    $dateNow = date_create(date('Y-m-d'));
598                    $dateNow = date_format($dateNow,"d/m/Y");
599
600                    $subject = __('language.send_request_notification.subject');
601                    $subject = str_replace('{{dateNow}}', $dateNow, $subject);
602                    $subject = str_replace('{{total}}', $allTotalRequest, $subject);
603
604                    if($toEmail != null){
605                        $email = new \SendGrid\Mail\Mail(); 
606                        $sentBy = 'System';
607
608                        $email->setFrom('fire@fire.es', 'Fire Service Titan');
609                        $email->setSubject($subject);
610
611                        $userAdmin = TblUsers::where('id', $this->userId)->first();
612                        $sentBy = $userAdmin->name;
613
614                        if(env('SENDGRID_STAGING')){
615                            $toEmail = $userAdmin->email;
616                            $sentBy = $userAdmin->name;
617                            $user->id = $this->userId;
618                        }else{
619                            $companyCcIds = array_values(array_unique($companyCcIds));
620                            $ccBcc = TblCcBccRequestNotifications::whereIn('company_id', $companyCcIds)->get();
621
622                            $inCc = array();
623
624                            if(count($ccBcc) > 0){
625                                foreach ($ccBcc as $data) {
626                                    if($data->email != $toEmail && !in_array($data->email, $inCc)){
627                                        $email->addCc($data->email);
628                                        array_push($inCc, $data->email);
629                                    }
630                                }
631                            }
632                        }
633
634                        $email->addTo($toEmail);
635                        $email->addContent("text/html", $html);
636
637                        $email->addAttachment(
638                            $imgpath,
639                            "image/png",
640                            "fireservicetitan.png",
641                            "inline",
642                            "fireservicetitan"
643                        );
644
645                        $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
646
647                        $response = $sendgrid->send($email);
648                        if ($response->statusCode() == 202) {
649                            Log::channel('email_log')->info('ID:' . $toEmail .' - REQUEST EMAIL NOTIFICATION SENT');
650                            
651                            TblNotifications::create(
652                                array(
653                                    'user_id' => $user->id,
654                                    'content' => $content,
655                                    'is_open' => 1,
656                                    'created_by' => 'System',
657                                )
658                            );
659
660                            TblNotificationLogs::create(
661                                array(
662                                    'company_id' => $companyId,
663                                    'commercial' => $user->name,
664                                    'total_request' => $allTotalRequest,
665                                    'created_by' => $sentBy
666                                )
667                            );
668                            
669                        } else {
670                            $error = true;
671                            Log::channel('email_log')->error('ID:' . $toEmail .' - ' . $response->body());
672                        }
673
674                        $body = "";
675                        $content = "";
676                    }
677                }
678
679                $hasRequest = false;
680                $body = "";
681                $content = "";
682                $allTotalRequest = 0;
683            }
684
685            return response([
686                'message' => 'OK'
687            ]);
688
689
690        } catch (\Exception $e) {
691            return response(['message' => 'KO', 'error' => $e->getMessage()]);
692        }
693    }
694
695    function get_cc_bcc($id){
696
697        try {
698            
699            $companyId = addslashes($id);
700
701            $result = TblCcBccNotifications::where('company_id', $companyId)->get();
702
703            return response(['message' => 'OK', 'data' => $result]);
704
705        } catch (\Exception $e) {
706            return response(['message' => 'KO', 'error' => $e->getMessage()]);
707        }
708    }
709
710    function delete_cc_bcc($id){
711
712        try {
713            
714            $id = addslashes($id);
715
716            TblCcBccNotifications::where('id', $id)->delete();
717
718            return response(['message' => 'OK']);
719
720        } catch (\Exception $e) {
721            return response(['message' => 'KO', 'error' => $e->getMessage()]);
722        }
723    }
724
725    function update_cc_bcc(Request $request, $id){
726
727        try {
728
729            $data = $request->all();
730            $id = addslashes($id);
731
732            $x = $this->isEmailValid($data['email']);
733
734            if($x){
735                $result = TblCcBccNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
736
737                if($result > 0){
738                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
739                }else{
740                    $data['updated_at'] = date('Y-m-d H:i:s');
741                    TblCcBccNotifications::where('id', $id)->update($data);
742                }
743            }else{
744                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
745            }
746
747            return response(['message' => 'OK']);
748
749        } catch (\Exception $e) {
750            return response(['message' => 'KO', 'error' => $e->getMessage()]);
751        }
752    }
753
754    function create_cc_bcc(Request $request){
755
756        try {
757            
758            $data = $request->all();
759
760            $x = $this->isEmailValid($data['email']);
761
762            if($x){
763                $result = TblCcBccNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
764
765                if($result > 0){
766                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
767                }else{
768                    TblCcBccNotifications::create($data);
769                }
770            }else{
771                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
772            }
773            
774            return response(['message' => 'OK']);
775
776        } catch (\Exception $e) {
777            return response(['message' => 'KO', 'error' => $e->getMessage()]);
778        }
779    }
780
781    function isEmailValid($email) {
782        // Regular expression pattern for email validation
783        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
784        
785        // Check if the email matches the pattern
786        if (preg_match($pattern, $email)) {
787            return true; // Valid email
788        } else {
789            return false; // Invalid email
790        }
791    }
792
793    function delete_notifications($userId){
794
795        try {
796            
797            $userId = addslashes($userId);
798
799            TblNotifications::where('user_id', $userId)->delete();
800
801            $r = new Request([
802                'user_id' => $userId
803            ]);
804
805            $result = $this->list_notifications($r);
806            
807            return $result;
808
809        } catch (\Exception $e) {
810            return response(['message' => 'KO', 'error' => $e->getMessage()]);
811        }
812
813    }
814
815    function list_notification_logs($companyId){
816
817        try {
818            
819            $companyId = addslashes($companyId);
820
821            $where = " company_id IN ({$this->companyId}";
822            
823            $query = "SELECT
824                        id,
825                        commercial,
826                        total_follow_ups,
827                        total_request,
828                        total_executive_report,
829                        total_g3w_warning,
830                        CASE 
831                            WHEN total_follow_ups IS NOT NULL THEN total_follow_ups
832                            WHEN total_request IS NOT NULL THEN total_request
833                            WHEN total_executive_report IS NOT NULL THEN total_executive_report
834                            WHEN total_g3w_warning IS NOT NULL THEN total_g3w_warning
835                        END totals,
836                        created_by,
837                        created_at
838                    FROM `tbl_notification_logs` 
839                    WHERE {$where}
840                    OR company_id IS NULL
841                    ORDER BY created_at DESC";
842
843            $result = DB::select($query);
844            
845            return response(['message' => 'OK', 'data' => $result]);
846
847        } catch (\Exception $e) {
848            return response(['message' => 'KO', 'error' => $e->getMessage()]);
849        }
850
851    }
852
853    function delete_notification_logs($companyId){
854
855        try {
856            
857            $companyId = addslashes($companyId);
858
859            TblNotificationLogs::where('company_id', $companyId)->orWhere('company_id', null)->delete();
860            
861            return response(['message' => 'OK']);
862
863        } catch (\Exception $e) {
864            return response(['message' => 'KO', 'error' => $e->getMessage()]);
865        }
866    }
867
868    function get_cc_g3w($id){
869
870        try {
871            
872            $companyId = addslashes($id);
873
874            $result = TblCcG3WEmailReminders::where('company_id', $companyId)->get();
875
876            return response(['message' => 'OK', 'data' => $result]);
877
878        } catch (\Exception $e) {
879            return response(['message' => 'KO', 'error' => $e->getMessage()]);
880        }
881    }
882
883    function delete_cc_g3w($id){
884
885        try {
886            
887            $id = addslashes($id);
888
889            TblCcG3WEmailReminders::where('id', $id)->delete();
890
891            return response(['message' => 'OK']);
892
893        } catch (\Exception $e) {
894            return response(['message' => 'KO', 'error' => $e->getMessage()]);
895        }
896    }
897
898    function update_cc_g3w(Request $request, $id){
899
900        try {
901
902            $data = $request->all();
903            $id = addslashes($id);
904
905            $x = $this->isEmailValid($data['email']);
906
907            if($x){
908                $result = TblCcG3WEmailReminders::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
909
910                if($result > 0){
911                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
912                }else{
913                    $data['updated_at'] = date('Y-m-d H:i:s');
914                    TblCcG3WEmailReminders::where('id', $id)->update($data);
915                }
916            }else{
917                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
918            }
919
920            return response(['message' => 'OK']);
921
922        } catch (\Exception $e) {
923            return response(['message' => 'KO', 'error' => $e->getMessage()]);
924        }
925    }
926
927    function create_cc_g3w(Request $request){
928
929        try {
930            
931            $data = $request->all();
932
933            $x = $this->isEmailValid($data['email']);
934
935            if($x){
936                $result = TblCcG3WEmailReminders::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
937
938                if($result > 0){
939                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
940                }else{
941                    TblCcG3WEmailReminders::create($data);
942                }
943            }else{
944                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
945            }
946            
947            return response(['message' => 'OK']);
948
949        } catch (\Exception $e) {
950            return response(['message' => 'KO', 'error' => $e->getMessage()]);
951        }
952    }
953
954    function get_cc_bcc_request($id){
955
956        try {
957            
958            $companyId = addslashes($id);
959
960            $result = TblCcBccRequestNotifications::where('company_id', $companyId)->get();
961
962            return response(['message' => 'OK', 'data' => $result]);
963
964        } catch (\Exception $e) {
965            return response(['message' => 'KO', 'error' => $e->getMessage()]);
966        }
967    }
968
969    function delete_cc_bcc_request($id){
970
971        try {
972            
973            $id = addslashes($id);
974
975            TblCcBccRequestNotifications::where('id', $id)->delete();
976
977            return response(['message' => 'OK']);
978
979        } catch (\Exception $e) {
980            return response(['message' => 'KO', 'error' => $e->getMessage()]);
981        }
982    }
983
984    function update_cc_bcc_request(Request $request, $id){
985
986        try {
987
988            $data = $request->all();
989            $id = addslashes($id);
990
991            $x = $this->isEmailValid($data['email']);
992
993            if($x){
994                $result = TblCcBccRequestNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
995
996                if($result > 0){
997                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
998                }else{
999                    $data['updated_at'] = date('Y-m-d H:i:s');
1000                    TblCcBccRequestNotifications::where('id', $id)->update($data);
1001                }
1002            }else{
1003                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1004            }
1005
1006            return response(['message' => 'OK']);
1007
1008        } catch (\Exception $e) {
1009            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1010        }
1011    }
1012
1013    function create_cc_bcc_request(Request $request){
1014
1015        try {
1016            
1017            $data = $request->all();
1018
1019            $x = $this->isEmailValid($data['email']);
1020
1021            if($x){
1022                $result = TblCcBccRequestNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1023
1024                if($result > 0){
1025                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1026                }else{
1027                    TblCcBccRequestNotifications::create($data);
1028                }
1029            }else{
1030                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1031            }
1032            
1033            return response(['message' => 'OK']);
1034
1035        } catch (\Exception $e) {
1036            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1037        }
1038    }
1039
1040    function send_executive(Request $request){
1041
1042        try {
1043            
1044            $data = $request->all();
1045
1046            $executiveEmails = TblCcBccExecutiveNotifications::get();
1047
1048            if(isset($data['User-ID'])){
1049                $this->userId = $data['User-ID'];
1050            }
1051            
1052            if(isset($data['self']) && $data['self'] == 1){
1053                $user = TblUsers::where('id', $this->userId)->first();
1054                $this->send_executive_report($user->email, $user->name, $user->id, $data['processed_by']);   
1055            }else{
1056                foreach ($executiveEmails as $item) {
1057                    $user = TblUsers::where('email', $item->email)->first();
1058                    if($user){                    
1059                        $this->send_executive_report($item->email, $user->name, $user->id, $data['processed_by']);   
1060                    }
1061                }
1062            }
1063
1064            return response([
1065                'message' => 'OK'
1066            ]);
1067            
1068        } catch (\Exception $e) {
1069            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1070        }
1071
1072    }
1073
1074    function send_executive_report($toEmail, $toName, $toUserId, $sentBy = 'System'){
1075
1076        try{
1077
1078            $result = TblNotificationSettings::where('id', 1)->first();
1079
1080            $currentYear = date('Y');
1081            $previousYear = date('Y', strtotime('-1 year', strtotime(date('Y-m-d'))));
1082
1083            if($toEmail != null && $result->is_auto_send_executive == 1){
1084
1085                if(env('SENDGRID_STAGING')){
1086                    $user = TblUsers::where('id', $this->userId)->first();
1087                    $toEmail = $user->email;
1088                }
1089                
1090                $result = (object) $this->get_executive_reports();
1091
1092                $weekNumber = $result->weekNumber;
1093                $monday = $result->monday;
1094                $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1095                $totalAmountApproved = $result->totalAmountApproved;
1096                $totalAmount = $result->totalAmount;
1097                $dividendMaintenance = $result->dividendMaintenance;
1098                $dividendCorrectives = $result->dividendCorrectives;
1099                $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1100                $approvalRate = $result->approvalRate;
1101    
1102                $subject = "FST executive report week $weekNumber (starting on monday - $monday) - Automated";
1103
1104                $body = "<p>Hello {$toName},</p>";
1105
1106                $url = env('URL') . "analytics?week={$weekNumber}";
1107                $body .= "<p>Find a summary of the commercial activity across <b>Grupo Fire</b> (see the <a href='{$url}'>report on FST here</a>) for week {$weekNumber} (starting on monday - {$monday})</p>";
1108                $body .= "<p><b>{$totalBudgets} budget(s)</b> ({$percentageMoreThanLastWeek}% compared to last week) created for a total of <b>{$totalAmount}</b> ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) - ";
1109                $body .= "this week across all companies - <i>we have an approval rate of <b>{$approvalRate}%</b> for the month <b>(<span style='color: blue;'>{$totalAmountApproved} approved</span>)</b></i></p>";
1110    
1111                $query = "SELECT 
1112                            a.company_id, 
1113                            a.name,
1114                            (
1115                            SELECT 
1116                                COUNT(created_at) 
1117                            FROM 
1118                                tbl_quotations 
1119                            WHERE 
1120                                company_id = a.company_id
1121                                AND for_add = 0 
1122                                AND created_at IS NOT NULL 
1123                                AND issue_date IS NOT NULL
1124                                AND YEAR(created_at) = YEAR(issue_date)
1125                            ) total 
1126                        FROM 
1127                            tbl_companies a 
1128                            WHERE is_send_executive = 1
1129                            -- AND company_id IN ({$this->companyId})
1130                        ORDER BY 
1131                            3 DESC
1132                        ";
1133                
1134                $companies = DB::select($query);
1135                
1136                $li = array();
1137    
1138                foreach ($companies as $company) {
1139                    $result = (object) $this->get_executive_reports($company->company_id);
1140                    $result->name = $company->name;
1141                    array_push($li, $result);
1142                }
1143    
1144                usort($li, function ($a, $b) {
1145                    return $b->totalBudgets - $a->totalBudgets;
1146                });
1147                
1148                $body .= "<ul>";
1149                foreach ($li as $result) {
1150                    $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1151                    $totalAmount = $result->totalAmount;
1152                    $dividendMaintenance = $result->dividendMaintenance;
1153                    $dividendCorrectives = $result->dividendCorrectives;
1154                    $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1155                    $approvalRate = $result->approvalRate;
1156    
1157                    $body .= "<li>{$totalBudgets} order(s) in “<b>{$result->name}</b>” ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) for total of <b>{$totalAmount}</b></li>";
1158                }
1159                $body .= "</ul>";
1160    
1161                
1162                $result = (object) $this->get_executive_reports(null, true, $currentYear);
1163                
1164                $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1165                $totalAmountApproved = $result->totalAmountApproved;
1166                $totalAmount = $result->totalAmount;
1167                $dividendMaintenance = $result->dividendMaintenance;
1168                $dividendCorrectives = $result->dividendCorrectives;
1169                $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1170                $approvalRate = $result->approvalRate;
1171                $totalDaysFromStartOfYear = date('z') + 1;
1172                $totalDaysOfCurrentYear = date('z', mktime(0, 0, 0, 12, 31,date('Y'))) + 1;
1173                $expected = 0;
1174
1175                $totalGoalForTheYear = 0;
1176                if($result->totalGoalForTheYear > 0){
1177                    $totalGoalForTheYear = number_format(($result->totalBudgets / $result->totalGoalForTheYear) * 100, 0, ',', '.');
1178                    $expected = number_format(($totalDaysFromStartOfYear / $totalDaysOfCurrentYear) * 100, 0, ',', '.');
1179                }
1180    
1181                $body .= "<p><b>For {$currentYear}</b> as a whole, <b><span style='color: blue;'>{$totalBudgets}</span> budgets (<span style='color: blue;'>{$totalGoalForTheYear}% of the goal for the year accomplished</span> vs {$expected}% expected) for a total of <span style='color: blue;'>{$totalAmount}</span></b> ({$dividendMaintenance}% “Mantenimientos”, {$dividendCorrectives}% “Correctivos”) ";
1182                $body .= "were created across all companies - <i>we have an approval rate of <b>{$approvalRate}%</b> for the year <b>(<span style='color: blue;'>{$totalAmountApproved} approved</span>)</b></i></p>";                            
1183
1184                $query = "SELECT 
1185                            a.company_id, 
1186                            a.name,
1187                            (
1188                            SELECT 
1189                                COUNT(created_at) 
1190                            FROM 
1191                                tbl_quotations 
1192                            WHERE 
1193                                company_id = a.company_id
1194                                AND for_add != 1
1195                                AND amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1196                                AND created_at IS NOT NULL 
1197                                AND YEAR(created_at) = {$currentYear}                                
1198                            ) total 
1199                        FROM 
1200                            tbl_companies a 
1201                            WHERE is_send_executive = 1
1202                            -- AND company_id IN ({$this->companyId})
1203                        ORDER BY 
1204                            3 DESC
1205                        ";
1206                
1207                $companies = DB::select($query);
1208
1209                $li = array();
1210    
1211                foreach ($companies as $company) {
1212                    $result = (object) $this->get_executive_reports($company->company_id, true, $currentYear);
1213                    $result->name = $company->name;
1214                    array_push($li, $result);
1215                }
1216    
1217                usort($li, function ($a, $b) {
1218                    return $b->totalBudgets - $a->totalBudgets;
1219                });
1220
1221                $body .= "<ul>";
1222                foreach ($li as $result) {
1223                    
1224                    $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1225                    $totalAmountApproved = $result->totalAmountApproved;
1226                    $totalAmount = $result->totalAmount;
1227                    $dividendMaintenance = $result->dividendMaintenance;
1228                    $dividendCorrectives = $result->dividendCorrectives;
1229                    $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1230                    $approvalRate = $result->approvalRate;
1231                    $goalForTheYear = number_format($result->totalGoalForTheYear, 0, ',', '.');
1232                    $totalDaysFromStartOfYear = date('z') + 1;
1233                    $totalDaysOfCurrentYear = date('z', mktime(0, 0, 0, 12, 31,date('Y'))) + 1;
1234                    $expected = 0;
1235
1236                    $totalGoalForTheYear = 0;
1237                    $style = "style='color: green'";
1238                    if($result->totalGoalForTheYear > 0){
1239                        $totalGoalForTheYear = number_format(($result->totalBudgets / $result->totalGoalForTheYear) * 100, 0, ',', '.');
1240                        $expected = number_format(($totalDaysFromStartOfYear / $totalDaysOfCurrentYear) * 100, 0, ',', '.');
1241
1242                        if($totalGoalForTheYear < $expected){
1243                            $style = "style='color: red'";
1244                        }
1245                    }
1246    
1247                    $body .= "<li>{$totalBudgets} order(s) in “<b>{$result->name}</b>” ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) for total of <b>{$totalAmount}</b></li>";
1248                    $body .= "<ul>";
1249                    $body .= "<li><i><b>{$goalForTheYear} goal</b> for the year. <b {$style}>{$totalGoalForTheYear}%</b> accomplished to date vs <b>{$expected}% expected</b></i></li>";
1250                    $body .= "<li><i>Approval rate of <b>{$approvalRate}%</b> (<span style='color: blue;'>{$totalAmountApproved} approved</span>)</i></li>";
1251                    $body .= "</ul>";
1252                }
1253
1254                $body .= "</ul>";
1255    
1256                
1257                $result = (object) $this->get_executive_reports(null, true, $previousYear);
1258                
1259                $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1260                $totalAmount = $result->totalAmount;
1261                $dividendMaintenance = $result->dividendMaintenance;
1262                $dividendCorrectives = $result->dividendCorrectives;
1263                $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1264                $approvalRate = $result->approvalRate;
1265    
1266                $body .= "<p>For your reference, in <b>{$previousYear}</b>, <b>{$totalBudgets} budgets for a total of {$totalAmount}</b> ({$dividendMaintenance}% “Mantenimientos”, {$dividendCorrectives}% “Correctivos”) ";
1267                $body .= "were created across all companies - <i>we have an approval rate of <b>{$approvalRate}%</b> for the year</i></p>";                            
1268
1269                $query = "SELECT 
1270                            a.company_id, 
1271                            a.name,
1272                            (
1273                            SELECT 
1274                                COUNT(created_at) 
1275                            FROM 
1276                                tbl_quotations 
1277                            WHERE 
1278                                company_id = a.company_id
1279                                AND for_add != 1
1280                                AND amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1281                                AND created_at IS NOT NULL 
1282                                AND YEAR(created_at) = {$currentYear}
1283                            ) total 
1284                        FROM 
1285                            tbl_companies a 
1286                            WHERE is_send_executive = 1
1287                            -- AND company_id IN ({$this->companyId})
1288                        ORDER BY 
1289                            3 DESC
1290                        ";
1291                
1292                $companies = DB::select($query);
1293
1294                $li = array();
1295    
1296                foreach ($companies as $company) {
1297                    $result = (object) $this->get_executive_reports($company->company_id, true, $previousYear);
1298                    $result->name = $company->name;
1299                    array_push($li, $result);
1300                }
1301    
1302                usort($li, function ($a, $b) {
1303                    return $b->totalBudgets - $a->totalBudgets;
1304                });
1305
1306                $body .= "<ul>";
1307
1308                foreach ($li as $result) {
1309                    $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1310                    $totalAmount = $result->totalAmount;
1311                    $dividendMaintenance = $result->dividendMaintenance;
1312                    $dividendCorrectives = $result->dividendCorrectives;
1313                    $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1314                    $approvalRate = $result->approvalRate;
1315    
1316                    $body .= "<li>{$totalBudgets} order(s) in “<b>{$result->name}</b>” ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) for total of <b>{$totalAmount}</b> <i> - approval rate of <b>{$approvalRate}%</b></i></li>";
1317                }
1318
1319                $body .= "</ul><br><br>";
1320    
1321                $imgpath = \File::get(public_path('fireservicetitan.png'));
1322                
1323                $content = $body;                                
1324
1325                $body .= "<br><p>Fire Service Titan</p>";
1326                $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
1327                
1328                $html = '<!DOCTYPE html>';
1329                $html .= '<html>';
1330                $html .= '<head>';
1331                $html .= '<meta charset="UTF-8">';
1332                $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1333                $html .= '</head>';
1334                $html .= '<body>';
1335                $html .= $body;
1336                $html .= '</body>';
1337                $html .= '</html>';
1338    
1339                $email = new \SendGrid\Mail\Mail(); 
1340    
1341                $email->setFrom('fire@fire.es', 'Fire Service Titan');
1342                $email->setSubject($subject);
1343    
1344                $email->addTo($toEmail);
1345                $email->addContent("text/html", $html);
1346    
1347                $email->addAttachment(
1348                    $imgpath,
1349                    "image/png",
1350                    "fireservicetitan.png",
1351                    "inline",
1352                    "fireservicetitan"
1353                );
1354    
1355                $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
1356    
1357                $response = $sendgrid->send($email);
1358                if ($response->statusCode() == 202) {
1359                    Log::channel('email_log')->info('ID:' . $toEmail .' - EXECUTIVE REPORT EMAIL NOTIFICATION SENT');
1360                    
1361                    TblNotifications::create(
1362                        array(
1363                            'user_id' => $toUserId,
1364                            'content' => $content,
1365                            'is_open' => 1,
1366                            'created_by' => 'System',
1367                        )
1368                    );
1369
1370                    TblNotificationLogs::create(
1371                        array(
1372                            'commercial' => $toName,
1373                            'total_executive_report' => 1,
1374                            'created_by' => $sentBy
1375                        )
1376                    );
1377                } else {
1378                    $error = true;
1379                    Log::channel('email_log')->error('ID:' . $toEmail .' - ' . $response->body());
1380                }
1381    
1382                $body = "";
1383    
1384                return response([
1385                    'message' => 'OK'
1386                ]);
1387            }
1388            
1389        } catch (\Exception $e) {
1390            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1391        }
1392
1393    }
1394
1395    function get_executive_reports($companyId = null, $wholeYear = false, $year = null){
1396
1397        $where = "";
1398        $whereYear = "";
1399        $whereMonth = "DATE_FORMAT(q.created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ";
1400
1401        if($companyId != null){
1402            $where = " AND company_id = {$companyId} ";
1403        }
1404
1405        $now = date('Y-m-d');
1406        $weekNumber = date('W', strtotime($now));
1407        $monday = date('F j, Y', strtotime($now . " - " . (date('N', strtotime($now)) - 1) . " days"));
1408
1409        $mondayDate = date('Y-m-d', strtotime($now . " - " . (date('N', strtotime($now)) - 1) . " days"));
1410        $sundayDate = date('Y-m-d', strtotime($mondayDate . " + 6 days"));
1411
1412        $mondayLastWeekDate = date('Y-m-d', strtotime($mondayDate . " - 1 week"));
1413        $sundayLastWeekDate = date('Y-m-d', strtotime($mondayLastWeekDate . " + 6 days"));
1414
1415        $whereAccMonth = "";
1416        if($wholeYear == false){
1417            $whereYear = " AND DATE_FORMAT(q.created_at, '%Y-%m-%d') BETWEEN '{$mondayDate}' AND '{$sundayDate}";
1418            $whereMonth = " AND DATE_FORMAT(q.created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ";
1419            $whereAccMonth = " AND DATE_FORMAT(q.acceptance_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ";
1420        }else{
1421            $whereYear = " AND YEAR(q.created_at) = {$year} ";
1422            $whereMonth = " AND YEAR(q.created_at) = {$year} ";
1423            $whereAccMonth = " AND YEAR(q.acceptance_date) = {$year} ";
1424        }
1425
1426        $query = "SELECT 
1427                    COUNT(q.created_at) totalBudgets, 
1428                    SUM(q.amount) totalAmount, 
1429                    COALESCE(
1430                        SUM(CASE WHEN bt.budget_type_group_id = 3 THEN 1 END)
1431                        , 0
1432                    ) / 
1433                    COUNT(q.created_at) * 100 dividendMaintenance, 
1434                    COALESCE(
1435                        SUM(CASE WHEN bt.budget_type_group_id = 5 THEN 1 END)
1436                        , 0
1437                    ) / 
1438                    COUNT(q.created_at) * 100 dividendCorrectives 
1439                FROM 
1440                    tbl_quotations q 
1441                    LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id 
1442                WHERE 
1443                    q.for_add != 1
1444                    AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1445                    AND q.created_at IS NOT NULL 
1446                    AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})
1447                    AND q.budget_type_id != 7
1448                    AND YEAR(q.created_at) = YEAR(q.issue_date)
1449                    {$whereYear}
1450                    ";
1451
1452        $result = DB::select($query)[0];
1453
1454        $totalBudgets = $result->totalBudgets;
1455        $totalAmount = $this->currency($result->totalAmount, 1, 0);
1456        $totalAmountC = $result->totalAmount;
1457        $dividendMaintenance = number_format($result->dividendMaintenance, 0);
1458        $dividendCorrectives = number_format($result->dividendCorrectives, 0);
1459
1460        $query = "SELECT 
1461                        COUNT(q.created_at) totalBudgetLastWeek 
1462                    FROM tbl_quotations q WHERE 
1463                    DATE_FORMAT(q.created_at, '%Y-%m-%d') BETWEEN '{$mondayLastWeekDate}
1464                    AND '{$sundayLastWeekDate}
1465                    AND q.for_add != 1
1466                    AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1467                    AND q.created_at IS NOT NULL 
1468                    AND q.budget_type_id != 7
1469                    AND q.budget_type_id IS NOT NULL 
1470                    AND YEAR(q.created_at) = YEAR(q.issue_date)
1471                    AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})";
1472        
1473        $result = DB::select($query)[0];
1474
1475        $percentageMoreThanLastWeek = 0;
1476
1477        if($result->totalBudgetLastWeek > 0){
1478            $percentageMoreThanLastWeek = number_format($totalBudgets / $result->totalBudgetLastWeek * 100, 2);
1479        }
1480
1481        $query = "SELECT 
1482                    SUM(q.amount) totalAmount
1483                FROM tbl_quotations q WHERE 
1484                q.for_add != 1
1485                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1486                AND q.created_at IS NOT NULL 
1487                AND q.budget_type_id != 7
1488                AND q.budget_type_id IS NOT NULL 
1489                AND YEAR(q.created_at) = YEAR(q.issue_date)
1490                AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})
1491                {$whereMonth}";
1492        
1493        $result = DB::select($query)[0];
1494
1495        $totalAmountCC = $result->totalAmount;
1496
1497        $query = "SELECT 
1498                COUNT(CASE WHEN q.created_at IS NOT NULL THEN 1 END) totalBudgets,
1499                COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND q.budget_status_id = 3 THEN 1 END) totalAcceptance,
1500                SUM(CASE WHEN q.acceptance_date IS NOT NULL AND q.budget_status_id = 3 THEN q.amount END) totalAmountApproved
1501            FROM tbl_quotations q WHERE 
1502            q.for_add != 1
1503            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1504            AND q.created_at IS NOT NULL 
1505            AND q.budget_type_id != 7
1506            AND q.budget_type_id IS NOT NULL 
1507            AND YEAR(q.created_at) = YEAR(q.issue_date)
1508            AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})
1509            {$whereAccMonth}";
1510
1511        $result = DB::select($query)[0];
1512
1513        $approvalRate = 0; 
1514        $totalAmountApproved = $result->totalAmountApproved;
1515        if($totalAmountCC > 0){
1516            $approvalRate = number_format(($totalAmountApproved / $totalAmountCC) * 100, 0);
1517        }
1518
1519        $query = "SELECT SUM(goal_for_the_year) goalForTheYear FROM tbl_companies WHERE is_send_executive = 1 {$where}";
1520        $result = DB::select($query)[0];
1521
1522        return array(
1523            'weekNumber' => $weekNumber,
1524            'monday' => $monday,
1525            'totalBudgets' => $totalBudgets,
1526            'totalAmount' => $totalAmount,
1527            'totalAmountApproved' => $this->currency($totalAmountApproved, 1, 0),
1528            'dividendMaintenance' => $dividendMaintenance,
1529            'dividendCorrectives' => $dividendCorrectives,
1530            'percentageMoreThanLastWeek' => $percentageMoreThanLastWeek,
1531            'approvalRate' => $approvalRate,
1532            'totalGoalForTheYear' => $result->goalForTheYear
1533        );
1534
1535    }
1536
1537    function currency($amount, $withEuro = null, $n = 2){
1538
1539        if($withEuro != null){
1540            $withEuro = ' €';
1541        }
1542
1543        return number_format($amount, $n, ',', '.') . $withEuro;
1544    }
1545
1546    function get_cc_bcc_executive(){
1547
1548        try {
1549
1550            $result = TblCcBccExecutiveNotifications::get();
1551
1552            return response(['message' => 'OK', 'data' => $result]);
1553
1554        } catch (\Exception $e) {
1555            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1556        }
1557    }
1558
1559    function delete_cc_bcc_executive($id){
1560
1561        try {
1562            
1563            $id = addslashes($id);
1564
1565            TblCcBccExecutiveNotifications::where('id', $id)->delete();
1566
1567            return response(['message' => 'OK']);
1568
1569        } catch (\Exception $e) {
1570            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1571        }
1572    }
1573
1574    function update_cc_bcc_executive(Request $request, $id){
1575
1576        try {
1577
1578            $data = $request->all();
1579            $id = addslashes($id);
1580
1581            $x = $this->isEmailValid($data['email']);
1582
1583            if($x){
1584                $result = TblCcBccExecutiveNotifications::where('email', strtolower($data['email']))->count();
1585
1586                if($result > 0){
1587                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1588                }else{
1589                    $data['updated_at'] = date('Y-m-d H:i:s');
1590                    TblCcBccExecutiveNotifications::where('id', $id)->update($data);
1591                }
1592            }else{
1593                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1594            }
1595
1596            return response(['message' => 'OK']);
1597
1598        } catch (\Exception $e) {
1599            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1600        }
1601    }
1602
1603    function create_cc_bcc_executive(Request $request){
1604
1605        try {
1606            
1607            $data = $request->all();
1608
1609            $x = $this->isEmailValid($data['email']);
1610
1611            if($x){
1612                $result = TblCcBccExecutiveNotifications::where('email', strtolower($data['email']))->count();
1613
1614                if($result > 0){
1615                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1616                }else{
1617                    TblCcBccExecutiveNotifications::create($data);
1618                }
1619            }else{
1620                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1621            }
1622            
1623            return response(['message' => 'OK']);
1624
1625        } catch (\Exception $e) {
1626            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1627        }
1628    }
1629
1630    function update_notification_settings(Request $request){
1631
1632        try {
1633            
1634            $data = $request->all();
1635
1636            $data['updated_at'] = date('Y-m-d H:i:s');
1637            TblNotificationSettings::where('id', 1)->update($data);
1638
1639            return response(['message' => 'OK']);
1640
1641        } catch (\Exception $e) {
1642            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1643        }
1644
1645    }
1646
1647    function get_notification_settings(){
1648
1649        try {
1650            
1651            $result = TblNotificationSettings::where('id', 1)->first();
1652
1653            return response(['message' => 'OK', 'data' => $result]);
1654
1655        } catch (\Exception $e) {
1656            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1657        }
1658    }
1659
1660    function send_report_logs(Request $request){
1661
1662        try {
1663
1664            $data = $request->all();
1665
1666            $toEmail = env('SENDGRID_TO_EMAIL');
1667
1668            $imgpath = \File::get('fireservicetitan.png');
1669
1670            $body = $data['logs'];
1671
1672            $body .= "<br><br><p>Fire Service Titan</p>";
1673            $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
1674            
1675            $html = '<!DOCTYPE html>';
1676            $html .= '<html>';
1677            $html .= '<head>';
1678            $html .= '<meta charset="UTF-8">';
1679            $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1680            $html .= '</head>';
1681            $html .= '<body>';
1682            $html .= $body;
1683            $html .= '</body>';
1684            $html .= '</html>';
1685
1686            $email = new \SendGrid\Mail\Mail(); 
1687            $subject = "FST Error report " . date('Y-m-d H:i:s');
1688    
1689            $email->setFrom('fire@fire.es', 'Fire Service Titan');
1690            $email->setSubject($subject);
1691
1692            $email->addTo($toEmail);
1693            $email->addContent("text/html", $html);
1694
1695            $email->addAttachment(
1696                $imgpath,
1697                "image/png",
1698                "fireservicetitan.png",
1699                "inline",
1700                "fireservicetitan"
1701            );
1702
1703            $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
1704
1705            $response = $sendgrid->send($email);
1706            if ($response->statusCode() == 202) {
1707                Log::channel('email_log')->info('ID:' . $toEmail .' - REPORT LOG EMAIL SENT');
1708            }
1709
1710            return response(['message' => 'OK']);
1711
1712        } catch (\Exception $e) {
1713            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1714        }
1715    }
1716
1717    function get_emails_acceptance_notifications($companyId){
1718
1719        try {
1720
1721            $companyId = addslashes($companyId);
1722
1723            $cc = TblCcAcceptanceNotifications::where('company_id', $companyId)->get();
1724            $to = TblToAcceptanceNotifications::where('company_id', $companyId)->get();
1725
1726            return response(['message' => 'OK', 'cc' => $cc, 'to' => $to]);
1727
1728        } catch (\Exception $e) {
1729            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1730        }
1731    }
1732
1733    function create_to_email_acceptance(Request $request){
1734
1735        try {
1736            
1737            $data = $request->all();
1738
1739            $x = $this->isEmailValid($data['email']);
1740
1741            if($x){
1742                $result = TblToAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1743
1744                if($result > 0){
1745                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1746                }else{
1747                    TblToAcceptanceNotifications::create($data);
1748                }
1749            }else{
1750                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1751            }
1752            
1753            return response(['message' => 'OK']);
1754
1755        } catch (\Exception $e) {
1756            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1757        }
1758    }
1759
1760    function delete_to_email_acceptance($id){
1761
1762        try {
1763            
1764            $id = addslashes($id);
1765
1766            TblToAcceptanceNotifications::where('id', $id)->delete();
1767
1768            return response(['message' => 'OK']);
1769
1770        } catch (\Exception $e) {
1771            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1772        }
1773    }
1774
1775    function update_to_email_acceptance(Request $request, $id){
1776
1777        try {
1778
1779            $data = $request->all();
1780            $id = addslashes($id);
1781
1782            $x = $this->isEmailValid($data['email']);
1783
1784            if($x){
1785                $to = TblToAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1786                $cc = TblCcAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1787
1788                if($to > 0 || $cc > 0){
1789                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1790                }else{
1791                    $data['updated_at'] = date('Y-m-d H:i:s');
1792                    TblToAcceptanceNotifications::where('id', $id)->update($data);
1793                }
1794            }else{
1795                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1796            }
1797
1798            return response(['message' => 'OK']);
1799
1800        } catch (\Exception $e) {
1801            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1802        }
1803    }
1804
1805    function create_cc_email_acceptance(Request $request){
1806
1807        try {
1808            
1809            $data = $request->all();
1810
1811            $x = $this->isEmailValid($data['email']);
1812
1813            if($x){
1814                $result = TblCcAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1815
1816                if($result > 0){
1817                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1818                }else{
1819                    TblCcAcceptanceNotifications::create($data);
1820                }
1821            }else{
1822                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1823            }
1824            
1825            return response(['message' => 'OK']);
1826
1827        } catch (\Exception $e) {
1828            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1829        }
1830    }
1831
1832    function delete_cc_email_acceptance($id){
1833
1834        try {
1835            
1836            $id = addslashes($id);
1837
1838            TblCcAcceptanceNotifications::where('id', $id)->delete();
1839
1840            return response(['message' => 'OK']);
1841
1842        } catch (\Exception $e) {
1843            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1844        }
1845    }
1846
1847    function update_cc_email_acceptance(Request $request, $id){
1848
1849        try {
1850
1851            $data = $request->all();
1852            $id = addslashes($id);
1853
1854            $x = $this->isEmailValid($data['email']);
1855
1856            if($x){
1857                $cc = TblCcAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1858                $to = TblToAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1859
1860                if($cc > 0 || $to > 0){
1861                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1862                }else{
1863                    $data['updated_at'] = date('Y-m-d H:i:s');
1864                    TblCcAcceptanceNotifications::where('id', $id)->update($data);
1865                }
1866            }else{
1867                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1868            }
1869
1870            return response(['message' => 'OK']);
1871
1872        } catch (\Exception $e) {
1873            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1874        }
1875    }
1876
1877    function list_last_follow_up_date($companyId){
1878
1879        try {
1880            
1881            $companyId = addslashes($companyId);
1882
1883            $result = TblLastFollowUpDate::where('company_id', $companyId)->orderBy('row_id', 'ASC')->get();
1884
1885            $data = array();
1886
1887            for ($i = 0; $i < count($result); $i++) { 
1888                $data[$result[$i]->row_id]['row_id'] = $result[$i]->row_id;
1889                $data[$result[$i]->row_id]['last_follow_up_date'] = $result[$i]->last_follow_up_date;
1890                if($result[$i]->budget_type_id != null){
1891                    $data[$result[$i]->row_id]['budget_types'][] = $result[$i]->budget_type_id;
1892                }
1893            }
1894
1895            return response(['message' => 'OK', 'data' => array_values($data)]);
1896
1897        } catch (\Exception $e) {
1898            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1899        }
1900
1901    }
1902
1903    function update_last_follow_up_date_working_days(Request $request){
1904
1905        try {
1906            
1907            $data = $request->all();
1908            $companyId = addslashes($data['company_id']);
1909            $rowId = addslashes($data['row_id']);
1910
1911            unset($data['company_id']);
1912            unset($data['row_id']);
1913
1914            $data['updated_at'] = date('Y-m-d H:i:s');
1915
1916            TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->update($data);
1917
1918            return $this->list_last_follow_up_date($companyId);
1919
1920        } catch (\Exception $e) {
1921            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1922        }
1923
1924    }
1925
1926
1927    function update_last_follow_up_date(Request $request){
1928
1929        try {
1930            
1931            $data = $request->all();
1932            $companyId = addslashes($data['company_id']);
1933            $rowId = addslashes($data['row_id']);
1934            unset($data['company_id']);
1935            unset($data['row_id']);
1936
1937            $previousData = TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->first();
1938
1939            $lastBudgetTypeId = end($data['budget_type_id']);
1940            $lastFollowUpDate = TblLastFollowUpDate::where('company_id', $companyId)->where('budget_type_id', $lastBudgetTypeId)->first();
1941
1942            TblLastFollowUpDate::where('company_id', $companyId)->whereIn('budget_type_id', $data['budget_type_id'])->delete();
1943            TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->delete();
1944
1945            foreach ($data['budget_type_id'] as $budgetTypeId) {
1946                TblLastFollowUpDate::create(
1947                    array(
1948                        'company_id' => $companyId,
1949                        'row_id' => $rowId,                        
1950                        'budget_type_id' => $budgetTypeId,                        
1951                        'last_follow_up_date' => $previousData->last_follow_up_date,
1952                        'updated_by' => $data['updated_by'],
1953                        'updated_at' => date('Y-m-d H:i:s')
1954                    )
1955                );
1956            }
1957
1958            if($lastFollowUpDate != null){
1959                if($lastFollowUpDate->budget_type_id != null){
1960                    TblLastFollowUpDate::create(
1961                        array(
1962                            'company_id' => $companyId,
1963                            'row_id' => $lastFollowUpDate->row_id,
1964                            'budget_type_id' => null,
1965                            'last_follow_up_date' => $lastFollowUpDate->last_follow_up_date,
1966                            'created_by' => $data['updated_by']
1967                        )
1968                    );
1969                }
1970            }
1971
1972            return $this->list_last_follow_up_date($companyId);
1973
1974        } catch (\Exception $e) {
1975            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1976        }
1977
1978    }
1979
1980    function delete_last_follow_up_date(Request $request){
1981
1982        try {
1983            
1984            $data = $request->all();
1985            $companyId = addslashes($data['company_id']);
1986            $rowId = addslashes($data['row_id']);
1987            unset($data['company_id']);
1988            unset($data['row_id']);
1989
1990            $count = TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->count();
1991
1992            if($count > 1){
1993                TblLastFollowUpDate::where('company_id', $companyId)->where('budget_type_id', $data['budget_type_id'])->delete();
1994            }else{
1995                TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->update(array('budget_type_id' => null));
1996            }
1997
1998            return $this->list_last_follow_up_date($companyId);
1999
2000        } catch (\Exception $e) {
2001            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2002        }
2003
2004    }
2005}