Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 767
0.00% covered (danger)
0.00%
0 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Itv
0.00% covered (danger)
0.00%
0 / 767
0.00% covered (danger)
0.00%
0 / 16
38220
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 list_itv
0.00% covered (danger)
0.00%
0 / 251
0.00% covered (danger)
0.00%
0 / 1
5700
 get_dates
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 update_itv
0.00% covered (danger)
0.00%
0 / 94
0.00% covered (danger)
0.00%
0 / 1
1332
 create_itv
0.00% covered (danger)
0.00%
0 / 75
0.00% covered (danger)
0.00%
0 / 1
870
 delete_itv
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 get_itv
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 human_filesize
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 get_itv_files
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 delete_itv_file
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 download_itv_file
0.00% covered (danger)
0.00%
0 / 10
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
 email_reminders
0.00% covered (danger)
0.00%
0 / 128
0.00% covered (danger)
0.00%
0 / 1
306
 email_reminders_mileage
0.00% covered (danger)
0.00%
0 / 90
0.00% covered (danger)
0.00%
0 / 1
56
 get_distincts
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
6
 get_all_users
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblCompanyUsers;
6use App\Models\TblItv;
7use App\Models\TblItvEmailLogs;
8use App\Models\TblItvFiles;
9use App\Models\TblUsers;
10use Illuminate\Http\Request;
11use Illuminate\Support\Facades\App;
12use Illuminate\Support\Facades\Cache;
13use Illuminate\Support\Facades\DB;
14use Illuminate\Support\Facades\Storage;
15
16class Itv extends Controller
17{
18    private $locale;
19
20    private $userId;
21
22    private $region;
23
24    private $companyIds;
25
26    private $companyId;
27
28    public function __construct()
29    {
30        $this->locale = @getallheaders()['Locale-ID'];
31        $this->userId = @getallheaders()['User-ID'];
32        $this->region = @getallheaders()['Region'];
33
34        App::setLocale($this->locale);
35
36        $this->companyIds = [];
37
38        if ($this->region != null && $this->region != '' && $this->region != 'All') {
39            $this->region = urldecode($this->region);
40
41            $query = 'SELECT 
42                        b.company_id
43                    FROM 
44                        tbl_company_users a 
45                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
46                    WHERE 
47                        a.user_id = ?
48                        AND b.region = ?';
49
50            $this->companyIds = DB::select($query, [intval($this->userId), $this->region]);
51
52            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
53        } else {
54            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
55        }
56
57        $this->companyId = implode(',', $this->companyIds);
58    }
59
60    public function list_itv(Request $request)
61    {
62
63        try {
64
65            $data = $request->all();
66            $companyId = intval($data['company_id']);
67            $userId = intval($data['user_id']);
68            $filter = $data['filterModel'];
69            $sort = $data['sortModel'];
70            $result = [];
71            $subquery = '';
72            $where = '';
73            $having = '';
74            $orderBy = '';
75            $start = intval($data['start']);
76            $end = intval($data['end']);
77            $totalRowCount = 0;
78            $withFilters = '';
79
80            $filterType = [
81                'contains' => "LIKE '%[value]%'",
82                'notContains' => "NOT LIKE '%[value]%'",
83                'equals' => "= '[value]'",
84                'notEqual' => "<> '[value]'",
85                'startsWith' => "LIKE '[value]%'",
86                'endsWith' => "LIKE '%[value]'",
87                'blank' => 'IS NULL',
88                'notBlank' => 'IS NOT NULL',
89                'lessThan' => '< [value]',
90                'lessThanOrEqual' => '<= [value]',
91                'greaterThan' => '> [value]',
92                'greaterThanOrEqual' => '>= [value]',
93                'inRange' => 'BETWEEN [value1] AND [value2]',
94            ];
95
96            if (isset($data['ids']) && count($data['ids']) > 0) {
97                $ids = implode(',', $data['ids']);
98                $where = " AND a.id IN ({$ids}";
99            }
100
101            if (isset($data['ids_not_in']) && count($data['ids_not_in']) > 0) {
102                $ids = implode(',', $data['ids_not_in']);
103                $where = " AND a.id NOT IN ({$ids}";
104            }
105
106            $matchScoreCol = '';
107            $matchScoreOrderBy = '';
108
109            if (isset($data['searchText']) && $data['searchText'] != null) {
110
111                $availableParameters = [
112                    'a.region',
113                    'b.name',
114                    'a.brand',
115                    'a.vehicle_type',
116                    'a.license_plate',
117                    'a.mileage',
118                    'a.last_itv_date',
119                    'a.next_itv_date',
120                    'a.mileage_threshold',
121                    'a.is_booked',
122                    'a.driver',
123                    'a.responsible_name',
124                    'a.responsible_email',
125                    'a.created_by',
126                    'a.created_at',
127                    'a.updated_by',
128                    'a.updated_at',
129                ];
130
131                $searchText = addslashes($data['searchText']);
132                $searchTextArray = explode(' ', $searchText);
133
134                $searchArray = [];
135                $splitSearchArray = [];
136                $matchScoreArray = [];
137                $sc = 1;
138                foreach ($availableParameters as $field) {
139                    if ($field == 'a.license_plate' || $field == 'a.created_at') {
140                        $sc = 3;
141                    } elseif ($field == 'a.last_itv_date') {
142                        $sc = 2;
143                    } else {
144                        $sc = 1;
145                    }
146
147                    $l = "{$field} LIKE '%{$searchText}%'";
148
149                    $d = "IFNULL((LENGTH(LOWER({$field})) - LENGTH(REPLACE(LOWER({$field}), LOWER('{$searchText}'), ''))) / LENGTH(LOWER('{$searchText}')), 0) * {$sc}";
150
151                    if (count($searchTextArray) > 1) {
152                        foreach ($searchTextArray as $word) {
153                            if (! is_numeric($word)) {
154                                $d .= " + IFNULL((LENGTH(LOWER({$field})) - LENGTH(REPLACE(LOWER({$field}), LOWER('{$word}'), ''))) / LENGTH(LOWER('{$word}')), 0) * {$sc}";
155                            }
156                        }
157                    }
158
159                    array_push($matchScoreArray, $d);
160
161                    if (is_numeric($searchText)) {
162                        array_push($searchArray, "({$l} OR {$field} = CAST('{$searchText}' AS UNSIGNED))");
163                    } else {
164                        array_push($searchArray, "({$l} OR DATE_FORMAT({$field}, '%d/%m/%Y') = DATE_FORMAT(STR_TO_DATE('{$searchText}', '%d/%m/%Y'), '%d/%m/%Y'))");
165                    }
166
167                    if (count($searchTextArray) > 1) {
168                        foreach ($searchTextArray as $word) {
169
170                            $l = "{$field} LIKE '%{$word}%'";
171
172                            if (is_numeric($word)) {
173                                array_push($splitSearchArray, "{$l} OR {$field} = CAST('{$word}' AS UNSIGNED)");
174                            } else {
175                                array_push($splitSearchArray, "{$l} OR DATE_FORMAT({$field}, '%d/%m/%Y') = DATE_FORMAT(STR_TO_DATE('{$word}', '%d/%m/%Y'), '%d/%m/%Y')");
176                            }
177                        }
178                    }
179
180                    $sc = 1;
181                }
182
183                if (count($splitSearchArray) > 0) {
184                    $splitSearchArray = implode(' OR ', $splitSearchArray);
185                    $splitSearchArray = " OR ({$splitSearchArray}";
186                } else {
187                    $splitSearchArray = '';
188                }
189
190                $searchArray = implode(' OR ', $searchArray);
191                $matchScoreArray = implode(',', $matchScoreArray);
192                $matchScoreCol = ", GREATEST({$matchScoreArray}) match_score";
193                $matchScoreOrderBy = 'match_score DESC,';
194                $where .= " AND ({$searchArray} {$splitSearchArray})";
195            }
196
197            if (count($sort) > 0) {
198                $field = $sort[0]['colId'];
199                $sortBy = $sort[0]['sort'];
200
201                if (strpos($field, 'translate') !== false) {
202                    $field = str_replace('_translate', '', $field);
203                } else {
204                    if ($field == 'company_name') {
205                        $field = 'b.name';
206                    }
207                }
208
209                if ($matchScoreOrderBy) {
210                    $matchScoreOrderBy = ', match_score DESC';
211                }
212
213                $orderBy = " ORDER BY {$field} {$sortBy} {$matchScoreOrderBy}";
214            } else {
215                $orderBy = " ORDER BY {$matchScoreOrderBy} a.id DESC";
216            }
217
218            foreach ($filter as $key => $data) {
219                if (strpos($key, 'translate') !== false) {
220
221                    $field = str_replace('_translate', '', $key);
222
223                    if ($field == 'created_at') {
224                        $field = 'a.created_at';
225                    } elseif ($field == 'updated_at') {
226                        $field = 'a.updated_at';
227                    } elseif ($field == 'last_itv_date') {
228                        $field = 'a.last_itv_date';
229                    } elseif ($field == 'next_itv_date') {
230                        $field = 'a.next_itv_date';
231                    }
232
233                    $whereDates = '';
234                    $z = 0;
235
236                    if (isset($data['filters']) && ! empty($data['filters'])) {
237                        foreach ($data['filters'] as $yearKey => $yearData) {
238                            $yearsMonths = [];
239                            $yearsWeeks = [];
240
241                            if ($z > 0) {
242                                $whereDates .= " OR (YEAR($field) = {$yearKey} ";
243                            } else {
244                                $whereDates .= " (YEAR($field) = {$yearKey} ";
245                            }
246
247                            for ($i = 0; $i < count($yearData['months']); $i++) {
248                                if ($yearData['months'][$i]['isChecked']) {
249                                    array_push($yearsMonths, $yearData['months'][$i]['value']);
250                                }
251                            }
252
253                            $yearsMonths = implode("','", $yearsMonths);
254                            $whereDates .= " AND (MONTH({$field}) IN ('{$yearsMonths}')";
255
256                            for ($i = 0; $i < count($yearData['weeks']); $i++) {
257                                if ($yearData['weeks'][$i]['isChecked']) {
258                                    array_push($yearsWeeks, $yearData['weeks'][$i]['value']);
259                                }
260                            }
261
262                            $yearsWeeks = implode("','", $yearsWeeks);
263                            if ($yearsWeeks != '') {
264                                $whereDates .= " OR WEEK({$field}) IN ('{$yearsWeeks}') ";
265                            }
266
267                            $whereDates .= ')) ';
268                            $z++;
269                        }
270                    }
271
272                    $whereDataUptoToday = '';
273                    if (isset($data['isDataUptoToday'])) {
274                        if ($data['isDataUptoToday']) {
275                            $whereDates = '';
276                            $whereDataUptoToday .= " AND {$field} < NOW() AND {$field} > 0 ";
277                        }
278                    }
279
280                    $whereBlanks = '';
281                    if (isset($data['isBlanks'])) {
282                        if ($data['isBlanks']) {
283                            $conj = 'OR';
284                            if ($whereDates == '') {
285                                $conj = '';
286                            }
287                            $whereBlanks .= " {$conj} {$field} IS NULL ";
288                        } else {
289                            $conj = 'AND';
290                            if ($whereDates == '') {
291                                $conj = '';
292                            }
293                            $whereBlanks .= " {$conj} {$field} IS NOT NULL ";
294                        }
295                    }
296
297                    $where .= " AND ({$whereDates} {$whereBlanks} {$whereDataUptoToday}";
298                } else {
299                    if ($data['filterType'] == 'number') {
300                        if (array_key_exists('operator', $data)) {
301                            if ($data['condition1']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
302                                $data['condition1']['filter'] = addslashes($data['condition1']['filter']);
303                                $data['condition2']['filter'] = addslashes($data['condition2']['filter']);
304
305                                if ($data['condition1']['type'] == 'inRange') {
306                                    $data['condition1']['filterTo'] = addslashes($data['condition1']['filterTo']);
307                                    $inRange = str_replace('[value1]', $data['condition1']['filter'], $filterType['inRange']);
308                                    $val1 = str_replace('[value2]', $data['condition1']['filterTo'], $inRange);
309                                } else {
310                                    $val1 = str_replace('[value]', $data['condition1']['filter'], $filterType[$data['condition1']['type']]);
311                                }
312
313                                if ($data['condition2']['type'] == 'inRange') {
314                                    $data['condition2']['filterTo'] = addslashes($data['condition2']['filterTo']);
315                                    $inRange = str_replace('[value1]', $data['condition2']['filter'], $filterType['inRange']);
316                                    $val2 = str_replace('[value2]', $data['condition2']['filterTo'], $inRange);
317                                } else {
318                                    $val2 = str_replace('[value]', $data['condition2']['filter'], $filterType[$data['condition2']['type']]);
319                                }
320
321                            } else {
322                                $val1 = $filterType[$data['condition1']['type']];
323                                $val2 = $filterType[$data['condition2']['type']];
324                            }
325
326                            $where .= " AND a.{$key} {$val1} {$data['operator']} a.{$key} {$val2} ";
327                        } else {
328                            if ($data['type'] != 'blank' && $data['type'] != 'notBlank') {
329                                $data['filter'] = addslashes($data['filter']);
330
331                                if ($data['type'] == 'inRange') {
332                                    $data['filterTo'] = addslashes($data['filterTo']);
333                                    $inRange = str_replace('[value1]', $data['filter'], $filterType['inRange']);
334                                    $val = str_replace('[value2]', $data['filterTo'], $inRange);
335                                } else {
336                                    $val = str_replace('[value]', $data['filter'], $filterType[$data['type']]);
337                                }
338                            } else {
339                                $val = $filterType[$data['type']];
340                            }
341
342                            $where .= " AND a.{$key} {$val} ";
343                        }
344                    }
345
346                    if ($data['filterType'] == 'text') {
347                        if (array_key_exists('operator', $data)) {
348                            $val1 = '';
349                            $val2 = '';
350
351                            if ($data['condition1']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
352                                $data['condition1']['filter'] = addslashes($data['condition1']['filter']);
353                                $val1 = str_replace('[value]', $data['condition1']['filter'], $filterType[$data['condition1']['type']]);
354                            }
355
356                            if ($data['condition2']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
357                                $data['condition2']['filter'] = addslashes($data['condition2']['filter']);
358                                $val2 = str_replace('[value]', $data['condition2']['filter'], $filterType[$data['condition2']['type']]);
359                            }
360
361                            $where .= " AND {$key} {$val1} {$data['operator']} {$key} {$val2} ";
362                        } else {
363                            if ($data['type'] != 'blank' && $data['type'] != 'notBlank') {
364                                $data['filter'] = addslashes($data['filter']);
365                                $val = str_replace('[value]', $data['filter'], $filterType[$data['type']]);
366                            } else {
367                                $val = $filterType[$data['type']];
368                            }
369
370                            $where .= " AND {$key} {$val} ";
371                        }
372                    }
373
374                    if ($data['filterType'] == 'set') {
375                        $statusName = $key;
376
377                        if ($key == 'updated_by') {
378                            $statusName = 'a.updated_by';
379                        } elseif ($key == 'created_by') {
380                            $statusName = 'a.created_by';
381                        } elseif ($key == 'company_name') {
382                            $statusName = 'b.name';
383                        } elseif ($key == 'region') {
384                            $statusName = 'a.region';
385                        } elseif ($key == 'is_booked') {
386                            $statusName = 'a.is_booked';
387                            if ($data['values']) {
388                                foreach ($data['values'] as $k => $v) {
389                                    if ($v == 'No') {
390                                        $data['values'][$k] = 0;
391                                    } elseif ($v == null) {
392                                        $data['values'][$k] = null;
393                                    } else {
394                                        $data['values'][$k] = 1;
395                                    }
396                                }
397                            }
398                        }
399
400                        $val = implode("','", $data['values']);
401
402                        if (in_array(null, $data['values'], true)) {
403                            $where .= " AND ({$statusName} IN ('{$val}') OR {$statusName} IS NULL) ";
404                        } else {
405                            $where .= " AND {$statusName} IN ('{$val}') ";
406                        }
407                    }
408                }
409            }
410
411            $offset = $start;
412            $limit = $end - $start;
413
414            $subquery = ",(SELECT can_write FROM tbl_company_users WHERE company_id = a.company_id AND user_id = {$userId}) can_write";
415
416            $query = "SELECT 
417                        a.id,
418                        a.region, 
419                        a.company_id,
420                        b.name company_name,
421                        a.registration_date,
422                        a.brand, 
423                        a.model,
424                        a.vehicle_type,
425                        a.license_plate,
426                        a.mileage,
427                        a.last_itv_date,
428                        a.next_itv_date,
429                        a.mileage_threshold,
430                        a.driver,
431                        a.responsible_name,
432                        a.responsible_email,
433                        a.created_by,
434                        a.created_at,
435                        a.updated_by,
436                        a.updated_at,
437                        a.is_due,
438                        a.is_due_appointment,
439                        CASE
440                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 0 THEN 0
441                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 1 THEN 1
442                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 15 THEN 15
443                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 30 THEN 30
444                        ELSE NULL
445                        END AS next_itv_date_due,
446                        CASE
447                            WHEN DATEDIFF(a.appointment_date, NOW()) <= 0 THEN 0
448                            WHEN DATEDIFF(a.appointment_date, NOW()) <= 1 THEN 1
449                            WHEN DATEDIFF(a.appointment_date, NOW()) <= 7 THEN 7
450                        ELSE NULL
451                        END AS appointment_date_due,
452                        a.comments,
453                        a.location,
454                        a.is_booked,
455                        a.appointment_time,
456                        a.appointment_date,
457                        DATE_FORMAT(a.registration_date, '%m/%Y') registration_date_translate,
458                        DATE_FORMAT(a.last_itv_date, '%d/%m/%Y') last_itv_date_translate,
459                        DATE_FORMAT(a.next_itv_date, '%m/%Y') next_itv_date_translate,
460                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
461                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate,
462                        DATE_FORMAT(a.appointment_date, '%d/%m/%Y') appointment_date_translate
463                        {$matchScoreCol}
464                        {$subquery}
465                    FROM 
466                        tbl_itv a 
467                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
468                    WHERE a.id > 0 {$where}
469                    GROUP BY a.id
470                    {$orderBy}
471                    LIMIT {$offset}{$limit}
472                    ";
473            // return $query;
474            $value = Cache::get(base64_encode($query));
475
476            if (! $value) {
477                $result = DB::select($query);
478
479                Cache::put(base64_encode($query), $result, 600);
480            } else {
481                $result = $value;
482            }
483
484            $totalQuery = "SELECT 
485                            COUNT(a.id) totalRowCount
486                        FROM 
487                            tbl_itv a 
488                            LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
489                        WHERE a.id > 0
490                        {$where}";
491
492            $value = Cache::get(base64_encode($totalQuery));
493
494            if (! $value) {
495                $countQuery = DB::select($totalQuery);
496
497                Cache::put(base64_encode($totalQuery), $countQuery, 600);
498            } else {
499                $countQuery = $value;
500            }
501
502            return response([
503                'message' => 'OK',
504                'data' => $result,
505                'totalRowCount' => $countQuery[0]->totalRowCount,
506            ]);
507
508        } catch (\Exception $e) {
509            return response(['message' => 'KO', 'error' => $e->getMessage()]);
510        }
511
512    }
513
514    public function get_dates()
515    {
516
517        try {
518
519            $query = "SELECT
520                        DATE_FORMAT(a.last_itv_date, '%d/%m/%Y') last_itv_date_translate,
521                        DATE_FORMAT(a.next_itv_date, '%d/%m/%Y') next_itv_date_translate,
522                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
523                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate
524                    FROM tbl_itv a";
525
526            $result = DB::select($query);
527
528            return response([
529                'message' => 'OK',
530                'data' => $result,
531            ]);
532
533        } catch (\Exception $e) {
534            return response(['message' => 'KO', 'error' => $e->getMessage()]);
535        }
536
537    }
538
539    public function update_itv(Request $request, $id)
540    {
541
542        try {
543
544            $id = intval($id);
545            $data = $request->all();
546
547            $files = $request->file('files');
548            unset($data['files']);
549
550            $itv = TblItv::where('id', $id)->first();
551
552            $isSendItv = 0;
553            $daysDifference = 0;
554            $duration = 0;
555            $isBooked = $data['is_booked'];
556
557            if ($data['is_booked'] == 0 || $data['is_booked'] == null) {
558                if (isset($data['next_itv_date'])) {
559                    $incommingDate = strtotime($data['next_itv_date']);
560                    $currentDate = strtotime(date('Y-m-d'));
561                    $secondsDifference = abs($incommingDate - $currentDate);
562                    $daysDifference = floor($secondsDifference / (60 * 60 * 24));
563
564                    $duration = 99999999;
565
566                    if ($daysDifference >= 15 && $daysDifference <= 30) {
567                        $duration = 30;
568                    } elseif ($daysDifference > 1 && $daysDifference <= 15) {
569                        $duration = 15;
570                    } elseif ($daysDifference == 1) {
571                        $duration = 1;
572                    }
573
574                    if ($daysDifference <= 30) {
575                        if ($itv->is_due != $duration) {
576                            $isSendItv = 1;
577                        }
578                    } else {
579                        $data['is_due'] = null;
580                    }
581                }
582            } elseif ($data['is_booked'] == 1) {
583                if (isset($data['appointment_date'])) {
584                    $incommingDate = strtotime($data['appointment_date']);
585                    $currentDate = strtotime(date('Y-m-d'));
586                    $secondsDifference = abs($incommingDate - $currentDate);
587                    $daysDifference = floor($secondsDifference / (60 * 60 * 24));
588
589                    $duration = 99999999;
590
591                    if ($daysDifference > 1 && $daysDifference <= 7) {
592                        $duration = 7;
593                    } elseif ($daysDifference == 1) {
594                        $duration = 1;
595                    }
596
597                    if ($daysDifference <= 7) {
598                        if ($itv->is_due_appointment != $duration) {
599                            $isSendItv = 1;
600                        }
601                    } else {
602                        $data['is_due_appointment'] = null;
603                    }
604                }
605            }
606
607            $isSendItvMileage = 0;
608            $mileageDuration = 0;
609            if (isset($data['mileage']) && isset($data['mileage_threshold'])) {
610                if (($data['mileage'] > 0 && $data['mileage'] != null) && ($data['mileage_threshold'] > 0 && $data['mileage_threshold'] != null)) {
611                    $mileage = floor($data['mileage']);
612                    $mileageThreshold = floor($data['mileage_threshold']);
613
614                    if ($mileage < $mileageThreshold) {
615                        $mileageDuration = abs($mileage - $mileageThreshold);
616
617                        if ($mileageDuration <= 3000) {
618                            if ($itv->is_due_mileage == null) {
619                                $isSendItvMileage = 1;
620                            }
621                        }
622                    }
623                }
624            }
625
626            $fileCount = TblItvFiles::where('itv_id', $id)->count();
627
628            if ($files) {
629                $totalFileCount = $fileCount + count($files);
630                if ($totalFileCount > 3) {
631                    return response(['message' => 'KO', 'error' => __('language.file_count_exceeded')]);
632                }
633            }
634
635            $data['updated_at'] = date('Y-m-d H:i:s');
636            TblItv::where('id', $id)->update($data);
637
638            if ($isSendItv == 1) {
639                $this->email_reminders($duration, $id, $isBooked);
640            }
641
642            if ($isSendItvMileage == 1) {
643                $this->email_reminders_mileage($mileageDuration, $id);
644            }
645
646            if ($files) {
647
648                $directory = 'public/uploads';
649                $uploadedFiles = [];
650                $i = 0;
651
652                $combinedFilesSize = 0;
653                foreach ($files as $file) {
654                    $i++;
655                    $origFilename = str_replace(' ', '', $file->getClientOriginalName());
656                    $filename = $id.'-ITV'.time().'-'.$origFilename;
657
658                    $combinedFilesSize = $combinedFilesSize + $file->getSize();
659
660                    if ($combinedFilesSize > 25000000) {
661                        return response(['message' => 'KO', 'error' => __('language.file_size_exceeded')]);
662                    }
663
664                    Storage::putFileAs($directory, $file, $filename);
665                    Storage::disk('google')->put($filename, file_get_contents(storage_path().'/app/public/uploads/'.$filename));
666
667                    if (in_array($origFilename, $uploadedFiles)) {
668                        $origFilename = $origFilename.$i;
669                    }
670
671                    TblItvFiles::create(
672                        [
673                            'itv_id' => $id,
674                            'original_name' => $origFilename,
675                            'filename' => $filename,
676                            'uploaded_by' => $data['updated_by'],
677                        ]
678                    );
679
680                    $uploadedFiles[] = $file->getClientOriginalName();
681                }
682            }
683
684            Cache::flush();
685
686            return response([
687                'message' => 'OK', $daysDifference, $itv->is_due, $duration,
688            ]);
689
690        } catch (\Exception $e) {
691            return response(['message' => 'KO', 'error' => $e->getMessage()]);
692        }
693
694    }
695
696    public function create_itv(Request $request)
697    {
698
699        try {
700
701            $data = $request->all();
702
703            $files = $request->file('files');
704            unset($data['files']);
705
706            $result = TblItv::create($data);
707
708            $id = $result->id;
709
710            $isBooked = $data['is_booked'];
711
712            if ($data['is_booked'] == 0 || $data['is_booked'] == null) {
713                if (isset($data['next_itv_date'])) {
714                    $incommingDate = strtotime($data['next_itv_date']);
715                    $currentDate = strtotime(date('Y-m-d'));
716                    $secondsDifference = abs($incommingDate - $currentDate);
717                    $daysDifference = floor($secondsDifference / (60 * 60 * 24));
718
719                    $duration = 99999999;
720
721                    if ($daysDifference >= 15 && $daysDifference <= 30) {
722                        $duration = 30;
723                    } elseif ($daysDifference > 1 && $daysDifference <= 15) {
724                        $duration = 15;
725                    } elseif ($daysDifference == 1) {
726                        $duration = 1;
727                    }
728
729                    if ($daysDifference <= 30) {
730                        $this->email_reminders($duration, $id, $isBooked);
731                    }
732                }
733            } elseif ($data['is_booked'] == 1) {
734                if (isset($data['appointment_date'])) {
735                    $incommingDate = strtotime($data['appointment_date']);
736                    $currentDate = strtotime(date('Y-m-d'));
737                    $secondsDifference = abs($incommingDate - $currentDate);
738                    $daysDifference = floor($secondsDifference / (60 * 60 * 24));
739
740                    $duration = 99999999;
741
742                    if ($daysDifference > 1 && $daysDifference <= 7) {
743                        $duration = 7;
744                    } elseif ($daysDifference == 1) {
745                        $duration = 1;
746                    }
747
748                    if ($daysDifference <= 7) {
749                        if ($result->is_due_appointment != $duration) {
750                            $this->email_reminders($duration, $id, $isBooked);
751                        }
752                    } else {
753                        $data['is_due_appointment'] = null;
754                    }
755                }
756            }
757
758            $mileageDuration = 0;
759            if (isset($data['mileage']) && isset($data['mileage_threshold'])) {
760                if (($data['mileage'] > 0 && $data['mileage'] != null) && ($data['mileage_threshold'] > 0 && $data['mileage_threshold'] != null)) {
761                    $mileage = floor($data['mileage']);
762                    $mileageThreshold = floor($data['mileage_threshold']);
763
764                    $mileageDuration = abs($mileage - $mileageThreshold);
765
766                    if ($mileageDuration <= 3000) {
767                        $this->email_reminders_mileage($mileageDuration, $id);
768                    }
769                }
770            }
771
772            if ($files) {
773
774                $directory = 'public/uploads';
775                $uploadedFiles = [];
776                $i = 0;
777
778                $combinedFilesSize = 0;
779                foreach ($files as $file) {
780                    $i++;
781                    $origFilename = str_replace(' ', '', $file->getClientOriginalName());
782                    $filename = $id.'-ITV'.time().'-'.$origFilename;
783
784                    $combinedFilesSize = $combinedFilesSize + $file->getSize();
785
786                    if ($combinedFilesSize > 25000000) {
787                        return response(['message' => 'KO', 'error' => __('language.file_size_exceeded')]);
788                    }
789
790                    Storage::putFileAs($directory, $file, $filename);
791                    Storage::disk('google')->put($filename, file_get_contents(storage_path().'/app/public/uploads/'.$filename));
792
793                    if (in_array($origFilename, $uploadedFiles)) {
794                        $origFilename = $origFilename.$i;
795                    }
796
797                    TblItvFiles::create(
798                        [
799                            'itv_id' => $id,
800                            'original_name' => $origFilename,
801                            'filename' => $filename,
802                            'uploaded_by' => $data['created_by'],
803                        ]
804                    );
805
806                    $uploadedFiles[] = $file->getClientOriginalName();
807                }
808            }
809
810            Cache::flush();
811
812            return response([
813                'message' => 'OK',
814            ]);
815
816        } catch (\Exception $e) {
817            return response(['message' => 'KO', 'error' => $e->getMessage()]);
818        }
819
820    }
821
822    public function delete_itv(Request $request)
823    {
824
825        try {
826
827            $data = $request->all();
828            $result = [];
829
830            $r = new Request([
831                'filterModel' => $data['filterModel'],
832                'sortModel' => $data['sortModel'],
833                'start' => 0,
834                'end' => 999999999,
835                'company_id' => $data['company_id'],
836                'user_id' => $data['user_id'],
837                'ids' => $data['ids'],
838                'searchText' => $data['searchText'],
839                'ids_not_in' => $data['ids_not_in'],
840            ]);
841
842            $result = $this->list_itv($r);
843            $result = $result->original['data'];
844
845            $outputArray = [];
846
847            foreach ($result as $item) {
848                if (isset($item->id)) {
849                    $outputArray[] = $item->id;
850                }
851            }
852
853            TblItv::whereIn('id', $outputArray)->delete();
854
855            Cache::flush();
856
857            return response(['message' => 'OK', 'data' => $result]);
858
859        } catch (\Exception $e) {
860            return response(['message' => 'KO', 'error' => $e->getMessage()]);
861        }
862
863    }
864
865    public function get_itv($id)
866    {
867
868        try {
869
870            $id = intval($id);
871
872            $query = "SELECT 
873                        a.id,
874                        a.region, 
875                        a.company_id,
876                        b.name company_name,
877                        a.registration_date,
878                        a.brand, 
879                        a.model,
880                        a.vehicle_type,
881                        a.license_plate,
882                        a.mileage,
883                        a.last_itv_date,
884                        a.next_itv_date,
885                        a.mileage_threshold,
886                        a.driver,
887                        a.responsible_name,
888                        a.responsible_email,
889                        a.created_by,
890                        a.created_at,
891                        a.updated_by,
892                        a.updated_at,            
893                        a.is_due,
894                        a.is_due_appointment,
895                        a.location,
896                        a.is_booked,
897                        a.appointment_time,
898                        a.appointment_date,
899                        DATE_FORMAT(a.registration_date, '%m/%Y') registration_date_translate,
900                        DATE_FORMAT(a.last_itv_date, '%d/%m/%Y') last_itv_date_translate,
901                        DATE_FORMAT(a.next_itv_date, '%m/%Y') next_itv_date_translate,
902                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
903                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate,
904                        DATE_FORMAT(a.appointment_date, '%d/%m/%Y') appointment_date_translate,
905                        CASE
906                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 0 THEN 0
907                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 1 THEN 1
908                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 15 THEN 15
909                            WHEN DATEDIFF(a.next_itv_date, NOW()) <= 30 THEN 30
910                        ELSE NULL
911                        END AS next_itv_date_due,
912                        CASE
913                            WHEN DATEDIFF(a.appointment_date, NOW()) <= 0 THEN 0
914                            WHEN DATEDIFF(a.appointment_date, NOW()) <= 1 THEN 1
915                            WHEN DATEDIFF(a.appointment_date, NOW()) <= 7 THEN 7
916                        ELSE NULL
917                        END AS appointment_date_due,
918                        a.comments
919                    FROM 
920                        tbl_itv a 
921                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
922                    WHERE a.id = {$id}";
923
924            $result = DB::select($query);
925
926            Cache::flush();
927
928            return response(['message' => 'OK', 'data' => $result]);
929
930        } catch (\Exception $e) {
931            return response(['message' => 'KO', 'error' => $e->getMessage()]);
932        }
933    }
934
935    public function human_filesize($bytes, $decimals = 2)
936    {
937        $size = ['B', 'KB', 'MB'];
938
939        $factor = (int) floor((strlen($bytes) - 1) / 3);
940
941        return number_format($bytes / pow(1024, $factor), 2, ',', '.').$size[$factor];
942    }
943
944    public function get_itv_files($id)
945    {
946
947        try {
948
949            $id = intval($id);
950
951            $result = TblItvFiles::where('itv_id', $id)->get();
952
953            foreach ($result as $key => $value) {
954                $path = storage_path('app/public/uploads/'.$result[$key]->filename);
955
956                if (\File::exists($path)) {
957                    $fileSizeBytes = \File::size($path);
958                    $result[$key]->setAttribute('filesize', $this->human_filesize($fileSizeBytes));
959                    $result[$key]->original_name = $result[$key]->original_name." ({$result[$key]->getAttribute('filesize')})";
960                }
961            }
962
963            $emailLogs = TblItvEmailLogs::where('itv_id', $id)->get();
964
965            return response(['message' => 'OK', 'data' => $result, 'itvEmailLogs' => $emailLogs]);
966
967        } catch (\Exception $e) {
968            return response(['message' => 'KO', 'error' => $e->getMessage()]);
969        }
970    }
971
972    public function delete_itv_file($fileId)
973    {
974
975        try {
976
977            $fileId = intval($fileId);
978            $file = TblItvFiles::where('file_id', $fileId)->first();
979            $result = TblItvFiles::where('file_id', $fileId)->first();
980
981            if ($result) {
982                TblItvFiles::where('file_id', $fileId)->delete();
983                $path = storage_path('app/public/uploads/'.$result->filename);
984                Storage::disk('public')->delete('uploads/'.$result->filename);
985            }
986
987            return response(['message' => 'OK']);
988
989        } catch (\Exception $e) {
990            return response(['message' => 'KO', 'error' => $e->getMessage()]);
991        }
992    }
993
994    public function download_itv_file($fileId)
995    {
996
997        try {
998
999            $fileId = intval($fileId);
1000
1001            $result = TblItvFiles::where('file_id', $fileId)->first();
1002
1003            if ($result) {
1004                $path = storage_path('app/public/uploads/'.$result->filename);
1005
1006                if (! Storage::disk('public')->exists('uploads/'.$result->filename)) {
1007                    return response(['message' => 'KO']);
1008                }
1009
1010                return response()->download($path);
1011            }
1012
1013            return response(['message' => 'KO']);
1014
1015        } catch (\Exception $e) {
1016            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1017        }
1018
1019    }
1020
1021    public function isEmailValid($email)
1022    {
1023        // Regular expression pattern for email validation
1024        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
1025
1026        // Check if the email matches the pattern
1027        if (preg_match($pattern, $email)) {
1028            return true; // Valid email
1029        } else {
1030            return false; // Invalid email
1031        }
1032    }
1033
1034    public function email_reminders($duration, $id, $isBooked = 0)
1035    {
1036
1037        $item = TblItv::where('id', $id)->first();
1038
1039        $due = '';
1040        $subject = __('language.itv_reminders.subject');
1041        $body = '';
1042        $footer = __('language.itv_reminders.body_message_footer');
1043
1044        if ($isBooked == 0) {
1045            if ($duration == 30) {
1046                $due = __('language.itv_reminders.in_one_month');
1047            } elseif ($duration == 15) {
1048                $due = __('language.itv_reminders.in_15_days');
1049            } elseif ($duration == 1) {
1050                $due = __('language.itv_reminders.tomorrow');
1051                $subject = __('language.itv_reminders.subject_urgent');
1052                $footer = __('language.itv_reminders.body_message_footer_urgent');
1053            } else {
1054                return false;
1055            }
1056        } elseif ($isBooked == 1) {
1057            if ($duration == 7) {
1058                $due = __('language.itv_reminders.app_7_days');
1059                $subject = __('language.itv_reminders.subject_7_days');
1060                $footer = __('language.itv_reminders.body_message_footer_appointment');
1061            } elseif ($duration == 1) {
1062                $due = __('language.itv_reminders.app_tomorrow');
1063                $subject = __('language.itv_reminders.subject_tomorrow');
1064                $footer = __('language.itv_reminders.body_message_footer_appointment_urgent');
1065            } else {
1066                return false;
1067            }
1068        }
1069
1070        $email = new \SendGrid\Mail\Mail;
1071
1072        $user = TblUsers::where('id', $this->userId)->first();
1073        $userName = $user->name;
1074
1075        $addTo = [];
1076
1077        if (env('SENDGRID_STAGING')) {
1078            $email->addTo($user->email);
1079            array_push($addTo, $user->email);
1080        } else {
1081
1082            $user = TblUsers::where('name', $item->created_by)->first();
1083            $email->addTo($user->email);
1084            array_push($addTo, $user->email);
1085
1086            if ($item->created_by != $item->responsible_name) {
1087                $isValid = $this->isEmailValid($item->responsible_email);
1088                if ($isValid) {
1089                    $email->addTo($item->responsible_email);
1090                    array_push($addTo, $item->responsible_email);
1091                } else {
1092                    TblItvEmailLogs::create(
1093                        [
1094                            'itv_id' => $item->id,
1095                            'email' => $item->responsible_email,
1096                            'sent_by' => $userName,
1097                            'status' => 'Invalid email',
1098                        ]
1099                    );
1100                }
1101            }
1102        }
1103
1104        $subject = str_replace('{{brand}}', $item->brand, $subject);
1105        $subject = str_replace('{{license_plate}}', $item->license_plate, $subject);
1106
1107        $email->setFrom('fire@fire.es', 'Fire Service Titan');
1108        $email->setSubject($subject);
1109
1110        $imgpath = \File::get('fireservicetitan.png');
1111
1112        $email->addAttachment(
1113            $imgpath,
1114            'image/png',
1115            'fireservicetitan.png',
1116            'inline',
1117            'fireservicetitan'
1118        );
1119
1120        $url = env('URL')."itv/{$item->id}";
1121
1122        $bodyHeaders = __('language.itv_reminders.body_message_header');
1123
1124        if ($isBooked == 1) {
1125            $bodyHeaders = __('language.itv_reminders.body_message_header_appointment');
1126        }
1127
1128        $body .= __('language.itv_reminders.body_hello');
1129        $body = str_replace('{{responsible_name}}', $item->responsible_name, $body);
1130
1131        $body .= $bodyHeaders;
1132        $body = str_replace('{{duration}}', $due, $body);
1133        $body = str_replace('{{click}}', $url, $body);
1134
1135        $body .= __('language.itv_reminders.body_vehicle');
1136        $body = str_replace('{{vehicle}}', $item->brand, $body);
1137
1138        $body .= __('language.itv_reminders.body_license_plate');
1139        $body = str_replace('{{license_plate}}', $item->license_plate, $body);
1140
1141        $body .= __('language.itv_reminders.body_vehicle_type');
1142        $body = str_replace('{{vehicle_type}}', $item->vehicle_type, $body);
1143
1144        if ($isBooked == 1) {
1145            $body .= __('language.itv_reminders.body_appointment_date');
1146            $item->setAttribute('appointment_date_translate', date('d/m/Y', strtotime($item->appointment_date)));
1147            $body = str_replace('{{appointment_date}}', $item->getAttribute('appointment_date_translate'), $body);
1148
1149            $body .= __('language.itv_reminders.body_appointment_time');
1150            $formattedTime = date('g:i A', strtotime($item->appointment_time));
1151            $body = str_replace('{{appointment_time}}', $formattedTime, $body);
1152
1153            $body .= __('language.itv_reminders.body_location');
1154            $body = str_replace('{{location}}', $item->location, $body);
1155        } else {
1156            $body .= __('language.itv_reminders.body_next_itv_date');
1157            $item->setAttribute('next_itv_date_translate', date('m/Y', strtotime($item->next_itv_date)));
1158            $body = str_replace('{{next_itv_date}}', $item->getAttribute('next_itv_date_translate'), $body);
1159
1160            $body .= __('language.itv_reminders.body_driver');
1161            $body = str_replace('{{driver}}', $item->driver, $body);
1162        }
1163
1164        $body .= $footer;
1165
1166        $body .= '<p>Fire Service Titan</p>';
1167        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
1168
1169        $html = '<!DOCTYPE html>';
1170        $html .= '<html>';
1171        $html .= '<head>';
1172        $html .= '<meta charset="UTF-8">';
1173        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1174        $html .= '</head>';
1175        $html .= '<body>';
1176        $html .= $body;
1177        $html .= '</body>';
1178        $html .= '</html>';
1179
1180        $email->addContent('text/html', $html);
1181
1182        $sendgrid = new \SendGrid(env('SENDGRID_API_KEY'));
1183
1184        $response = $sendgrid->send($email);
1185        if ($response->statusCode() == 202) {
1186
1187            foreach ($addTo as $addToEmail) {
1188                TblItvEmailLogs::create(
1189                    [
1190                        'itv_id' => $item->id,
1191                        'email' => $addToEmail,
1192                        'sent_by' => $userName,
1193                        'status' => 'OK',
1194                    ]
1195                );
1196            }
1197
1198            $toUpdate = ['is_due' => $duration, 'updated_by' => $userName, 'updated_at' => date('Y-m-d H:i:s')];
1199
1200            if ($isBooked == 1) {
1201                $toUpdate = ['is_due_appointment' => $duration, 'updated_by' => $userName, 'updated_at' => date('Y-m-d H:i:s')];
1202            }
1203
1204            TblItv::where('id', $item->id)->update($toUpdate);
1205        } else {
1206            foreach ($addTo as $addToEmail) {
1207                TblItvEmailLogs::create(
1208                    [
1209                        'itv_id' => $item->id,
1210                        'email' => $addToEmail,
1211                        'sent_by' => $userName,
1212                        'status' => $response->body(),
1213                    ]
1214                );
1215            }
1216        }
1217    }
1218
1219    public function email_reminders_mileage($duration, $id)
1220    {
1221
1222        $item = TblItv::where('id', $id)->first();
1223
1224        $body = '';
1225        $subject = '';
1226
1227        $email = new \SendGrid\Mail\Mail;
1228
1229        $user = TblUsers::where('id', $this->userId)->first();
1230        $userName = $user->name;
1231
1232        $addTo = [];
1233
1234        if (env('SENDGRID_STAGING')) {
1235            $email->addTo($user->email);
1236            array_push($addTo, $user->email);
1237        } else {
1238
1239            $user = TblUsers::where('name', $item->created_by)->first();
1240            $email->addTo($user->email);
1241            array_push($addTo, $user->email);
1242
1243            if ($item->created_by != $item->responsible_name) {
1244                $isValid = $this->isEmailValid($item->responsible_email);
1245                if ($isValid) {
1246                    $email->addTo($item->responsible_email);
1247                    array_push($addTo, $item->responsible_email);
1248                } else {
1249                    TblItvEmailLogs::create(
1250                        [
1251                            'itv_id' => $item->id,
1252                            'email' => $item->responsible_email,
1253                            'sent_by' => $userName,
1254                            'status' => 'Invalid email',
1255                        ]
1256                    );
1257                }
1258            }
1259        }
1260
1261        $subject = __('language.itv_reminders_km.subject');
1262        $subject = str_replace('{{brand}}', $item->brand, $subject);
1263        $subject = str_replace('{{license_plate}}', $item->license_plate, $subject);
1264
1265        $email->setFrom('fire@fire.es', 'Fire Service Titan');
1266        $email->setSubject($subject);
1267
1268        $imgpath = \File::get('fireservicetitan.png');
1269
1270        $email->addAttachment(
1271            $imgpath,
1272            'image/png',
1273            'fireservicetitan.png',
1274            'inline',
1275            'fireservicetitan'
1276        );
1277
1278        $url = env('URL')."itv/{$item->id}";
1279
1280        $body .= __('language.itv_reminders_km.body_hello');
1281        $body = str_replace('{{responsible_name}}', $item->responsible_name, $body);
1282
1283        $body .= __('language.itv_reminders_km.body_message_header');
1284        $body = str_replace('{{click}}', $url, $body);
1285
1286        $body .= __('language.itv_reminders_km.body_vehicle');
1287        $body = str_replace('{{vehicle}}', $item->brand, $body);
1288
1289        $body .= __('language.itv_reminders_km.body_license_plate');
1290        $body = str_replace('{{license_plate}}', $item->license_plate, $body);
1291
1292        $body .= __('language.itv_reminders.body_vehicle_type');
1293        $body = str_replace('{{vehicle_type}}', $item->vehicle_type, $body);
1294
1295        $body .= __('language.itv_reminders_km.body_mileage');
1296        $body = str_replace('{{mileage}}', number_format($item->mileage, 2, ',', '.'), $body);
1297
1298        $body .= __('language.itv_reminders_km.body_mileage_threshold');
1299        $body = str_replace('{{mileage_threshold}}', number_format($item->mileage_threshold, 2, ',', '.'), $body);
1300
1301        $body .= __('language.itv_reminders_km.body_message_footer');
1302
1303        $body .= '<p>Fire Service Titan</p>';
1304        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
1305
1306        $html = '<!DOCTYPE html>';
1307        $html .= '<html>';
1308        $html .= '<head>';
1309        $html .= '<meta charset="UTF-8">';
1310        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1311        $html .= '</head>';
1312        $html .= '<body>';
1313        $html .= $body;
1314        $html .= '</body>';
1315        $html .= '</html>';
1316
1317        $email->addContent('text/html', $html);
1318
1319        $sendgrid = new \SendGrid(env('SENDGRID_API_KEY'));
1320
1321        $response = $sendgrid->send($email);
1322        if ($response->statusCode() == 202) {
1323
1324            foreach ($addTo as $addToEmail) {
1325                TblItvEmailLogs::create(
1326                    [
1327                        'itv_id' => $item->id,
1328                        'email' => $addToEmail,
1329                        'sent_by' => $userName,
1330                        'status' => 'OK',
1331                    ]
1332                );
1333            }
1334
1335            TblItv::where('id', $item->id)->update(['is_due_mileage' => $duration, 'updated_by' => $userName, 'updated_at' => date('Y-m-d H:i:s')]);
1336        } else {
1337            foreach ($addTo as $addToEmail) {
1338                TblItvEmailLogs::create(
1339                    [
1340                        'itv_id' => $item->id,
1341                        'email' => $addToEmail,
1342                        'sent_by' => $userName,
1343                        'status' => $response->body(),
1344                    ]
1345                );
1346            }
1347        }
1348    }
1349
1350    public function get_distincts()
1351    {
1352
1353        try {
1354
1355            $query = 'SELECT DISTINCT region FROM tbl_itv ORDER BY region ASC';
1356            $regions = DB::select($query);
1357
1358            $query = 'SELECT DISTINCT brand FROM tbl_itv ORDER BY brand ASC';
1359            $brands = DB::select($query);
1360
1361            $query = 'SELECT 
1362                        DISTINCT b.name 
1363                    FROM tbl_itv a 
1364                    LEFT JOIN tbl_companies b
1365                        ON a.company_id = b.company_id
1366                    ORDER BY b.name ASC';
1367
1368            $companies = DB::select($query);
1369
1370            $query = 'SELECT DISTINCT responsible_name FROM tbl_itv ORDER BY responsible_name ASC';
1371            $responsibleNames = DB::select($query);
1372
1373            $query = 'SELECT DISTINCT driver FROM tbl_itv ORDER BY driver ASC';
1374            $drivers = DB::select($query);
1375
1376            return response([
1377                'message' => 'OK',
1378                'regions' => $regions,
1379                'brands' => $brands,
1380                'companies' => $companies,
1381                'responsibleNames' => $responsibleNames,
1382                'drivers' => $drivers,
1383            ]);
1384
1385        } catch (\Exception $e) {
1386            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1387        }
1388
1389    }
1390
1391    public function get_all_users($companyId)
1392    {
1393
1394        try {
1395
1396            $companyId = intval($companyId);
1397
1398            $where = '';
1399
1400            if ($companyId != 0) {
1401                $where = "WHERE company_id = {$companyId} ";
1402            } else {
1403                $where = "WHERE company_id IN ({$this->companyId}";
1404            }
1405
1406            $query = "SELECT 
1407                        DISTINCT responsible_name 
1408                    FROM 
1409                        tbl_itv
1410                    {$where}
1411                    ORDER BY 
1412                    responsible_name ASC";
1413
1414            $responsibleNames = DB::select($query);
1415
1416            return response([
1417                'message' => 'OK',
1418                'responsibleNames' => $responsibleNames,
1419            ]);
1420
1421        } catch (\Exception $e) {
1422            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1423        }
1424    }
1425}