Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
5866 eleazar 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
8
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
9
use Laminas\Mvc\Controller\AbstractActionController;
10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
use Laminas\View\Model\JsonModel;
13
use LeadersLinked\Mapper\QueryMapper;
14
use Laminas\Db\Sql\Select;
15
use LeadersLinked\Library\Functions;
16
use LeadersLinked\Mapper\SurveyTestMapper;
17
use LeadersLinked\Mapper\SurveyMapper;
18
use LeadersLinked\Mapper\SurveyFormMapper;
19
use LeadersLinked\Form\SurveyTestForm;
20
use LeadersLinked\Model\SurveyTest;
21
use LeadersLinked\Mapper\UserMapper;
22
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
23
use LeadersLinked\Library\SurveyReport;
7080 eleazar 24
use PhpOffice\PhpSpreadsheet\Spreadsheet;
25
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
26
use PhpOffice\PhpSpreadsheet\IOFactory;
5866 eleazar 27
 
28
class SurveyReportController extends AbstractActionController {
29
 
30
    /**
31
     *
32
     * @var AdapterInterface
33
     */
34
    private $adapter;
35
 
36
    /**
37
     *
38
     * @var AbstractAdapter
39
     */
40
    private $cache;
41
 
42
    /**
43
     *
44
     * @var  LoggerInterface
45
     */
46
    private $logger;
47
 
48
    /**
49
     *
50
     * @var array
51
     */
52
    private $config;
53
 
54
    /**
55
     *
56
     * @param AdapterInterface $adapter
57
     * @param AbstractAdapter $cache
58
     * @param LoggerInterface $logger
59
     * @param array $config
60
     */
61
    public function __construct($adapter, $cache, $logger, $config) {
62
        $this->adapter = $adapter;
63
        $this->cache = $cache;
64
        $this->logger = $logger;
65
        $this->config = $config;
66
    }
67
 
68
    public function indexAction() {
5911 eleazar 69
 
5866 eleazar 70
        $request = $this->getRequest();
71
        $currentUserPlugin = $this->plugin('currentUserPlugin');
72
        $currentCompany = $currentUserPlugin->getCompany();
73
        $currentUser = $currentUserPlugin->getUser();
74
 
6424 eleazar 75
        try{
5866 eleazar 76
        $request = $this->getRequest();
77
        if ($request->isGet()) {
78
 
79
            $headers = $request->getHeaders();
80
 
81
            $isJson = false;
82
            if ($headers->has('Accept')) {
83
                $accept = $headers->get('Accept');
84
 
85
                $prioritized = $accept->getPrioritized();
86
 
87
                foreach ($prioritized as $key => $value) {
88
                    $raw = trim($value->getRaw());
89
 
90
                    if (!$isJson) {
91
                        $isJson = strpos($raw, 'json');
92
                    }
93
                }
94
            }
95
 
96
            if ($isJson) {
5911 eleazar 97
 
5866 eleazar 98
                $search = $this->params()->fromQuery('search', []);
99
                $search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
100
 
101
                $page = intval($this->params()->fromQuery('start', 1), 10);
102
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
103
                $order = $this->params()->fromQuery('order', []);
104
                $order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
105
                $order_direction = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var($order[0]['dir'], FILTER_SANITIZE_STRING));
106
 
6411 eleazar 107
                $fields = ['name'];
6416 eleazar 108
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
5866 eleazar 109
 
110
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
111
                    $order_direction = 'ASC';
112
                }
113
 
6411 eleazar 114
                $surveyMapper = SurveyMapper::getInstance($this->adapter);
6412 eleazar 115
                $paginator = $surveyMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
6423 eleazar 116
 
117
                $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
118
 
5866 eleazar 119
                $items = [];
120
                $records = $paginator->getCurrentItems();
6866 eleazar 121
 
5866 eleazar 122
                foreach ($records as $record) {
6423 eleazar 123
                    $surveyForm = $surveyFormMapper->fetchOne($record->form_id);
6451 eleazar 124
                    $params = [
125
 
126
                        'id' => $record->uuid,
127
                    ];
5866 eleazar 128
                    $item = [
14215 kerby 129
                        'id' => $record->id,
6426 eleazar 130
                        'name' => $record->name,
6211 eleazar 131
                        'form' => $surveyForm->name,
6427 eleazar 132
                        'status' => $record->status,
5866 eleazar 133
                        'actions' => [
6496 eleazar 134
                            'link_report_all' => $this->url()->fromRoute('survey/report/all', ['survey_id' => $record->uuid]),
15150 efrain 135
                            'link_report_excel' => $this->url()->fromRoute('survey/report/excel', ['survey_id' => $record->uuid]),
6496 eleazar 136
                            'link_overview' => $this->url()->fromRoute('survey/report/overview', ['survey_id' => $record->uuid])
5866 eleazar 137
                        ]
138
                    ];
139
 
140
                    array_push($items, $item);
141
                }
142
 
143
                return new JsonModel([
144
                    'success' => true,
145
                    'data' => [
146
                        'items' => $items,
147
                        'total' => $paginator->getTotalItemCount(),
148
                    ]
149
                ]);
5911 eleazar 150
            } else {
151
                $surveyMapper = SurveyMapper::getInstance($this->adapter);
152
                $survies = $surveyMapper->fetchAllByCompanyId($currentCompany->id);
153
 
5866 eleazar 154
                $form = new SurveyTestForm($this->adapter, $currentCompany->id);
155
 
156
                $this->layout()->setTemplate('layout/layout-backend');
157
                $viewModel = new ViewModel();
5933 eleazar 158
                $viewModel->setTemplate('leaders-linked/survey-report/index.phtml');
5866 eleazar 159
                $viewModel->setVariables([
5911 eleazar 160
                    'form'      => $form,
161
                    'survies' => $survies
5866 eleazar 162
                ]);
163
                return $viewModel;
164
            }
165
        } else {
166
            return new JsonModel([
167
                'success' => false,
168
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
169
            ]);
170
 
6424 eleazar 171
        }
172
        } catch (\Throwable $e) {
173
            $e->getMessage();
174
            return new JsonModel([
175
                'success' => false,
176
                'data' => $e
177
            ]);
5866 eleazar 178
        }
6212 eleazar 179
 
5866 eleazar 180
    }
5911 eleazar 181
 
6496 eleazar 182
    public function overviewAction(){
183
        $request = $this->getRequest();
184
        $currentUserPlugin = $this->plugin('currentUserPlugin');
185
        $currentCompany = $currentUserPlugin->getCompany();
186
        $currentUser = $currentUserPlugin->getUser();
187
 
188
        $request = $this->getRequest();
189
        $uuid = $this->params()->fromRoute('survey_id');
190
 
191
        if (!$uuid) {
192
            $data = [
193
                'success' => false,
194
                'data' => 'ERROR_INVALID_PARAMETER'
195
            ];
196
 
197
            return new JsonModel($data);
198
        }
199
 
200
        $surveyMapper = SurveyMapper::getInstance($this->adapter);
201
        $survey = $surveyMapper->fetchOneByUuid($uuid);
202
 
203
        $surveyMapper = SurveyMapper::getInstance($this->adapter);
204
        $survey = $surveyMapper->fetchOneByUuid($uuid);
205
 
206
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
207
        $surveyTests = $surveyTestMapper->fetchAllBySurveyId($survey->id);
208
 
8355 eleazar 209
        if (!$surveyTests) {
210
            $data = [
211
                'success' => false,
212
                'data' => 'No hay respuestas en esta encuesta'
213
            ];
214
 
215
            return new JsonModel($data);
216
        }
217
 
6496 eleazar 218
        $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
219
        $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
220
 
221
        $sections = json_decode($surveyForm->content, true);
222
 
223
        $allTests = array_map(
224
            function($response) {
225
                return json_decode($response->content, true);
226
            },
227
            $surveyTests,
228
        );
229
 
230
        $averages = [];
231
 
232
        foreach($sections as $section) {
233
            foreach($section['questions'] as $question) {
234
                switch ($question['type']) {
235
                    case 'multiple':
236
                        $totals = [];
237
 
238
                        foreach($question['options'] as $option) {
239
                            $totals[$option['slug_option']] = 0;
240
                        }
241
 
242
                        foreach($question['options'] as $option) {
243
                            $totals[$option['slug_option']] = count(array_filter(
244
                                $allTests,
245
                                function ($test) use($option, $question) {
246
                                    return in_array($option['slug_option'], $test[$question['slug_question']]);
247
                                }
248
                            ));
249
                        }
250
 
251
                        $averages[$question['slug_question']] = $totals;
252
 
253
                        break;
254
 
255
                    case 'simple':
256
                        $totals = [];
257
 
258
                        foreach($question['options'] as $option) {
259
                            $totals[$option['slug_option']] = 0;
260
                        }
261
 
262
                        foreach ($allTests as $test) {
263
                            $totals[$test[$question['slug_question']]]++;
264
                        }
265
 
266
                        foreach($totals as $slug => $amount) {
267
                            $totals[$slug] = ($amount / count($allTests)) * 100;
268
                        }
269
 
270
                        $averages[$question['slug_question']] = $totals;
271
                    break;
272
 
273
                }
274
            }
275
        }
276
 
277
        $this->layout()->setTemplate('layout/layout-backend.phtml');
278
        $viewModel = new ViewModel();
279
        $viewModel->setTemplate('leaders-linked/survey-report/overview.phtml');
280
        $viewModel->setVariables([
6506 eleazar 281
            'sections' => $sections,
6524 eleazar 282
            'averages' => $averages,
6496 eleazar 283
        ]);
284
        return $viewModel ;
285
 
286
    }
287
 
6447 eleazar 288
    public function allAction() {
5930 eleazar 289
        $request = $this->getRequest();
290
        $currentUserPlugin = $this->plugin('currentUserPlugin');
291
        $currentCompany = $currentUserPlugin->getCompany();
292
        $currentUser = $currentUserPlugin->getUser();
293
 
294
        $request = $this->getRequest();
6043 eleazar 295
        $uuid = $this->params()->fromRoute('survey_id');
5961 eleazar 296
 
5930 eleazar 297
 
298
 
299
        if (!$uuid) {
300
            $data = [
301
                'success' => false,
302
                'data' => 'ERROR_INVALID_PARAMETER'
303
            ];
304
 
305
            return new JsonModel($data);
306
        }
307
 
6039 eleazar 308
        $surveyMapper = SurveyMapper::getInstance($this->adapter);
309
        $survey = $surveyMapper->fetchOneByUuid($uuid);
6044 eleazar 310
 
5965 eleazar 311
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
6052 eleazar 312
        $surveyTests = $surveyTestMapper->fetchAllBySurveyId($survey->id);
5966 eleazar 313
 
6052 eleazar 314
        if (!$surveyTests) {
5930 eleazar 315
            $data = [
316
                'success' => false,
5961 eleazar 317
                'data' => 'ERROR_RECORD_NOT_FOUND'
5930 eleazar 318
            ];
319
 
320
            return new JsonModel($data);
321
        }
322
 
5965 eleazar 323
 
5930 eleazar 324
        if ($request->isGet()) {
15150 efrain 325
 
5930 eleazar 326
            $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
5965 eleazar 327
            $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
5930 eleazar 328
 
329
            if ($surveyForm) {
330
 
15150 efrain 331
                return $this->renderPDF($currentCompany, $surveyForm, $surveyTests, $survey);
5930 eleazar 332
            } else {
333
 
334
                $data = [
335
                    'success' => false,
336
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
337
                ];
338
 
339
                return new JsonModel($data);
340
            }
341
        } else {
342
            $data = [
343
                'success' => false,
344
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
345
            ];
346
 
347
            return new JsonModel($data);
348
        }
349
 
350
        return new JsonModel($data);
351
    }
352
 
353
 
15150 efrain 354
    public function renderPDF($company, $surveyForm, $surveyTests, $survey) {
5930 eleazar 355
 
15150 efrain 356
 
357
 
5930 eleazar 358
 
359
 
15150 efrain 360
        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $company->uuid;
361
 
362
        $header = $company->header ? $target_path . DIRECTORY_SEPARATOR . $company->header : '';
363
        if(empty($header) || !file_exists($header)) {
364
            $header = $this->config['leaderslinked.images_default.company_pdf_header'];
365
        }
366
 
367
        $footer = $company->footer ? $target_path . DIRECTORY_SEPARATOR . $company->footer : '';
368
        if(empty($footer) || !file_exists($footer)) {
369
            $footer = $this->config['leaderslinked.images_default.company_pdf_footer'];
370
        }
371
 
372
 
373
        //Generate New PDF
374
        $pdf = new SurveyReport();
375
 
376
 
377
        $pdf->header = $header;
378
        $pdf->footer = $footer;
379
 
380
 
381
 
382
        $target_path = $this->config[ 'leaderslinked.fullpath.survey'] . DIRECTORY_SEPARATOR . $survey->uuid;
383
        if(!file_exists($target_path)) {
384
            mkdir($target_path, 0755, true);
385
        } else {
5930 eleazar 386
            Functions::deleteFiles($target_path);
387
        }
388
 
389
        // Set Data
15150 efrain 390
        $headerFormName = $this->cleanStringToPdf($surveyForm->name);
391
        $headerSurveyName = $this->cleanStringToPdf('Informe de Encuesta: ' . trim($survey->name) . ' al ' . date("m-d-Y H:i:s", strtotime($survey->added_on)));
6052 eleazar 392
        $sections = json_decode($surveyForm->content, true);
393
 
6053 eleazar 394
        $allTests = array_map(
6052 eleazar 395
            function($response) {
396
                return json_decode($response->content, true);
397
            },
398
            $surveyTests,
399
        );
15150 efrain 400
 
401
 
6052 eleazar 402
 
15150 efrain 403
 
6052 eleazar 404
        $averages = [];
405
 
406
        foreach($sections as $section) {
407
            foreach($section['questions'] as $question) {
408
                switch ($question['type']) {
6054 eleazar 409
                    case 'multiple':
6056 eleazar 410
                        $totals = [];
411
 
412
                        foreach($question['options'] as $option) {
413
                            $totals[$option['slug_option']] = 0;
414
                        }
415
 
416
                        foreach($question['options'] as $option) {
6057 eleazar 417
                            $totals[$option['slug_option']] = count(array_filter(
6056 eleazar 418
                                $allTests,
6452 eleazar 419
                                function ($test) use($option, $question) {
6450 eleazar 420
                                    return in_array($option['slug_option'], $test[$question['slug_question']]);
6056 eleazar 421
                                }
422
                            ));
423
                        }
6084 eleazar 424
 
6056 eleazar 425
                        $averages[$question['slug_question']] = $totals;
426
 
427
                        break;
6449 eleazar 428
 
6052 eleazar 429
                    case 'simple':
6053 eleazar 430
                        $totals = [];
6052 eleazar 431
 
432
                        foreach($question['options'] as $option) {
6053 eleazar 433
                            $totals[$option['slug_option']] = 0;
6052 eleazar 434
                        }
435
 
6053 eleazar 436
                        foreach ($allTests as $test) {
437
                            $totals[$test[$question['slug_question']]]++;
6052 eleazar 438
                        }
439
 
6053 eleazar 440
                        foreach($totals as $slug => $amount) {
441
                            $totals[$slug] = ($amount / count($allTests)) * 100;
6052 eleazar 442
                        }
443
 
6084 eleazar 444
                        $averages[$question['slug_question']] = $totals;
6052 eleazar 445
                    break;
6071 eleazar 446
 
6052 eleazar 447
                }
448
            }
449
        }
450
 
5930 eleazar 451
 
452
        $pdf->AliasNbPages();
453
        $pdf->AddPage();
454
 
455
        // Set header secundary
6071 eleazar 456
        $pdf->customHeader($headerFormName, $headerSurveyName);
5930 eleazar 457
 
6609 eleazar 458
        $countSection = 0;
459
 
15150 efrain 460
        for ($i = 0, $max = count($sections);  $i < $max ; $i++) {
461
            $headerUserName = '';
462
 
6615 eleazar 463
            if ($countSection > 1) {
464
                $countSection = 0;
465
                $pdf->AddPage();
466
                $pdf->customHeader($headerFormName, $headerUserName);
467
            }
468
            $section = $sections[$i];
6084 eleazar 469
 
470
            foreach ($section['questions'] as $question) {
6615 eleazar 471
 
6614 eleazar 472
                    switch ($question['type']) {
473
                        case 'simple':
474
                            $labels = [];
475
                            $values = [];
6039 eleazar 476
 
6614 eleazar 477
                            foreach($question['options'] as $option) {
15150 efrain 478
                                $label = $this->cleanStringToPdf($option['text']) . "\n(%.1f%%)";
479
                                $value = $averages[$question['slug_question']][$option['slug_option']];
480
                                if(empty($value)) {
481
                                    continue;
482
                                }
483
 
484
                                array_push($labels, $label);
485
 
486
                                array_push($values, $value);
6614 eleazar 487
                            }
488
 
489
                            $filename = $target_path . DIRECTORY_SEPARATOR .  $question['slug_question'] . '.png';
15150 efrain 490
                            $pdf->Cell(0,10, $this->cleanStringToPdf($question['text'], false),0,1);
6914 eleazar 491
                            $pdf->pieChart($labels, $values, '', $filename);
6614 eleazar 492
                            $pdf->SetFont('Arial', '', 12);
15150 efrain 493
                            $pdf->Image($filename, 10, $pdf->getY(), 190);
6614 eleazar 494
                            $pdf->setY($pdf->getY() + 90);
6912 eleazar 495
 
6614 eleazar 496
 
497
                            break;
498
 
499
                        case 'multiple':
500
                            $labels = [];
501
                            $values = [];
502
 
15150 efrain 503
                            foreach($question['options'] as $option)
504
                            {
505
                                $label = $this->cleanStringToPdf($option['text']) . "\n(%.1f%%)";
506
                                $value = $averages[$question['slug_question']][$option['slug_option']];
507
                                if(empty($value)) {
508
                                    continue;
509
                                }
510
 
511
                                array_push($labels, $label);
6614 eleazar 512
 
15150 efrain 513
                                array_push($values, $value);
6614 eleazar 514
                            }
515
 
516
                            $filename = $target_path . DIRECTORY_SEPARATOR .  $question['slug_question'] . '.png';
15150 efrain 517
                            $pdf->Cell(0,10,$this->cleanStringToPdf($question['text'], false),0,1);
518
                            $pdf->pieChart($labels, $values, '', $filename);
6614 eleazar 519
                            $pdf->SetFont('Arial', '', 12);
15150 efrain 520
                            $pdf->Image($filename, 10, $pdf->getY(), 190);
6614 eleazar 521
                            $pdf->setY($pdf->getY() + (count($values) * 13) + 10);
522
 
523
                            break;
524
                    }
6615 eleazar 525
                $countSection++;
6084 eleazar 526
            }
6608 eleazar 527
 
6615 eleazar 528
 
5930 eleazar 529
        }
530
 
7021 eleazar 531
        return $pdf->Output();
532
    }
533
 
15150 efrain 534
    public function excelAction() {
7021 eleazar 535
        $request = $this->getRequest();
536
        $currentUserPlugin = $this->plugin('currentUserPlugin');
537
        $currentCompany = $currentUserPlugin->getCompany();
538
        $currentUser = $currentUserPlugin->getUser();
539
 
540
        $request = $this->getRequest();
541
        $uuid = $this->params()->fromRoute('survey_id');
542
 
543
 
544
 
545
        if (!$uuid) {
546
            $data = [
547
                'success' => false,
548
                'data' => 'ERROR_INVALID_PARAMETER'
549
            ];
550
 
551
            return new JsonModel($data);
552
        }
553
 
554
        $surveyMapper = SurveyMapper::getInstance($this->adapter);
555
        $survey = $surveyMapper->fetchOneByUuid($uuid);
556
 
557
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
558
        $surveyTests = $surveyTestMapper->fetchAllBySurveyId($survey->id);
559
 
560
        if (!$surveyTests) {
561
            $data = [
562
                'success' => false,
563
                'data' => 'ERROR_RECORD_NOT_FOUND'
564
            ];
565
 
566
            return new JsonModel($data);
567
        }
568
 
569
 
570
        if ($request->isGet()) {
15150 efrain 571
 
7021 eleazar 572
            $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
573
            $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
574
 
575
            if ($surveyForm) {
576
 
15150 efrain 577
                $filename = $this->excelRender($surveyForm, $surveyTests, $survey);
578
                $content = file_get_contents($filename);
579
 
580
 
581
                $response = $this->getResponse();
582
                $headers = $response->getHeaders();
583
                $headers->clearHeaders();
584
 
585
 
586
                $headers->addHeaderLine('Content-Description: File Transfer');
587
                $headers->addHeaderLine('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
588
                $headers->addHeaderLine('Content-Disposition: attachment; filename='.$survey->uuid.'.xls');
589
                $headers->addHeaderLine('Content-Transfer-Encoding: binary');
590
                $headers->addHeaderLine('Expires: 0');
591
                $headers->addHeaderLine('Cache-Control: must-revalidate');
592
                $headers->addHeaderLine('Pragma: public');
593
 
594
 
595
                $response->setStatusCode(200);
596
                $response->setContent($content);
597
 
598
 
599
                return $response;
7021 eleazar 600
            } else {
601
 
602
                $data = [
603
                    'success' => false,
15150 efrain 604
                    'data' => 'ERROR_SURVEY_NOT_FOUND'
7021 eleazar 605
                ];
606
 
607
                return new JsonModel($data);
608
            }
609
        } else {
610
            $data = [
611
                'success' => false,
612
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
613
            ];
614
 
615
            return new JsonModel($data);
616
        }
617
 
618
        return new JsonModel($data);
619
    }
620
 
621
 
15150 efrain 622
    public function excelRender($surveyForm, $surveyTests, $survey)
7021 eleazar 623
    {
7026 eleazar 624
        $sections = json_decode($surveyForm->content, true);
7020 eleazar 625
 
7088 eleazar 626
        $spreadsheet = new Spreadsheet();
627
        $sheet = $spreadsheet->getActiveSheet();
628
 
7025 eleazar 629
        $allTests = array_map(
630
            function($response) {
631
                return json_decode($response->content, true);
632
            },
633
            $surveyTests,
634
        );
635
 
636
        $averages = [];
637
 
638
        foreach($sections as $section) {
639
            foreach($section['questions'] as $question) {
640
                switch ($question['type']) {
641
                    case 'multiple':
642
                        $totals = [];
643
 
644
                        foreach($question['options'] as $option) {
645
                            $totals[$option['slug_option']] = 0;
646
                        }
647
 
648
                        foreach($question['options'] as $option) {
649
                            $totals[$option['slug_option']] = count(array_filter(
650
                                $allTests,
651
                                function ($test) use($option, $question) {
652
                                    return in_array($option['slug_option'], $test[$question['slug_question']]);
653
                                }
654
                            ));
655
                        }
656
 
657
                        $averages[$question['slug_question']] = $totals;
658
 
659
                        break;
660
 
661
                    case 'simple':
662
                        $totals = [];
663
 
664
                        foreach($question['options'] as $option) {
665
                            $totals[$option['slug_option']] = 0;
666
                        }
667
 
668
                        foreach ($allTests as $test) {
669
                            $totals[$test[$question['slug_question']]]++;
670
                        }
671
 
672
                        foreach($totals as $slug => $amount) {
673
                            $totals[$slug] = ($amount / count($allTests)) * 100;
674
                        }
675
 
676
                        $averages[$question['slug_question']] = $totals;
677
                    break;
678
 
679
                }
680
            }
681
        }
682
 
7101 eleazar 683
        $row = 1;
684
 
7025 eleazar 685
        for ($i = 0; $i < count($sections); $i++) {
686
            $section = $sections[$i];
687
 
7096 eleazar 688
           for($j = 0; $j < count($section['questions']); $j++) {
7099 eleazar 689
                $question = $section['questions'][$j];
7095 eleazar 690
 
7101 eleazar 691
                if (!in_array($question['type'], ['simple', 'multiple'])){
692
                    continue;
693
                }
15150 efrain 694
 
695
                $row++;
696
                $sheet->setCellValue('A' . $row , $this->cleanStringToExcel($question['text']));
7101 eleazar 697
 
7028 eleazar 698
                switch ($question['type']) {
7032 eleazar 699
                    case 'simple':
7102 eleazar 700
                        for($k = 0; $k < count($question['options']); $k++) {
15150 efrain 701
                            $row++;
702
 
7102 eleazar 703
                            $option = $question['options'][$k];
15150 efrain 704
 
705
 
706
                            $sheet->setCellValue('B' . $row , $this->cleanStringToExcel($option['text']));
707
                            $sheet->setCellValue('C' . $row , round($averages[$question['slug_question']][$option['slug_option']], 2) . '%');
708
 
7032 eleazar 709
                        }
7025 eleazar 710
 
7032 eleazar 711
                        break;
7025 eleazar 712
 
7032 eleazar 713
                    case 'multiple':
7102 eleazar 714
                        for($k = 0; $k < count($question['options']); $k++) {
15150 efrain 715
 
716
                            $row++;
7102 eleazar 717
                            $option = $question['options'][$k];
15150 efrain 718
                            $sheet->setCellValue('B' . $row , $this->cleanStringToExcel($option['text']));
719
                            $sheet->setCellValue('C' . $row , round($averages[$question['slug_question']][$option['slug_option']]));
720
 
7032 eleazar 721
                        }
7025 eleazar 722
 
7032 eleazar 723
                        break;
724
                }
7025 eleazar 725
            }
726
 
727
 
728
        }
729
 
15150 efrain 730
 
731
 
732
        $target_path = $this->config[ 'leaderslinked.fullpath.survey'] . DIRECTORY_SEPARATOR . $survey->uuid;
733
        if(!file_exists($target_path)) {
734
            mkdir($target_path, 0755, true);
735
        }
736
 
737
        $filename = $target_path  . DIRECTORY_SEPARATOR . $survey->uuid . '.xls';
738
 
7088 eleazar 739
        $writer = new Xlsx($spreadsheet);
15150 efrain 740
        $writer->save($filename);
741
 
742
        return $filename;
743
 
744
    }
745
 
7088 eleazar 746
 
15150 efrain 747
 
748
    private function cleanStringToPdf($s, $mbConvert = true)
749
    {
750
 
751
        $s = html_entity_decode($s);
752
 
753
 
754
        if($mbConvert) {
755
            $detect = mb_detect_encoding($s);
756
            if(strtoupper($detect) != 'UTF8') {
757
 
758
                $s = mb_convert_encoding($s, 'UTF8', $detect);
759
 
760
            }
761
        } else {
762
            $s = utf8_decode($s);
763
        }
764
 
765
 
766
        return strip_tags($s);
5930 eleazar 767
    }
15150 efrain 768
 
769
    private function cleanStringToExcel($s)
770
    {
771
 
772
        $s = html_entity_decode($s);
773
        return strip_tags($s);
774
    }
5866 eleazar 775
}