Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.48% covered (success)
93.48%
43 / 46
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
PdfSignatureHtmxController
93.33% covered (success)
93.33%
42 / 45
75.00% covered (warning)
75.00%
3 / 4
13.05
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 modalSignature
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 saveSignature
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
5
 persistSignature
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
6.73
1<?php
2
3declare(strict_types=1);
4
5/** @license For full copyright and license information, please see the LICENSE.md file. */
6
7namespace App\Modules\Pdf\Presentation\Htmx;
8
9defined('AMMONLY_APP') || exit('Direct script access is forbidden.');
10
11use App\Core\Database\FallbackPdoResolver;
12use PDO;
13use Psr\Http\Message\ResponseFactoryInterface;
14use Psr\Http\Message\ResponseInterface;
15use Psr\Http\Message\ServerRequestInterface;
16use Twig\Environment as TwigEnvironment;
17
18/**
19 * HTMX Controller for Handwritten Canvas Signature Capture Modals.
20 *
21 * @package App\Modules\Pdf\Presentation\Htmx
22 */
23final readonly class PdfSignatureHtmxController
24{
25    private ?PDO $pdo;
26
27    /**
28     * PdfSignatureHtmxController constructor.
29     *
30     * @param TwigEnvironment          $twig            Twig template engine.
31     * @param ResponseFactoryInterface $responseFactory PSR-17 response factory.
32     * @param PDO|null                 $pdo             Database connection handle.
33     */
34    public function __construct(
35        private TwigEnvironment $twig,
36        private ResponseFactoryInterface $responseFactory,
37        ?PDO $pdo = null
38    ) {
39        $this->pdo = $pdo ?? FallbackPdoResolver::resolveDefaultConnection();
40    }
41
42    /**
43     * Renders handwritten signature pad modal dialog.
44     *
45     * @param ServerRequestInterface $request HTTP request.
46     * @return ResponseInterface Modal HTML snippet.
47     */
48    public function modalSignature(ServerRequestInterface $request): ResponseInterface
49    {
50        $params = $request->getQueryParams();
51        $module = (string)($params['module'] ?? 'tickets');
52        $recordId = (int)($params['record_id'] ?? 0);
53        $signerRole = (string)($params['role'] ?? 'client');
54
55        $html = $this->twig->render('modules/pdf_templates/partials/modal_signature.twig', [
56            'module_name' => $module,
57            'record_id'   => $recordId,
58            'signer_role' => $signerRole,
59        ]);
60
61        $response = $this->responseFactory->createResponse(200)
62            ->withHeader('Content-Type', 'text/html; charset=UTF-8');
63        $response->getBody()->write($html);
64
65        return $response;
66    }
67
68    /**
69     * Handles submission of handwritten canvas signature (Base64 data URI).
70     *
71     * @param ServerRequestInterface $request HTTP request.
72     * @return ResponseInterface Success toast or trigger header.
73     */
74    public function saveSignature(ServerRequestInterface $request): ResponseInterface
75    {
76        $parsedBody = $request->getParsedBody();
77        $data = is_array($parsedBody) ? $parsedBody : [];
78
79        $module = (string)($data['module_name'] ?? 'tickets');
80        $recordId = (int)($data['record_id'] ?? 0);
81        $signatureData = (string)($data['signature_data'] ?? '');
82
83        if ($recordId > 0 && str_starts_with($signatureData, 'data:image/png;base64,') && $this->pdo !== null) {
84            $this->persistSignature($module, $recordId, $signatureData);
85        }
86
87        $toastHtml = '<div class="alert alert-success alert-dismissible mb-0" role="alert">'
88            . '<div class="d-flex">'
89            . '<div><h4 class="alert-title">Signature saved successfully!</h4>'
90            . '<div class="text-secondary">'
91            . 'The captured signature will be included in the generated PDF.'
92            . '</div></div></div>'
93            . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>'
94            . '</div>';
95
96        $response = $this->responseFactory->createResponse(200)
97            ->withHeader('Content-Type', 'text/html; charset=UTF-8')
98            ->withHeader('HX-Trigger', 'signatureSaved');
99        $response->getBody()->write($toastHtml);
100
101        return $response;
102    }
103
104    /**
105     * Persists signature data URI into database if compatible column exists.
106     *
107     * @param string $module        Module name.
108     * @param int    $recordId      Record identifier.
109     * @param string $signatureData Base64 Data URI string.
110     */
111    private function persistSignature(string $module, int $recordId, string $signatureData): void
112    {
113        if ($this->pdo === null) {
114            return;
115        }
116
117        try {
118            $cleanModule = strtolower(trim($module));
119            if (!preg_match('/^[a-z0-9_]{2,64}$/', $cleanModule)) {
120                return;
121            }
122            $table = 'a_mod_' . $cleanModule . '_records';
123            $checkCol = $this->pdo->query("SHOW COLUMNS FROM `{$table}` LIKE 'signature_data'");
124            if ($checkCol !== false && $checkCol->fetch() !== false) {
125                $upd = $this->pdo->prepare("UPDATE `{$table}` SET `signature_data` = :sig WHERE `id` = :id");
126                $upd->execute([':sig' => $signatureData, ':id' => $recordId]);
127            }
128        } catch (\Throwable) {
129            // Silently handled for modular flexibility
130        }
131    }
132}