<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$clear_btn = new Button();
$clear_btn->value("CLEAR");
$clear_btn->onclick("signaturePad.clear()");

$delete_btn = new Button();
$delete_btn->value("DELETE");
$delete_btn->onclick("delete_signature()");

if (file_exists("../signature/images/a-{$_SESSION['user_id']}-signature.png")) {
    $styles_change = "float:right;";
    ?>
    <div class='form_down' style="display:flex;flex-direction:row">
        <h1 style="width:100%">SIGNATURES</h1>

        <div class='form_down' style='width:40%; margin-bottom:5vw; float:left'>
            <h1>CURRENT</h1>
            <img src="../signature/images/a-<?php echo $_SESSION['user_id']; ?>-signature.png?v<?php echo rand(0, 9999); ?>"
                alt="NOT FOUND" style="width: 40%; border-radius: 1%;">
            <?php
            $delete_btn->add();
            ?>
            <!-- <button type="button" id="delete_signature" onclick="delete_signature();" class="button">DELETE</button> -->

            <script>
                function delete_signature() {
                    // delete the signature png
                    if (confirm('Are you sure you want to delete your current signature?')) {
                        var xhttp = new XMLHttpRequest();
                        xhttp.onreadystatechange = function () {
                            if (this.readyState == 4 && this.status == 200) {
                                if (this.responseText == 1) {
                                    window.reload();
                                } else {
                                    alert(this.responseText);
                                }
                            }
                        };
                        xhttp.open("GET", "../signature/delete_signature.php", true);
                        xhttp.send();
                    }
                }
            </script>
        </div>
        <?php
} else {
    ?>
        <div class='form_down' style='margin-bottom:5vw;<?php echo $styles_change; ?>'>
            <h2>NEW</h2>
            <canvas id="signature_pad" class="signature-pad" width=500 height=300
                style='background-color:lightgrey;border-radius:20px;'></canvas><br>
            <div style="display:flex">
                <button type="button" id="save_signature" class="submit_btn">SAVE</button>
                <?php
                $clear_btn->add();
                ?>
            </div>
        </div>
        <?php
}
?>

</div>

<script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

<script>
    var canvas = document.getElementById('signature_pad');
    var signaturePad = new SignaturePad(canvas);

    document.getElementById('save_signature').addEventListener('click', function () {
        if (signaturePad.isEmpty()) {
            alert("Please provide signature first.");
        } else {
            var dataURL = signaturePad.toDataURL('image/png');
            var blob = dataURLToBlob(dataURL);
            var formData = new FormData();
            formData.append('file', blob, 'signature.png');

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "../signature/upload_signature.php", true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // alert(xhr.responseText); // Handle the server response
                    if (xhr.responseText.indexOf("OK") > 1) {
                        // repload page
                        location.reload();

                    } else {
                        alert(xhr.responseText);
                    }
                }
            };
            xhr.send(formData);
        }
    });

    function dataURLToBlob(dataURL) {
        var binary = atob(dataURL.split(',')[1]);
        var array = [];
        for (var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {
            type: dataURL.split(',')[0].split(':')[1].split(';')[0]
        });
    }
</script>