<?php include "../../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$jobcard_data_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = '{$_GET['record_id']}'");

$jobcard_data = $jobcard_data_res->fetch_assoc();

$jobcard_history_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = '{$jobcard_data['drilling_invoice']}'");
$jobcard_history = $jobcard_history_res->fetch_assoc();
?>

<style>
    @media (min-width: 651px) and (max-width: 1050px) {
        .save_sign_btn {
            position: relative;
            font-size: 2em;
            cursor: pointer;
            border: 3px solid navy;
            background: white;
            color: black;
            border-radius: 15px;
            padding: 1.5vw;
            height: 15vw;
            width: 55vw;
            text-align: center;
        }

        .signature_form {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
        }

        .div_signatures {
            position: relative;
            display: flex;
            flex-direction: column;
            width: 100%;
            justify-content: space-around;
            width: fit-content;
            /* margin-top: 30vh; */
            /* margin-bottom: 30vh; */
        }

        .history_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }
    }
</style>

<div class="signature_form" id="signatures" style="padding: 4vw; margin-top: 3vw; height: 130vh;">
    <h1 class="sign_h1">SIGNATURES</h1>
    <div class="list_inputs">
        Please Note: Savuki Drilling Mpumalanga
        <ul>
            <li>1. Cannot be held responsible for any damage or borehole collapse.</li>
            <li>2. Steel casings must be installed on the recommendation of the drill team.</li>
            <li>3. Will not be held liable for any damage on property.</li>
            <li>4. No water is guaranteed even if Savuki Drilling surveyed.</li>
            <li>5. Client pays for service of drilling, not water.</li>
        </ul>
        <b><i>SAFETY PRECAUTION - <br> CUSTOMER IS RESPONSIBLE FOR COVERING OF BOREHOLE AFTER DRILLING.<br> SAVUKI
                DRILLING MPUMALANGA WILL NOT BE LIABLE FOR ANY ACCIDENTS CAUSED BY ANY UNCOVERED BOREHOLES.</i></b>
    </div>

    <input type="text" id="jobcard_id" name="jobcard_id" value="<?php echo $jobcard_data['jobcard_no']; ?>" hidden>

    <div class='div_signatures'>
        <div class="sub_down">

            <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

            <?php
            // EMPLOYEE SIGNATURE
            if (file_exists("../jobcards/signatures/employee-jc" . $jobcard_data['drilling_invoice'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                ?>
                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                    <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                    <input type='image' src='../jobcards/signatures/employee-jc<?php echo $jobcard_data['jobcard_no']; ?>-
                <?php echo $_SESSION['user_id']; ?>-signature.png' alt='employee signature' class="signature_image">
                </div>
                <?php
            } else {
                ?>
                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                    <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                    <canvas id="employee_signature" class="signature-pad"></canvas>
                    <div style="display:flex;gap:10px;">
                        <button type="button" id="clear_employee_signature" class="sign_btn">CLEAR</button>
                    </div>
                </div>
                <?php
            }

            // CLIENT SIGNATURE
            if (file_exists("../jobcards/signatures/client-jc" . $jobcard_data['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                ?>
                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                    <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                    <input type="image"
                        src="../jobcards/signatures/client-jc<?php echo $jobcard_data['jobcard_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png"
                        alt="client signature" class="signature_image">
                </div>
                <?php
            } else {
                ?>
                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                    <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                    <canvas id="client_signature" class="signature-pad"></canvas>
                    <div style="display:flex;gap:10px;">
                        <button type="button" id="clear_client_signature" class="sign_btn">CLEAR</button>
                    </div>
                </div>
                <?php
            }
            ?>

            <script>
                document.addEventListener('DOMContentLoaded', function () {
                    const clientCanvas = document.getElementById('client_signature');
                    const employeeCanvas = document.getElementById('employee_signature');
                    const saveButton = document.getElementById('save_signatures');
                    const clearClient = document.getElementById('clear_client_signature');
                    const clearEmployee = document.getElementById('clear_employee_signature');
                    const record_id = document.getElementById("jobcard_id").value;

                    function resizeCanvas(canvas) {
                        if (!canvas) return;
                        const ratio = Math.max(window.devicePixelRatio || 1, 1);
                        // use getBoundingClientRect to respect CSS height/width
                        const rect = canvas.getBoundingClientRect();
                        canvas.width = rect.width * ratio;
                        canvas.height = rect.height * ratio;
                        const ctx = canvas.getContext("2d");
                        ctx.scale(ratio, ratio);
                    }

                    resizeCanvas(clientCanvas);
                    resizeCanvas(employeeCanvas);

                    window.addEventListener("resize", () => {
                        resizeCanvas(clientCanvas);
                        resizeCanvas(employeeCanvas);
                    });

                    // Improved SignaturePad options
                    const padOptions = {
                        minWidth: 0.5,
                        maxWidth: 2.5,
                        throttle: 0,
                        velocityFilterWeight: 0.6,
                        penColor: 'black',
                        backgroundColor: 'rgba(255,255,255,0)'
                    };

                    const client_pad = clientCanvas ? new SignaturePad(clientCanvas, padOptions) : null;
                    const employee_pad = employeeCanvas ? new SignaturePad(employeeCanvas, padOptions) : null;

                    // Prevent scrolling while signing (mobile)
                    [clientCanvas, employeeCanvas].forEach(canvas => {
                        if (canvas) {
                            canvas.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
                            canvas.addEventListener("touchmove", e => e.preventDefault(), { passive: false });
                        }
                    });

                    // Clear buttons
                    if (clearClient && client_pad) {
                        clearClient.addEventListener('click', () => client_pad.clear());
                    }

                    if (clearEmployee && employee_pad) {
                        clearEmployee.addEventListener('click', () => employee_pad.clear());
                    }

                    // Save button
                    if (saveButton) {
                        saveButton.addEventListener('click', function () {
                            if ((!client_pad || client_pad.isEmpty()) && (!employee_pad || employee_pad.isEmpty())) {
                                alert("Please provide at least one signature.");
                                return;
                            }

                            saveButton.disabled = true;
                            saveButton.textContent = "Saving...";

                            let uploads = 0;
                            let total = (client_pad && !client_pad.isEmpty() ? 1 : 0) +
                                (employee_pad && !employee_pad.isEmpty() ? 1 : 0);

                            function checkComplete() {
                                uploads++;
                                if (uploads === total) location.reload();
                            }

                            if (client_pad && !client_pad.isEmpty()) uploadSignature(client_pad, 'client', checkComplete);
                            if (employee_pad && !employee_pad.isEmpty()) uploadSignature(employee_pad, 'employee', checkComplete);
                        });
                    }

                    // Upload function
                    function uploadSignature(pad, type, callback) {
                        const dataURL = pad.toDataURL('image/png');
                        const blob = dataURLToBlob(dataURL);
                        const formData = new FormData();

                        formData.append('file', blob, type + '_signature.png');
                        formData.append('record_id', record_id);
                        formData.append('type', type);

                        const xhr = new XMLHttpRequest();
                        xhr.open("POST", "../jobcards/upload_signature.php", true);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4) {
                                if (xhr.status === 200 && xhr.responseText === "OK") {
                                    console.log(`${type} signature saved successfully.`);
                                } else {
                                    const errorMsg = xhr.responseText.replace('ERROR: ', '');
                                    alert(`Error saving ${type} signature: ${errorMsg}`);
                                }
                                if (callback) callback();
                            }
                        };
                        xhr.send(formData);
                    }

                    // Convert Base64 to Blob
                    function dataURLToBlob(dataURL) {
                        const binary = atob(dataURL.split(',')[1]);
                        const array = [];
                        for (let i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
                        return new Blob([new Uint8Array(array)], { type: 'image/png' });
                    }
                });
            </script>

            <div style="margin-top: 40vw;">
                <?php
                if (
                    !file_exists("../jobcards/signatures/employee-jc" . $jobcard_data['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png") ||
                    !file_exists("../jobcards/signatures/client-jc" . $jobcard_data['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png")
                ) {
                    ?>
                    <button type="button" id="save_signatures" class="save_sign_btn">SAVE</button>
                    <?php
                }
                ?>
            </div>
        </div>
    </div>
</div>

<div class="history_div">
    <h2 class="create_h2">JOCARD HISTORY</h2>
    <br>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">CLIENT NAME : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['client_name']; ?>">
    </div>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">CONTACT NUMBER : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['contact_number']; ?>">
    </div>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">OTHER NUMBER : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['other_number']; ?>">
    </div>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">ALTERNATE NUMBER : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['alternate_number']; ?>">
    </div>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">BREAK FOUND ON : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['break_found_on']; ?>">
    </div>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">WATER STRIKE : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['water_strike']; ?>">
    </div>
    <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jc_no_label" class="create_details_label">WATER FLOW : </label>
        <input class="create_details_input" value="<?php echo $jobcard_history['water_flow']; ?>">
    </div>
</div>