<?php

class signature
{
    function __construct($html_input_for_file_name = '', $save_is_submit = 0, $width = 300, $height = 200)
    {
        ?>
        <style>
            #signature-container {
                width:
                    <?php echo $width; ?>
                    px;
                height:
                    <?php echo $height; ?>
                    px;
                border: 1px solid #ccc;
                background-color: #fff;
                touch-action: none;
                position: relative;
            }

            #signature-pad {
                width: 100%;
                /* height: 100%; */
            }

            #buttons {
                margin-top: 10px;
            }
        </style>

        <h2>Signature Pad</h2>
        <div id="signature-container">
            <canvas id="signature-pad"></canvas>
        </div>

        <div id="buttons">
            <button class="submit_btn" onclick="clearPad()">Clear</button>
            <button class="submit_btn" onclick="savePad()">SIGN</button>
        </div>

        <script>
            const canvas = document.getElementById('signature-pad');
            const container = document.getElementById('signature-container');
            const ctx = canvas.getContext('2d');

            // Match canvas resolution to container size
            canvas.width = container.offsetWidth;
            canvas.height = container.offsetHeight;

            let drawing = false;

            canvas.addEventListener('mousedown', startDraw);
            canvas.addEventListener('mouseup', stopDraw);
            canvas.addEventListener('mouseout', stopDraw);
            canvas.addEventListener('mousemove', draw);

            canvas.addEventListener('touchstart', startDraw, { passive: false });
            canvas.addEventListener('touchend', stopDraw, { passive: false });
            canvas.addEventListener('touchmove', drawTouch, { passive: false });

            function getPos(e) {
                const rect = canvas.getBoundingClientRect();
                const clientX = e.clientX || (e.touches && e.touches[0].clientX);
                const clientY = e.clientY || (e.touches && e.touches[0].clientY);
                return {
                    x: (clientX - rect.left) * (canvas.width / rect.width),
                    y: (clientY - rect.top) * (canvas.height / rect.height)
                };
            }

            function startDraw(e) {
                e.preventDefault();
                drawing = true;
                ctx.beginPath();
                const pos = getPos(e);
                ctx.moveTo(pos.x, pos.y);
            }

            function stopDraw() {
                drawing = false;
            }

            function draw(e) {
                if (!drawing) return;
                const pos = getPos(e);
                ctx.lineTo(pos.x, pos.y);
                ctx.stroke();
            }

            function drawTouch(e) {
                e.preventDefault();
                if (!drawing) return;
                const pos = getPos(e);
                ctx.lineTo(pos.x, pos.y);
                ctx.stroke();
            }

            function clearPad() {
                event.preventDefault();
                ctx.clearRect(0, 0, canvas.width, canvas.height);
            }

            function savePad() {
                // Prevent form from submitting
                event.preventDefault();
                const dataURL = canvas.toDataURL('image/png');

                const xhr = new XMLHttpRequest();
                xhr.open('POST', '//<?php echo $_SERVER['HTTP_HOST']; ?>/classes/save_signature.php', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (xhr.responseText !== '0') {
                            alert('Signature saved successfully!');
                            const inputName = '<?php echo $html_input_for_file_name; ?>';
                            const saveIsSubmit = <?php echo (int) $save_is_submit; ?>;

                            if (inputName !== '') {
                                // alert(inputName);
                                const inputElement = document.getElementById(inputName);
                                if (inputElement) {
                                    inputElement.setAttribute('value', xhr.responseText);
                                    // alert(inputElement.value);

                                }
                            }
                            if (inputElement.value == xhr.responseText) {
                                // ✅ Only try submitting form if save_is_submit == 1
                                if (<?php echo (int) $save_is_submit; ?> === 1) {
                                    const form = document.forms[0];
                                    const requiredInputs = form.querySelectorAll('input[required], select[required], textarea[required]');
                                    let valid = true;

                                    requiredInputs.forEach(el => {
                                        if (el.value.trim() === '') {
                                            valid = false;
                                        }
                                    });

                                    if (valid) {
                                        // alert(document.getElementById('signature1').value);
                                        form.dispatchEvent(new Event('submit'));
                                    } else {
                                        alert('Please fill in all required fields!');
                                    }
                                }
                            }
                        } else {
                            alert('Error saving signature!');
                        }
                    }
                };

                xhr.send('image=' + encodeURIComponent(dataURL));
            }
        </script>
        <?php
    }
}