<?php include "../../root.class.php";
$html = new html();
$db = new db_safeguard();
$html->add_styles_page();

$date_time = date("Y-m-d H:i", strtotime("+2 Hours"));

if (isset($_GET['record_id'])) {
    $lop_res = $db->query("final_sorting_jobcard", "SELECT * FROM final_sorting_jobcard WHERE record_id = '" . $_GET['record_id'] . "' ");
    $final_sorting = $lop_res->fetch_assoc();
    $final_sorting_record_id = $final_sorting['record_id'];
} else {

    $lop_res = $db->query("final_sorting_jobcard", "SELECT jobcard_no FROM final_sorting_jobcard ORDER BY record_id DESC LIMIT 1");
    if ($lop_res->num_rows == 0) {
        $jobcard_no = 1;
    } else {
        $final_sorting = $lop_res->fetch_assoc();
        $jobcard_no = $final_sorting['jobcard_no'] + 1;
    }
    $final_sorting_record_id = $db->query("final_sorting_jobcard", "INSERT INTO final_sorting_jobcard (jobcard_no) VALUES ('" . $jobcard_no . "')");
    echo "<script>window.location.href = 'final_sorting.php?record_id=" . $final_sorting_record_id . "'</script>";
}

$product_id_label = new label();
$product_id_label->for("product_id_label");
$product_id_label->value("Product Identification");

$product_id = new input();
$product_id->type("text");
$product_id->name("product_id");
$product_id->id("product_id");
$product_id->placeholder("Product ID");
$product_id->style("width: 20%");
$product_id->value($final_sorting['product_no']);

$final_sorting_id = new input();
$final_sorting_id->type("hidden");
$final_sorting_id->name("final_sorting_id");
$final_sorting_id->id("final_sorting_id");
$final_sorting_id->placeholder("LOP JC NO");
$final_sorting_id->value($final_sorting_record_id);

$record_id = new input();
$record_id->type("hidden");
$record_id->name("record_id");
$record_id->id("record_id");
$record_id->placeholder("");
$record_id->value($final_sorting_record_id);

$jobcard_date_opened_label = new label();
$jobcard_date_opened_label->for("date_opened_label");
$jobcard_date_opened_label->value("Date Jobcard Opened");

$jobcard_date_opened = new input();
$jobcard_date_opened->type("datetime-local");
$jobcard_date_opened->name("jobcard_date_opened");
$jobcard_date_opened->id("jobcard_date_opened");
$jobcard_date_opened->value($final_sorting['date_jobcard_opened']);

$checked_by_production_label = new label();
$checked_by_production_label->for("checked_by_label");
$checked_by_production_label->value("Checked By (Production)");

$checked_by_production = new input();
$checked_by_production->type("text");
$checked_by_production->name("production_checked_by");
$checked_by_production->id("production_checked_by");
$checked_by_production->placeholder("Checked By (Production)");
$checked_by_production->style("width: 40%");
$checked_by_production->value($final_sorting['production_checked_by']);

$checked_by_quality_control_label = new label();
$checked_by_quality_control_label->for("checked_by_label");
$checked_by_quality_control_label->value("Checked By (Quality Control)");

$user_id = $_SESSION['user_id'];

$username_res = $db->query("users", "SELECT username FROM users WHERE record_id = $user_id");
$username = $username_res->fetch_assoc();

$checked_by_quality_control = new input();
$checked_by_quality_control->type("text");
$checked_by_quality_control->name("quality_control_checked_by");
$checked_by_quality_control->id("quality_control_checked_by");
$checked_by_quality_control->placeholder("Checked By (Quality Control)");
$checked_by_quality_control->value($username['username']);
$checked_by_quality_control->style("width: 40%");

$batch_no_label = new label();
$batch_no_label->for("batch_no_label");
$batch_no_label->value("Batch No");

$batch_no = new input();
$batch_no->type("text");
$batch_no->name("batch_no");
$batch_no->id("batch_no");
$batch_no->placeholder("Batch No");
$batch_no->value($final_sorting['batch_no']);
$batch_no->style("width: 20%");


// EQUIPMENT SECTION

$equipment_label = new label();
$equipment_label->for("equipment_label");
$equipment_label->value("Equipment");

$equipment_settings_label = new label();
$equipment_settings_label->for("equipment_settings_label");
$equipment_settings_label->value("Equipment Settings & Line-speed specifications");

$accurate_label = new label();
$accurate_label->for("accurate_label");
$accurate_label->value("Accurate (YES/NO)");

$equipment = new input();
$equipment->name("equipment_0");
$equipment->id("equipment_0");
$equipment->placeholder("Equipment");
$equipment->style("width: 90%");

$varify_settings = new input();
$varify_settings->type("text");
$varify_settings->name("verify_settings_0");
$varify_settings->id("varify_settings_0");
$varify_settings->placeholder("List of settings to be verified before start-up");
$varify_settings->style("width: 90%");

$accurate = new select();
$accurate->name("accurate_0");
$accurate->id("accurate_0");
$accurate->add_option("", "SELECT ACCURATE");
$accurate->add_option("YES", "YES");
$accurate->add_option("NO", "NO");
$accurate->style("width: 90%");

$submit_btn = new button();
$submit_btn->class("submit_btn");
$submit_btn->value("Submit");
$submit_btn->id("submit_btn");

?>

<form id="final_sorting_form" action="save_final_sorting.php" method="post">
    <div class="form_down">
        <h1>FINAL SORTING JOBCARD</h1>

        <?php
        $record_id->add();
        $jobcard_date_opened_label->add();
        $jobcard_date_opened->add();

        $product_id_label->add();
        $product_id->add();

        $checked_by_quality_control_label->add();
        $checked_by_quality_control->add();

        $checked_by_production_label->add();
        $checked_by_production->add();

        $batch_no_label->add();
        $batch_no->add();
        ?>
        <div style="display: flex; justify-content: center;">
            <button type="button" onclick="halfway_save()" class="submit_btn">SAVE</button>
        </div>
        <br>
        <br>
        <br><br>
        <h1>EQUIPMENT CHECKLIST</h1>
        <br>
        <div id="equipments_table" style="display: flex; flex-direction: column; border: 2px solid black; width: 90%;">
            <input type="text" hidden name="final_sorting_id" value="<?php echo $final_sorting_record_id; ?>">
            <table style="width: 100%;">
                <tr>
                    <td>EQUIPMENT</td>
                    <td>QUESTION</td>
                    <td>ANSWER</td>
                    <td>DATE</td>
                    <td>USER</td>
                </tr>
                <tbody>
                    <?php
                    $equipment_check_res = $db->query("final_sorting_equipment_check_list", "SELECT * FROM final_sorting_equipment_check_list WHERE final_sorting_id = '" . $final_sorting_record_id . "' ORDER BY record_id, equipment_id ASC");
                    if ($equipment_check_res->num_rows > 0) {
                        while ($equipment_check = $equipment_check_res->fetch_assoc()) {
                            // check if equipment is already checked
                            $show = 0;
                            ?>
                            <tr>
                                <td>
                                    <?php echo $func->get_equipment($equipment_check["equipment_id"]); ?>
                                </td>
                                <td>
                                    <?php echo $equipment_check["question"]; ?>
                                </td>
                                <td>
                                    <select class="inputs">
                                        <option><?php echo $equipment_check["text"]; ?></option>
                                    </select>
                                </td>
                                <td>
                                    <?php echo $equipment_check["date_time"]; ?>
                                </td>
                                <td>
                                    <?php echo $func->get_username($equipment_check["user_id"]); ?>
                                </td>
                            </tr>
                            </tr>
                            <?php
                            $index++;
                        }
                    } else {
                        $index = 0;
                        $equipment_res = $db->query("equipment_list", "SELECT * FROM equipment_list WHERE 1 ORDER BY record_id ASC");
                        while ($equipment = $equipment_res->fetch_assoc()) {
                            $show = 1;
                            // check if equipment is already checked
                    
                            ?>
                            <tr>

                                <input type="text" hidden name="equipment_id[]" value="<?php echo $equipment["record_id"]; ?>">
                                <input type="text" hidden name="text_clean_<?php echo $equipment["record_id"]; ?>[]"
                                    value="Equipment appears clean and free from damage">
                                <td><?php echo $equipment["name"]; ?></td>
                                <td>Equipment appears clean and free from damage</td>
                                <td><select name="clean_<?php echo $equipment["record_id"]; ?>[]" class="inputs">
                                        <option></option>
                                        <option>YES</option>
                                        <option>NO</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td> <input type="text" hidden name="text_excessive_<?php echo $equipment["record_id"]; ?>[]"
                                        value="No signs of excessive wear, rust, or corrosion"></td>
                                <td>No signs of excessive wear, rust, or corrosion</td>
                                <td><select name="excessive_<?php echo $equipment["record_id"]; ?>[]" class="inputs">
                                        <option></option>
                                        <option>YES</option>
                                        <option>NO</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td> <input type="text" hidden name="text_guardsk_<?php echo $equipment["record_id"]; ?>[]"
                                        value="All guards, covers, and shields are securely fitted"></td>
                                <td>All guards, covers, and shields are securely fitted</td>
                                <td><select name="guardsk_<?php echo $equipment["record_id"]; ?>[]" class="inputs">
                                        <option></option>
                                        <option>YES</option>
                                        <option>NO</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td><input type="text" hidden name="text_Moving_<?php echo $equipment["record_id"]; ?>[]"
                                        value="Moving parts operate smoothly without obstruction"></td>
                                <td>Moving parts operate smoothly without obstruction</td>
                                <td><select name="Moving_<?php echo $equipment["record_id"]; ?>[]" class="inputs">
                                        <option></option>
                                        <option>YES</option>
                                        <option>NO</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td><input type="text" hidden name="text_Power_<?php echo $equipment["record_id"]; ?>[]"
                                        value="Power cables and plugs are intact and undamaged"></td>
                                <td>Power cables and plugs are intact and undamaged</td>
                                <td><select name="Power_<?php echo $equipment["record_id"]; ?>[]" class="inputs">
                                        <option></option>
                                        <option>YES</option>
                                        <option>NO</option>
                                    </select>
                                </td>
                            </tr>
                            <?php
                            $index++;
                        }
                    } ?>
                </tbody>
            </table>
        </div>

        <input type="button" value="SAVE LIST" class="submit_btn" onclick="save_equipment_check()" <?php if ($show == 0)
            echo "hidden"; ?>>
        <script>
            function save_equipment_check() {
                var formData = new FormData();
                document.querySelectorAll("#equipments_table input, #equipments_table select").forEach(function (input) {
                    if (input.value == '') {
                        input.style.border = "1px solid red";
                        input.focus();
                        return;
                    } else {
                        input.style.border = "1px solid green";

                        formData.append(input.name, input.value);
                    }
                });
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "equipment_final_sorting.ajax.php", true);
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        if (xhr.responseText == "1") {
                            alert("Successfully saved equipment check.");
                            location.reload();
                        } else {
                            alert("Failed to save equipment check." + xhr.responseText);
                            console.log(xhr.responseText);

                        }
                    } else {
                        console.log("Error: " + xhr.statusText);
                    }
                };
                xhr.send(formData);
            }
        </script>
        <br>
        <br>

        <style>
            .quality_process_popup {
                display: none;
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
            }

            .quality_process_content {
                /* background-color: #004aad */
                background-color: #528edf;
                margin: 2% auto;
                padding: 20px;
                border-radius: 10px;
                width: 90%;
                height: 90%;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
                position: relative;
                overflow-y: scroll;
            }

            .close-btn {
                position: absolute;
                top: 10px;
                right: 15px;
                font-weight: bolder;
                font-size: 5vw;
                cursor: pointer;
                color: white;
            }

            table {
                width: 95%;
                border-collapse: collapse;
            }

            th,
            td {
                padding: 10px;
                border: 3px solid black;
                text-align: left;
                background-color: white;
            }
        </style>

        <br><br><br>

        <input type="number" name="food_inspection_counter" id="food_inspection_counter" value="10" hidden>

        <div id="food_inspection_table" style="width: 95%; display: flex; justify-content: center;">
            <table>
                <?php
                // check 
                $check_res = $db->query("final_sorting_food_safety_inspections", "SELECT * FROM final_sorting_food_safety_inspections WHERE final_sorting_jobcard_no = '$final_sorting_record_id' ORDER BY record_id DESC LIMIT 1");
                if ($check_res->num_rows > 0) {
                    $check = $check_res->fetch_assoc();
                    $comment_res = $db->query("final_sorting_food_comments", "SELECT * FROM final_sorting_food_comments WHERE final_sorting_jobcard_no = '$final_sorting_record_id' ORDER BY record_id DESC LIMIT 1");
                    if ($comment_res->num_rows > 0) {
                        $comment = $comment_res->fetch_assoc();
                    } else {
                        $comment[] = "";
                    }
                } else {
                    $check[] = "";
                }
                ?>
                <tr>
                    <th colspan="3" style="text-align: center;">Food Safety Inspections</th>
                </tr>
                <tr>
                    <th>Food safety Inspection criteria/ points:</th>
                    <th>Select/ complete:</th>
                    <th>Comment:</th>
                </tr>
                <tr>
                    <td>Equipment Clean & sanitized</td>
                    <td>
                        <select name="equipment_cleaned" id="equipment_cleaned" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="equipmentCleaned()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td>
                        <input type="text" name="equipment_cleaned_comment" id="equipment_cleaned_comment"
                            class="inputs" style="margin: 0vw; width: 100%;">
                    </td>
                </tr>
                <script>
                    document.getElementById("equipment_cleaned").value = "<?php echo $check['equipment_cleaned']; ?>";
                    document.getElementById("equipment_cleaned_comment").value = "<?php echo $comment['equipment_cleaned_comment']; ?>";
                </script>
                <tr>
                    <td>Colour Sorters Clean?</td>
                    <td>
                        <select name="final_sorting_room_cleaned" id="final_sorting_room_cleaned" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="lopRoomCleaned()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="final_sorting_room_comment" id="final_sorting_room_comment"
                            class="inputs" style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("final_sorting_room_cleaned").value = "<?php echo $check['final_sorting_room_cleaned']; ?>";
                    document.getElementById("final_sorting_room_comment").value = "<?php echo $comment['final_sorting_room_comment']; ?>";
                </script>
                <tr>
                    <td>Areas of visual inspection, is lighting sufficient to detect defects?</td>
                    <td>
                        <select name="pest_activity_noted" id="pest_activity_noted" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="pestActivityNoted()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="pest_activity_comment" id="pest_activity_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("pest_activity_noted").value = "<?php echo $check['pest_activity_noted']; ?>";
                    document.getElementById("pest_activity_comment").value = "<?php echo $comment['pest_activity_comment']; ?>";
                </script>
                <tr>
                    <td>Are waste containers available & labelled? </td>
                    <td>
                        <select name="smells_taints_signs" id="smells_taints_signs" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="smellsTaintsSigns()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="smells_taints_signs_comment" id="smells_taints_signs_comment"
                            class="inputs" style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("smells_taints_signs").value = "<?php echo $check['smells_taints_signs']; ?>";
                    document.getElementById("smells_taints_signs_comment").value = "<?php echo $comment['smells_taints_signs_comment']; ?>";
                </script>
                <tr>
                    <td>Staff PPE in a good condition?</td>
                    <td>
                        <select name="air_dust_operational" id="air_dust_operational" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="airDustOperational()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="air_dust_operational_comment" id="air_dust_operational_comment"
                            class="inputs" style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("air_dust_operational").value = "<?php echo $check['air_dust_operational']; ?>";
                    document.getElementById("air_dust_operational_comment").value = "<?php echo $comment['air_dust_operational_comment']; ?>";
                </script>
                <tr>
                    <td>Air/ dust extraction system operational?</td>
                    <td>
                        <select name="visual_contamination_risks" id="visual_contamination_risks" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="visualContaminationRisks()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="visual_contamination_risks_comment"
                            id="visual_contamination_risks_comment" class="inputs" style="margin: 0vw; width: 100%;">
                    </td>
                </tr>
                <script>
                    document.getElementById("visual_contamination_risks").value = "<?php echo $check['visual_contamination_risks']; ?>";
                    document.getElementById("visual_contamination_risks_comment").value = "<?php echo $comment['visual_contamination_risks_comment']; ?>";
                </script>
                <tr>
                    <td>Shell separator & sieves clean?</td>
                    <td>
                        <select name="cheese_crates_clean" id="cheese_crates_clean" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="cheeseCratesClean()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="cheese_crates_clean_comment" id="cheese_crates_clean_comment"
                            class="inputs" style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("cheese_crates_clean").value = "<?php echo $check['cheese_crates_clean']; ?>";
                    document.getElementById("cheese_crates_clean_comment").value = "<?php echo $comment['cheese_crates_clean_comment']; ?>";
                </script>
                <tr>
                    <td>Air filtration/dust control working properly?</td>
                    <td>
                        <select name="trolley_traceability_available" id="trolley_traceability_available" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="trolleyTraceabilityAvailable()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="trolley_traceability_available_comment"
                            id="trolley_traceability_available_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("trolley_traceability_available").value = "<?php echo $check['trolley_traceability_available']; ?>";
                    document.getElementById("trolley_traceability_available_comment").value = "<?php echo $comment['trolley_traceability_available_comment']; ?>";
                </script>
                <tr>
                    <td>Personal hygiene (hands, gloves, PPE) checked??</td>
                    <td>
                        <select name="personal_hygiene" id="personal_hygiene" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="trolleyTraceabilityAvailable()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="personal_hygiene_comment" id="personal_hygiene_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("personal_hygiene").value = "<?php echo $check['personal_hygiene']; ?>";
                    document.getElementById("personal_hygiene_comment").value = "<?php echo $comment['personal_hygiene_comment']; ?>";
                </script>
                <tr>
                    <td>Tools sanitized and labelled? ?</td>
                    <td>
                        <select name="tools_sanitized" id="tools_sanitized" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="trolleyTraceabilityAvailable()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="tools_sanitized_comment" id="tools_sanitized_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("tools_sanitized").value = "<?php echo $check['tools_sanitized']; ?>";
                    document.getElementById("tools_sanitized_comment").value = "<?php echo $comment['tools_sanitized_comment']; ?>";
                </script>
            </table>
        </div>
        <div style="display: flex; justify-content: center;">
            <button type="button" onclick="halfway_save()" class="submit_btn">SAVE</button>
        </div>
        <br><br><br>

        <div id="Operation_procedure_table" style="width: 90%; display: flex; justify-content: center;">
            <table>
                <tr>
                    <th>Standard Operating procedure: </th>
                    <th> Sampling of nuts for evaluation</th>
                </tr>
                <tr>
                    <td>Step 1</td>
                    <td>Take a random sample of cracked nuts (e.g., 100–200 kernels) per batch or hourly from the
                        cracking output</td>
                </tr>
                <tr>
                    <td> Step 2</td>
                    <td>Look for signs of over-cracking, broken pieces, or stuck kernels</td>
                </tr>
                <tr>
                    <td>Step 3</td>
                    <td>Count how many are: whole, half, broken, crushed, or with shell fragments</td>
                </tr>
                <tr>
                    <td>Step 4</td>
                    <td>% of whole + half kernels vs. total</td>
                </tr>
                <tr>
                    <td>Step 5</td>
                    <td>If breakage is high (>10–15%), adjust cracker pressure, roller gap, or shell moisture- consult
                        operations manager</td>
                </tr>
                <tr>
                    <td>Step 6</td>
                    <td>For the inspection of the magnets at end of shift- please indicate the number of the magnet, and
                        then if metal was detected</td>
                </tr>
            </table>
        </div>

        <style>
            .guidance_popup {
                display: none;
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
            }

            .guidance_content {
                /* background-color: #004aad */
                background-color: #528edf;
                margin: 3% auto;
                padding: 20px;
                border-radius: 10px;
                width: 80%;
                height: 85%;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
                position: relative;
                /* overflow-y: scroll; */
            }

            .quality_process_popup {
                display: none;
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
            }

            .quality_process_content {
                /* background-color: #004aad */
                background-color: #528edf;
                margin: 2% auto;
                padding: 20px;
                border-radius: 10px;
                width: 90%;
                height: 90%;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
                position: relative;
                overflow-y: scroll;
            }

            .close-btn {
                position: absolute;
                top: 10px;
                right: 15px;
                font-weight: bolder;
                font-size: 5vw;
                cursor: pointer;
                color: white;
            }

            .close-btn {
                position: absolute;
                top: 10px;
                right: 15px;
                font-weight: bolder;
                font-size: 5vw;
                cursor: pointer;
                color: white;
            }

            table {
                width: 95%;
                border-collapse: collapse;
            }

            th,
            td {
                padding: 10px;
                border: 3px solid black;
                text-align: left;
                background-color: white;
            }
        </style>
        <br>
        <h1>QUALITY CONTROL HISTORY</h1>
        <?php $quality_res = $db->query("final_sorting_quality_control", "SELECT * FROM final_sorting_quality_control WHERE final_sorting_id = '" . $final_sorting_record_id . "'");
        if ($quality_res->num_rows > 0) {
            while ($quality = $quality_res->fetch_assoc()) {
                ?>
                <div style="width: 90%; display: flex; justify-content: center;">
                    <div class="quality_process_content">
                        <table>
                            <tr>
                                <th>0%</th>
                                <th>
                                    < 0.5%</th>
                                <th>
                                    < 0.5%</th>
                                <th>0%</th>
                                <th>
                                    <= 10 - 15%</th>
                                <th>
                                    < 1%</th>
                                <th>
                                    < 1-2%</th>
                            </tr>
                            <tr>
                                <th>Mouldy Kernel</th>
                                <th>Germinated Kernel</th>
                                <th>Insect-damaged (e.g., stink bug, borer)</th>
                                <th>Rancid/off-smell kernel</th>
                                <th>Foreign matter (FM: shell, stone, hair, etc.)</th>
                                <th>Shell in kernel (adhering)</th>
                                <th>Un-cracked Nuts (shell in tact)</th>
                            </tr>
                            <tr>
                                <td><input type="number" class="inputs" step="0.01" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['mouldy_kernal']; ?>">
                                </td>
                                <td><input type="number" class="inputs" step="0.01" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['germinated_kernal']; ?>"></td>
                                <td><input type="number" class="inputs" step="0.01" style="margin: 0vw; width: 100%;"
                                        value="<?php echo $quality['insect_damaged']; ?>">
                                </td>
                                <td><input type="number" class="inputs" step="0.01" style="margin: 0vw; width: 100%;"
                                        value="<?php echo $quality['rancid_smell_kernal']; ?>">
                                </td>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw; width: 100%;"
                                        value="<?php echo $quality['foreign_matter']; ?>"></td>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw; width: 100%;"
                                        value="<?php echo $quality['shell_in_kernal']; ?>"></td>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw; width: 100%;"
                                        value="<?php echo $quality['uncracked_nuts']; ?>"></td>
                            </tr>
                        </table>

                        <br>

                        <table>
                            <tr>
                                <th>0%(rework required)</th>
                                <th>1.5 - 3.5%</th>
                                <th>18 -24°C</th>
                                <th>45 - 55 RH</th>
                                <th>Metal Fragments-Capture on FO library</th>
                                <th></th>
                            </tr>
                            <tr>
                                <th>Crushed/ missing kernel</th>
                                <th>Moisture %</th>
                                <th>Env. Temperature</th>
                                <th>Env. Humidity</th>
                                <th>Magnet inspection, end of shift</th>
                                <th>Person Inspecting</th>
                                <th>signature</th>
                            </tr>
                            <tr>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['crushed_missing_kernal']; ?>"></td>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['moisture']; ?>"></td>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['env_temperature']; ?>"></td>
                                <td><input type="number" step="0.01" class="inputs" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['env_humidity']; ?>"></td>
                                <td>
                                    <select style="margin: 0vw;width: 100%;"
                                        id="magnet_inspection_<?php echo $quality['record_id']; ?>" class="inputs">
                                        <option value=""></option>
                                        <option value="DETECTED">DETECTED</option>
                                        <option value="NOT DETECTED">NOT DETECTED</option>
                                    </select>
                                    <script>
                                        document.getElementById("magnet_inspection_<?php echo $quality['record_id']; ?>").value = "<?php echo $quality['magnet_inspection']; ?>";
                                    </script>
                                </td>
                                <td>
                                    <?php
                                    $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '" . $quality['person_inspecting'] . "'");
                                    $user = $user_res->fetch_assoc()['username'];
                                    ?>
                                    <input type="text" readonly step="0.01" class="inputs" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $user ?>">
                                </td>
                                <td>
                                    <img src="<?php echo $quality['signature']; ?>" alt="signature" style="width: 100px;">
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <?php
            }
        }

        ?>


        <div id="quality_process_control_table" class="quality_process_popup"
            style="width: 100%; justify-content: center;">
            <div class="quality_process_content">
                <span class="close-btn" onclick="close_quality_control()">&times;</span>
                <h3>QUALIITY & PROCESS CONTROL TRACK INFORMATION:</h3>
                <div style="width: 100%; display: flex; flex-direction: row; justify-content: space-evenly;">
                    <div style="display: flex; flex-direction: column;">
                        <?php
                        $final_sorting_id->add();
                        $datetime = new label();
                        $datetime->for("datetime_label");
                        $datetime->value("Date & time");
                        $datetime->add();
                        ?>
                        <br>
                        <input type="datetime-local" name="date_time" id="date_time" class="inputs" style="margin: 0vw;"
                            value="<?php echo $date_time; ?>">
                    </div>
                    <div style="display: flex; flex-direction: column;">
                        <?php
                        $shift_label = new label();
                        $shift_label->for("shift_label");
                        $shift_label->value("Shift (Day / Night)");
                        $shift_label->add();
                        ?>
                        <br>
                        <select name="shift" id="shift" class="inputs" style="margin: 0vw;">
                            <option value=""></option>
                            <option value="D">DAY</option>
                            <option value="N">NIGHT</option>
                        </select>
                    </div>
                    <div style="display: flex; flex-direction: column;">
                        <?php
                        $sample_size_label = new label();
                        $sample_size_label->for("sample_size_label");
                        $sample_size_label->value("Sample Size (Kg)");
                        $sample_size_label->add();
                        ?>
                        <br>
                        <input type="number" name="sample_size" id="sample_size" class="inputs" step="0.01"
                            style="margin: 0vw;">
                    </div>
                </div>

                <h4>SPECIFICATION / GUIDANCE ON ELEVATION
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
                        <?php
                        $product_samples_point_label = new label();
                        $product_samples_point_label->for("product_samples_point_label");
                        $product_samples_point_label->value("Product samples point");
                        $product_samples_point_label->add();
                        ?>
                        <br>
                        <?php
                        $product_samples_point = new select();
                        $product_samples_point->name("product_samples_point");
                        $product_samples_point->id("product_samples_point");
                        $product_samples_point->class("inputs");
                        $product_samples_point->style("width: 20vw;");
                        $product_samples_point->fill_from_db("product_sample_point", "record_id", "name");
                        $product_samples_point->add();
                        ?>
                    </div>

                    <br>
                    <br>

                    <table>
                        <tr>
                            <th>0%</th>
                            <th>
                                < 0.5%</th>
                            <th>
                                < 0.5%</th>
                            <th>0%</th>
                            <th>
                                <= 10 - 15%</th>
                            <th>
                                < 1%</th>
                            <th>
                                < 1-2%</th>
                        </tr>
                        <tr>
                            <th>Mouldy Kernel</th>
                            <th>Germinated Kernel</th>
                            <th>Insect-damaged (e.g., stink bug, borer)</th>
                            <th>Rancid/off-smell kernel</th>
                            <th>Foreign matter (FM: shell, stone, hair, etc.)</th>
                            <th>Shell in kernel (adhering)</th>
                            <th>Un-cracked Nuts (shell in tact)</th>
                        </tr>
                        <tr>
                            <td><input type="number" name="mouldy_kernal" id="mouldy_kernal" class="inputs" step="0.01"
                                    style="margin: 0vw;width: 100%;">
                            </td>
                            <td><input type="number" name="germinated_kernal" id="germinated_kernal" class="inputs"
                                    step="0.01" style="margin: 0vw;width: 100%;"></td>
                            <td><input type="number" name="insect_damaged" id="insect_damaged" class="inputs"
                                    step="0.01" style="margin: 0vw; width: 100%;">
                            </td>
                            <td><input type="number" name="rancid_smell_kernal" id="rancid_smell_kernal" class="inputs"
                                    step="0.01" style="margin: 0vw; width: 100%;">
                            </td>
                            <td><input type="number" name="foreign_matter" id="foreign_matter" step="0.01"
                                    class="inputs" style="margin: 0vw; width: 100%;"></td>
                            <td><input type="number" name="shell_in_kernal" id="shell_in_kernal" step="0.01"
                                    class="inputs" style="margin: 0vw; width: 100%;"></td>
                            <td><input type="number" name="uncracked_nuts" id="uncracked_nuts" step="0.01"
                                    class="inputs" style="margin: 0vw; width: 100%;"></td>
                        </tr>
                    </table>

                    <br><br>

                    <table>
                        <tr>
                            <th>0%(rework required)</th>
                            <th>1.5 - 3.5%</th>
                            <th>18 -24°C</th>
                            <th>45 - 55 RH</th>
                            <th>Metal Fragments-Capture on FO library</th>
                            <th></th>
                        </tr>
                        <tr>
                            <th>Crushed/ missing kernel</th>
                            <th>Moisture %</th>
                            <th>Env. Temperature</th>
                            <th>Env. Humidity</th>
                            <th>Magnet inspection, end of shift</th>
                            <th>Person Inspecting</th>
                        </tr>
                        <tr>
                            <td><input type="number" name="crushed_missing_kernal" id="crushed_missing_kernal"
                                    step="0.01" class="inputs" style="margin: 0vw;width: 100%;"></td>
                            <td><input type="number" name="moisture" id="moisture" step="0.01" class="inputs"
                                    style="margin: 0vw;width: 100%;"></td>
                            <td><input type="number" name="env_temperature" id="env_temperature" step="0.01"
                                    class="inputs" style="margin: 0vw;width: 100%;"></td>
                            <td><input type="number" name="env_humidity" id="env_humidity" step="0.01" class="inputs"
                                    style="margin: 0vw;width: 100%;"></td>
                            <td>
                                <select name="magnet_inspection" style="margin: 0vw;width: 100%;" id="magnet_inspection"
                                    class="inputs">
                                    <option value=""></option>
                                    <option value="DETECTED">DETECTED</option>
                                    <option value="NOT DETECTED">NOT DETECTED</option>
                                </select>
                            </td>
                            <td>
                                <?php
                                $person_inspecting = new select();
                                $person_inspecting->name("person_inspecting");
                                $person_inspecting->id("person_inspecting");
                                $person_inspecting->class("inputs");
                                $person_inspecting->style("margin: 0vw;width: 100%;");
                                $person_inspecting->fill_from_db("users", "record_id", "username");
                                $person_inspecting->add();
                                ?>
                            </td>
                        </tr>
                    </table>

                    <br>
                    <div style="display: flex; flex-direction: row; width: 100%; justify-content: center;">
                        <!-- <button type="button" id="save_btn" class="submit_btn">SIGN</button> -->
                        <button type="button" id="clear_signature" onclick="signaturePad.clear();"
                            class="submit_btn">CLEAR</button>
                    </div>
                    <h2>SIGNATURE</h2>
                    <canvas id="qa_signature_pad" class="signature-pad" width=400 height=200
                        style='background-color:white;border-radius:20px;'></canvas><br>

                    <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
                    <script>
                        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>

                    <button type="button" onclick="submit_quality_control()" class="submit_btn">SAVE</button>
                    <br>
                    <button type="button" onclick="close_quality_control()" class="submit_btn">CLOSE</button>
            </div>
            <script>
                signaturePad = new SignaturePad(document.getElementById('qa_signature_pad'));

                function submit_quality_control() {
                    event.preventDefault();
                    // Use the existing signaturePad instance (do not reinitialize)
                    var canvas = document.getElementById('qa_signature_pad');

                    var formData = new FormData();
                    var inputs = document.querySelectorAll("#quality_process_control_table input, #quality_process_control_table select");

                    inputs.forEach(function (input) {
                        formData.append(input.name, input.value);
                    });

                    if (signaturePad.isEmpty()) {
                        alert("Please provide signature first.");
                        return;
                    }

                    var dataURL = signaturePad.toDataURL('image/png');
                    var blob = dataURLToBlob(dataURL);
                    formData.append('signature', blob, 'signature.png');
                    formData.append('type', 'quality_control');

                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "add_quality_control_final_sorting.php", true);
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            if (xhr.responseText.trim() === "1") {
                                alert("Successfully saved quality control.");
                                window.location.reload();
                            } else {
                                alert("Failed to save quality control.");
                                console.log(xhr.responseText);
                            }
                        } else {
                            alert("Server error: " + xhr.status);
                        }
                    };
                    xhr.send(formData);
                }
            </script>
        </div>
        <input type="button" value="QUALIITY CONTROL" class="submit_btn" onclick="open_quality_control()">

        <br>
        <input type="button" value="GUIDANCE SPECS" class="submit_btn" onclick="open_Popup_1()">
        <br>

        <div id="guidance_popup1" class="guidance_popup">
            <div class="guidance_content">
                <span class="close-btn" onclick="close_Popup_1()">&times;</span>
                <h2>GUIDANCE/ SPECIFICATION & DEFINATION</h2>
                <h3>Please consult the maintenance artisan or the operations manager when out of
                    specification <br>
                    results
                    are
                    recorded in order for the process and equipment to be altered. </h3>

                <table>
                    <tr>
                        <th style="color: red;">PROBLEM</th>
                        <th style="color: orange;">LIKELY CAUSE</th>
                        <th style="color: green;">CORRECTION</th>
                    </tr>
                    <tr>
                        <td>Too many broken kernels</td>
                        <td>Cracking force too high</td>
                        <td>Reduce roller pressure or adjust spacing</td>
                    </tr>
                    <tr>
                        <td>Shell not cracking open</td>
                        <td>Shell too dry or cracker not aligned</td>
                        <td>Adjust moisture (~10–13% ideal) or realign machine</td>
                    </tr>
                    <tr>
                        <td>Shell fragments in kernel</td>
                        <td>Poor shell separation</td>
                        <td>Check air classifier or vibrating sieve settings</td>
                    </tr>
                    <tr>
                        <td>Crushed + discolored kernels</td>
                        <td>Old nuts or over-dried product</td>
                        <td>Recheck drying specs, avoid over-dehydration</td>
                    </tr>
                </table>

                <br>

                <table>
                    <tr>
                        <th style="color: green;">GOOD CRACK</th>
                        <th style="color: red;">POOR CRACK</th>
                    </tr>
                    <tr>
                        <td>Shell is cleanly split open</td>
                        <td>Over-cracked: Kernel is crushed, broken, or bruised</td>
                    </tr>
                    <tr>
                        <td>Kernel is intact (whole) or minimally damaged</td>
                        <td>Under-cracked: Shell not fully broken, kernel stuck</td>
                    </tr>
                    <tr>
                        <td>Minimal adhering shell or husk on the kernel</td>
                        <td>Adhering shell pieces: Risk of contamination</td>
                    </tr>
                    <tr>
                        <td>No deep gouges, crushing, or bruising on kernel</td>
                        <td>Multiple fractures in kernel: Reduces grading value</td>
                    </tr>
                </table>
            </div>
        </div>

        <input type="number" name="batch_output_counter" id="batch_output_counter" value="14" hidden>

        <div id="batch_output_summary_table" style="width: 90%;">
            <?php
            $summary_res = $db->query("final_sorting_batch_summary", "SELECT * FROM final_sorting_batch_summary WHERE final_sorting_jobcard_no = '$final_sorting_record_id'");
            if ($summary_res->num_rows > 0) {
                $summary = $summary_res->fetch_assoc();
            } else {
                $summary['kernal_size_accuracy'] = 0;
                $summary['reject'] = 0;
                $summary['broken_kernal'] = 0;
                $summary['kernal_breakage_rate'] = 0;
                $summary['shell_fragment_contamination'] = 0;
                $summary['moisture'] = 0;
                $summary['visual_defect_rate'] = 0;
                $summary['whole_kernal_recovery'] = 0;
                $summary['colour_final_sorting_accuracy'] = 0;
                $summary['shell_kernal_contamination'] = 0;
                $summary['whole_kernal'] = 0;
                $summary['kernal_stuck_shell'] = 0;
                $summary['halves'] = 0;
                $summary['chips_broken'] = 0;
                $summary['actions_taken'] = 0;
            }
            ?>
            <table style="width: 100%;">
                <tr>
                    <th colspan="6" style="text-align: center;">
                        <h3 style="margin: 0vw;">Batch Output Calculation Summary</h3>
                    </th>
                </tr>
                <tr>
                    <td>
                        Kernel size separation accuracy (per grade specification)
                    </td>
                    <td><input type="number" name="kernal_size_accuracy" id="kernal_size_accuracy" class="inputs"
                            style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['kernal_size_accuracy']; ?>"></td>
                    <td>
                        Reject / waste
                    </td>
                    <td><input type="number" name="reject" id="reject" class="inputs" style="margin: 0vw;width: 100%;"
                            step="0.01" value="<?php echo $summary['reject']; ?>"></td>
                    </td>
                </tr>
                <tr>
                    <td>
                        Broken Kernel % (≤ 10% [for whole grade])
                    </td>

                    <td><input type="number" name="broken_kernal" id="broken_kernal" class="inputs"
                            style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['broken_kernal']; ?>"></td>
                    </td>
                    <td>
                        Kernal Breakage rate (≤ 10–15%)
                    </td>

                    <td><input type="number" name="kernal_breakage_rate" id="kernal_breakage_rate" class="inputs"
                            style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['kernal_breakage_rate']; ?>"></td>
                </tr>
                <tr>
                    <td>
                        Shell fragment contamination (0%)
                    </td>

                    <td><input type="number" name="shell_fragment_contamination" id="shell_fragment_contamination"
                            class="inputs" style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['shell_fragment_contamination']; ?>"></td>
                    <td>
                        Moisture (in-shell 1.5–3.0%)
                    </td>

                    <td><input type="number" name="moisture" id="moisture" class="inputs"
                            style="margin: 0vw;width: 100%;" step="0.01" value="<?php echo $summary['moisture']; ?>">
                    </td>
                </tr>
                <tr>
                    <td>
                        Visual defect rate (per 100g) (< 0.5%)</td>

                    <td><input type="number" name="visual_defect_rate" id="visual_defect_rate" class="inputs"
                            style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['visual_defect_rate']; ?>"></td>
                    <td>
                        Whole kernel recovery (≥ 85%)
                    </td>

                    <td><input type="number" name="whole_kernal_recovery" id="whole_kernal_recovery" class="inputs"
                            style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['whole_kernal_recovery']; ?>"></td>
                </tr>
                <tr>
                    <td>
                        Colour final_sorting Accuracy
                    </td>
                    <td><input type="number" name="colour_final_sorting_accuracy" id="colour_final_sorting_accuracy"
                            class="inputs" style="margin: 0vw;width: 100%;" step="0.01"
                            value="<?php echo $summary['colour_final_sorting_accuracy']; ?>"></td>
                    <td>
                        Shell in kernel contamination (0%)
                    </td>

                    <td><input type="number" name="shell_kernal_contamination" id="shell_kernal_contamination"
                            class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['shell_kernal_contamination']; ?>" step="0.01"></td>
                </tr>
                <tr>
                    <td>
                        Whole Kernal
                    </td>

                    <td><input type="number" name="whole_kernal" id="whole_kernal" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['whole_kernal']; ?>"
                            step="0.01"></td>
                    <td>
                        Kernel stuck in shell (< 1–2%)</td>

                    <td><input type="number" name="kernal_stuck_shell" id="kernal_stuck_shell" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['kernal_stuck_shell']; ?>"
                            step="0.01"></td>
                </tr>
                <tr>
                    <td>
                        Halves
                    </td>
                    <td><input type="number" name="halves" id="halves" class="inputs" style="margin: 0vw;width: 100%;"
                            step="0.01" value="<?php echo $summary['halves']; ?>"></td>
                    </td>
                    <td colspan="2"></td>

                </tr>
                <tr>
                    <td>
                        Chips / broken
                    </td>
                    <td><input type="number" name="chips_broken" id="chips_broken" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['chips_broken']; ?>"
                            step="0.01"></td>
                    <td>Actions taken for NC product: </td>
                    <td colspan="2"><input type="text" name="actions_taken" id="actions_taken" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['actions_taken']; ?>"
                            step="0.01"></td>
                </tr>
            </table>
        </div>

        <br><br>

        <div style="display: flex; flex-direction: column;">
            <?php
            $date_jobcard_closed_label = new label();
            $date_jobcard_closed_label->for("date_jobcard_closed");
            $date_jobcard_closed_label->value("Date Jobcard Closed");
            $date_jobcard_closed_label->add();

            $date_jobcard_closed = new input();
            $date_jobcard_closed->type("datetime-local");
            $date_jobcard_closed->id("jobcard_closed");
            $date_jobcard_closed->name("jobcard_closed");
            $date_jobcard_closed->value($final_sorting['date_jobcard_closed']);
            $date_jobcard_closed->add();
            ?>
        </div>

        <div style="display: flex; flex-direction: row; justify-content: space-around; width: 90%;">
            <div style="display: flex; flex-direction: column;align-items: center;">
                <?php
                $product_supervisor_label = new label();
                $product_supervisor_label->for("product_supervisor_signature_label");
                $product_supervisor_label->value("Product Supervisor");
                $product_supervisor_label->add();

                $production_supervisor = new select();
                $production_supervisor->name("production_supervisor");
                $production_supervisor->id("production_supervisor");
                $production_supervisor->class("inputs");
                $production_supervisor->style("width: 20vw;");
                $production_supervisor->fill_from_db("users", "record_id", "username");
                $production_supervisor->value_from_db("final_sorting_jobcard", "production_supervisor", "record_id = $final_sorting_record_id");
                $production_supervisor->add();
                ?>
                <?php if ($final_sorting['supervisor_signature'] != null) { ?>
                    <img src="<?php echo $final_sorting['supervisor_signature']; ?>" width="400" height="200">
                <?php } else { ?>
                    <canvas id="ps_signature_pad" class="signature-pad" width="400" height="200"
                        style="background-color:white;border-radius:20px;"></canvas>
                    <br>
                    <div style="display: flex; flex-direction: row; width: 50%; justify-content: center;">
                        <button type="button" id="clear_ps_signature" class="submit_btn">CLEAR</button>
                    </div>
                    <script>
                        // Initialize both signature pads

                        const psPad = new SignaturePad(document.getElementById('ps_signature_pad'));
                        document.getElementById('clear_ps_signature').addEventListener('click', () => psPad.clear());
                    </script>
                <?php } ?>
            </div>
            <div style="display: flex; flex-direction: column;align-items: center;">
                <?php
                $quality_control__label = new label();
                $quality_control__label->for("quality_control_signature_label");
                $quality_control__label->value("Quality Control");
                $quality_control__label->add();

                $quality_control_name = new select();
                $quality_control_name->name("quality_control");
                $quality_control_name->id("quality_control");
                $quality_control_name->class("inputs");
                $quality_control_name->style("width: 20vw;");
                $quality_control_name->fill_from_db("users", "record_id", "username");
                $quality_control_name->value_from_db("final_sorting_jobcard", "quality_controll", "record_id = $final_sorting_record_id");
                $quality_control_name->add();

                ?>

                <?php if ($final_sorting['quality_controller_signature'] != null) { ?>
                    <img src="<?php echo $final_sorting['quality_controller_signature']; ?>" width="400" height="200">
                <?php } else { ?>
                    <canvas id="qc_signature_pad" class="signature-pad" width="400" height="200"
                        style="background-color:white;border-radius:20px;"></canvas>
                    <br>
                    <div style="display: flex; flex-direction: row; width: 50%; justify-content: center;">
                        <button type="button" id="clear_qc_signature" class="submit_btn">CLEAR</button>
                    </div>
                    <script>
                        const qcPad = new SignaturePad(document.getElementById('qc_signature_pad'));
                        // Clear buttons
                        document.getElementById('clear_qc_signature').addEventListener('click', () => qcPad.clear());
                    </script>
                <?php } ?>

            </div>
        </div>

        <div style="display: flex; justify-content: center;">
            <button type="button" id="submit_form_btn" class="submit_btn">UPDATE</button>
        </div>

    </div>
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
    <script>


        // Convert DataURL 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: dataURL.split(',')[0].split(':')[1].split(';')[0]
            });
        }

        // Final form submission
        document.getElementById('submit_form_btn').addEventListener('click', function () {
            const form = document.getElementById('final_sorting_form');
            try {
                if (qcPad.isEmpty()) {

                } else {


                    // Remove previous hidden inputs if any
                    document.querySelectorAll('.signature_hidden_input').forEach(e => e.remove());


                    const qcData = qcPad.toDataURL('image/png');

                    const qcInput = document.createElement('input');
                    qcInput.type = 'hidden';
                    qcInput.name = 'qc_signature';
                    qcInput.value = qcData;
                    qcInput.classList.add('signature_hidden_input');

                    form.appendChild(qcInput);
                }
            } catch (e) { }
            try {
                if (psPad.isEmpty()) {

                } else {


                    // Remove previous hidden inputs if any
                    document.querySelectorAll('.signature_hidden_input').forEach(e => e.remove());

                    // Create hidden fields for each signature
                    const psData = psPad.toDataURL('image/png');

                    const psInput = document.createElement('input');
                    psInput.type = 'hidden';
                    psInput.name = 'ps_signature';
                    psInput.value = psData;
                    psInput.classList.add('signature_hidden_input');

                    form.appendChild(psInput);
                }
            } catch (e) { }

            // Submit the form
            form.submit();
        });

        function open_Popup_1() {
            document.getElementById("guidance_popup1").style.display = "block";
        }

        function close_Popup_1() {
            document.getElementById("guidance_popup1").style.display = "none";
        }

        function open_quality_control() {
            document.getElementById("quality_process_control_table").style.display = "block";
        }

        function close_quality_control() {
            document.getElementById("quality_process_control_table").style.display = "none";
        }

        function addEquipmentRow() {
            // Use the number of children already inside #equipment_row to get a unique index
            var i = document.getElementById("equipment_counter").value;

            // Create wrapper div for this row
            var newDiv = document.createElement("div");
            newDiv.style.display = "flex";
            newDiv.style.flexDirection = "row";
            newDiv.style.borderBottom = "4px solid black";
            newDiv.style.width = "100%";

            // First Column: Equipment Input
            var row1 = document.createElement("div");
            row1.style.width = "25%";
            var select1 = document.createElement("input");
            select1.name = "equipment_" + i;
            select1.id = "equipment_" + i;
            select1.className = "inputs";
            select1.placeholder = "Equipment";
            select1.style.width = "90%";

            row1.appendChild(select1);
            newDiv.appendChild(row1);

            // Second Column: Verify Settings Input
            var row2 = document.createElement("div");
            row2.style.width = "50%";
            row2.style.borderLeft = "2px solid black";
            row2.style.borderRight = "2px solid black";

            var input2 = document.createElement("input");
            input2.type = "text";
            input2.name = "verify_settings_" + i;
            input2.id = "verify_settings_" + i;
            input2.className = "inputs";
            input2.placeholder = "List of settings to be verified before start-up";
            input2.style.width = "90%";
            row2.appendChild(input2);
            newDiv.appendChild(row2);

            // Third Column: Accuracy Select
            var row3 = document.createElement("div");
            row3.style.width = "25%";

            var select = document.createElement("select");
            select.name = "accurate_" + i;
            select.id = "accurate_" + i;
            select.className = "inputs";
            select.style.width = "90%";

            var options = ["", "YES", "NO"];
            options.forEach(function (val) {
                var option = document.createElement("option");
                option.value = val;
                option.text = val === "" ? "SELECT ACCURACY" : val;
                select.appendChild(option);
            });

            row3.appendChild(select);
            newDiv.appendChild(row3);

            // Append the whole row
            document.getElementById("equipment_row").appendChild(newDiv);

            // Increment the counter
            document.getElementById("equipment_counter").value = parseInt(document.getElementById("equipment_counter").value) + 1;
        }

        function halfway_save() {
            const form = document.getElementById('final_sorting_form');

            const psInput = document.createElement('input');
            psInput.type = 'hidden';
            psInput.name = 'save_halfway';
            psInput.value = '1';

            form.appendChild(psInput);

            // Submit the form
            form.submit();
        }

    </script>
</form>