<?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("cracking_jobcard", "SELECT * FROM cracking_jobcard WHERE record_id = '" . $_GET['record_id'] . "' ");
    $cracking = $lop_res->fetch_assoc();
    $cracking_record_id = $cracking['record_id'];

    $batch_no_res = $db->query("batch_data", "SELECT * FROM batch_data WHERE record_id = $cracking_record_id");
    $batch_no = $batch_no_res->fetch_assoc();
} else {

    $lop_res = $db->query("cracking_jobcard", "SELECT jobcard_no FROM cracking_jobcard ORDER BY record_id DESC LIMIT 1");
    if ($lop_res->num_rows == 0) {
        $jobcard_no = 1;
    } else {
        $cracking = $lop_res->fetch_assoc();
        $jobcard_no = $cracking['jobcard_no'] + 1;
    }
    $cracking_record_id = $db->query("cracking_jobcard", "INSERT INTO cracking_jobcard (jobcard_no) VALUES ('" . $jobcard_no . "')");
    echo "<script>window.location.href = 'cracking.php?record_id=" . $cracking_record_id . "'</script>";
}

$product_id_label = new label();
$product_id_label->for("product_id_label");
$product_id_label->value("Product Identification");

$product_id = new select();
$product_id->name("product_id");
$product_id->id("product_id");
$product_id->style("width: 20%");
$product_id->fill_from_db("variety", "record_id", "name");
$product_id->value_from_db("cracking_jobcard", "product_id", "record_id = $cracking_record_id");

$cracking_id = new input();
$cracking_id->type("hidden");
$cracking_id->name("cracking_id");
$cracking_id->id("cracking_id");
$cracking_id->placeholder("LOP JC NO");
$cracking_id->value($cracking_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($cracking_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($cracking['jobcard_date_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($cracking['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 select();
$batch_no->name("batch_no");
$batch_no->id("batch_no");
$batch_no->style("width: 20%");
$batch_no->fill_from_db("batch_data", "batch_no", "batch_no");
$batch_no->value_from_db("batch_data", "batch_no", "record_id = $cracking_record_id");


// 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");
$submit_btn->onclick("validateForm()");

?>

<form id="cracking_form" action="save_cracking.php" method="post">
    <div class="form_down">
        <h1>CRAKING JOBCARD</h1>

        <?php
        $record_id->add();
        $jobcard_date_opened_label->add();
        $jobcard_date_opened->add();

        $batch_no_label->add();
        $batch_no->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();

        ?>
        <div style="display: flex; justify-content: center;">
            <button type="button" onclick="halfway_save()" style="width: 100%;" class="submit_btn">SAVE</button>
        </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);
            }

            .equipment_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;
            }

            .equipment_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;
            }

            .equipment_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><br>

        <h1>EQUIPMENT CHECK HISTORY</h1>
        <div style="width: 90%; display: flex; justify-content: center;">
            <div class="quality_process_content">
                <?php
                $batch_no_res = $db->query("batch_data", "SELECT * FROM batch_data WHERE record_id = $cracking_record_id ORDER BY batch_no DESC LIMIT 1");
                $batch_data = $batch_no_res->fetch_assoc();

                $equipment_res = $db->query("cracking_equipment_check_list", "SELECT * FROM cracking_equipment_check_list WHERE batch_no = '{$batch_data['batch_no']}' GROUP BY check_no");

                if ($equipment_res->num_rows > 0) {
                    ?>
                    <table>
                        <tr>
                            <th>USER</th>
                            <th>CHECK NO</th>
                            <th>DATE TIME</th>
                            <th></th>
                        </tr>
                        <?php
                        while ($equipment = $equipment_res->fetch_assoc()) {

                            $equipment_data_res = $db->query("equipment_list", "SELECT * FROM equipment_list WHERE record_id = '" . $equipment['equipment_id'] . "'");
                            $equipment_data = $equipment_data_res->fetch_assoc();

                            $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '" . $equipment['user_id'] . "'");
                            $user = $user_res->fetch_assoc();
                            ?>
                            <tr>
                                <td><?php echo $user['username']; ?></td>
                                <td><?php echo $equipment['check_no']; ?></td>
                                <td><?php echo $equipment['date_time']; ?></td>
                                <td>
                                    <button type="button" class="submit_btn"
                                        onclick="window.location.href='../reports/equipment.pdf.php?record_id=<?php echo $cracking_record_id; ?>&check_no=<?php echo $equipment['check_no']; ?>'">
                                        PDF
                                    </button>
                                </td>
                            </tr>
                            <?php
                        }
                        ?>
                    </table>
                    <?php
                }
                ?>
                <br>
            </div>
        </div>

        <input type="button" value="CHECK EQUIPMENT" class="submit_btn" onclick="open_equipment()">

        <div id="equipment_popup" class="equipment_popup">
            <div class="equipment_content">
                <span class="equipment_close_btn" onclick="close_equipment()">&times;</span>

                <h1>EQUIPMENT CHECKLIST</h1>
                <br>
                <div id="equipments_table"
                    style="display: flex; flex-direction: column; align-items: center; width: 100%;">
                    <?php

                    $cracking_jobcard_res = $db->query("cracking_jobcard", "SELECT * FROM cracking_jobcard WHERE record_id = '" . $_GET['record_id'] . "' ");
                    $cracking_jobcard = $cracking_jobcard_res->fetch_assoc();

                    $equipment_res = $db->query("cracking_equipment_check_list", "SELECT * FROM cracking_equipment_check_list WHERE batch_no = '{$cracking_jobcard['batch_no']}' ORDER BY check_no DESC LIMIT 1");

                    if ($equipment_res->num_rows < 0) {
                        $check_no = 1;
                        $batch_no = 1;
                    } else {
                        $batch_row = $equipment_res->fetch_assoc();
                        $check_no_db = is_numeric($batch_row['check_no']) ? (int) $batch_row['check_no'] : 0;

                        $check_no = $check_no_db + 1;
                        // echo $check_no;
                        $batch_no = $batch_row['batch_no'];
                        // echo $batch_no;
                    }


                    $lop_res = $db->query("cracking_jobcard", "SELECT jobcard_no FROM cracking_jobcard ORDER BY record_id DESC LIMIT 1");
                    if ($lop_res->num_rows == 0) {
                        $jobcard_no = 1;
                    } else {
                        $cracking = $lop_res->fetch_assoc();
                        $jobcard_no = $cracking['jobcard_no'] + 1;
                    }
                    ?>

                    <input type="hidden" name="check_no" value="<?php echo $check_no; ?>">
                    <input type="hidden" name="cracking_id" value="<?php echo $cracking_record_id; ?>">
                    <input type="hidden" name="batch_no" value="<?php echo $batch_no; ?>">
                    <table style="width: 100%;">
                        <table>
                            <tr>
                                <td>EQUIPMENT</td>
                                <td>QUESTION</td>
                                <td>ANSWER</td>
                                <td>COMMENT</td>
                            </tr>
                            <?php
                            $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;
                                ?>
                                <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"]; ?>[]"
                                            id="clean_<?php echo $equipment["record_id"]; ?>[]"
                                            onchange="equipment_comment('clean_<?php echo $equipment['record_id']; ?>[]','clean_comment_<?php echo $equipment['record_id']; ?>[]');"
                                            class="inputs" style="margin:0;">
                                            <option></option>
                                            <option>YES</option>
                                            <option>NO</option>
                                            <option>N/A</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="text" name="clean_comment_<?php echo $equipment["record_id"]; ?>[]"
                                            id="clean_comment_<?php echo $equipment["record_id"]; ?>[]" class="inputs"
                                            style="margin: 0vw; width: 100%;">
                                    </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"]; ?>[]"
                                            id="excessive_<?php echo $equipment["record_id"]; ?>[]"
                                            onchange="equipment_comment('excessive_<?php echo $equipment['record_id']; ?>[]','excessive_comment_<?php echo $equipment['record_id']; ?>[]');"
                                            class="inputs" style="margin:0;">
                                            <option></option>
                                            <option>YES</option>
                                            <option>NO</option>
                                            <option>N/A</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="text" name="excessive_comment_<?php echo $equipment["record_id"]; ?>[]"
                                            id="excessive_comment_<?php echo $equipment["record_id"]; ?>[]" class="inputs"
                                            style="margin: 0vw; width: 100%;">
                                    </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"]; ?>[]"
                                            id="guardsk_<?php echo $equipment["record_id"]; ?>[]"
                                            onchange="equipment_comment('guardsk_<?php echo $equipment['record_id']; ?>[]','guardsk_comment_<?php echo $equipment['record_id']; ?>[]');"
                                            class="inputs" style="margin:0;">
                                            <option></option>
                                            <option>YES</option>
                                            <option>NO</option>
                                            <option>N/A</option>

                                        </select>
                                    </td>
                                    <td>
                                        <input type="text" name="guardsk_comment_<?php echo $equipment["record_id"]; ?>[]"
                                            id="guardsk_comment_<?php echo $equipment["record_id"]; ?>[]" class="inputs"
                                            style="margin: 0vw; width: 100%;">
                                    </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"]; ?>[]"
                                            id="Moving_<?php echo $equipment["record_id"]; ?>[]"
                                            onchange="equipment_comment('Moving_<?php echo $equipment['record_id']; ?>[]','Moving_comment_<?php echo $equipment['record_id']; ?>[]');"
                                            class="inputs" style="margin:0;">
                                            <option></option>
                                            <option>YES</option>
                                            <option>NO</option>
                                            <option>N/A</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="text" name="Moving_comment_<?php echo $equipment["record_id"]; ?>[]"
                                            id="Moving_comment_<?php echo $equipment["record_id"]; ?>[]" class="inputs"
                                            style="margin: 0vw; width: 100%;">
                                    </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"]; ?>[]"
                                            id="Power_<?php echo $equipment["record_id"]; ?>[]"
                                            onchange="equipment_comment('Power_<?php echo $equipment['record_id']; ?>[]','Power_comment_<?php echo $equipment['record_id']; ?>[]');"
                                            class="inputs" style="margin:0;">
                                            <option></option>
                                            <option>YES</option>
                                            <option>NO</option>
                                            <option>N/A</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="text" name="Power_comment_<?php echo $equipment["record_id"]; ?>[]"
                                            id="Power_comment_<?php echo $equipment["record_id"]; ?>[]" class="inputs"
                                            style="margin: 0vw; width: 100%;">
                                    </td>
                                </tr>
                                <?php
                                $index++;
                            }
                            ?>
                        </table>
                        <br>
                        <input type="button" value="SAVE LIST" class="submit_btn" onclick="save_equipment_check()">

                        <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_cracking.ajax.php", true);
                                xhr.onload = function () {
                                    if (xhr.status === 200) {
                                        if (xhr.responseText == "1") {
                                            alert("Successfully saved equipment check.");
                                        } else {
                                            alert("Failed to save equipment check." + xhr.responseText);
                                            console.log(xhr.responseText);

                                        }
                                    } else {
                                        console.log("Error: " + xhr.statusText);
                                    }
                                };
                                xhr.send(formData);
                            }
                        </script>
                </div>
            </div>
        </div>

        <br><br><br><br>

        <div id="food_inspection_table" style="width: 95%; display: flex; justify-content: center;">
            <?php

            $safety_res = $db->query("cracking_food_safety_inspections", "SELECT * FROM cracking_food_safety_inspections WHERE cracking_jobcard_id = '" . $cracking_record_id . "' ORDER BY record_id ASC");
            if ($safety_res->num_rows > 0) {
                $safety = $safety_res->fetch_assoc();
                $safety_comments_res = $db->query("cracking_food_safety_comments", "SELECT * FROM cracking_food_safety_comments WHERE food_safety_id = '" . $cracking_record_id . "' ORDER BY record_id ASC");
                if ($safety_comments_res->num_rows > 0) {
                    $safety_comments = $safety_comments_res->fetch_assoc();
                }
            } else {
                $safety = array();
                $safety_comments = array();
            }
            ?>
            <table>
                <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="check_option()">
                            <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 $safety["equipment_cleaned"] ?>";
                    document.getElementById("equipment_cleaned_comment").value = "<?php echo $safety_comments["equipment_cleaned_comment"] ?>";
                </script>
                <tr>
                    <td>Magnet 1 <input type="text" name="magnet_1_name" id="magnet_1_name"
                            placeholder="Magnet ID/ Serial NO" class="inputs" style="margin: 0vw; width: 50%;">
                        (Initial) Clean?</td>
                    <td>
                        <select name="magnet_1_cleaned" id="magnet_1_cleaned" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_1()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="magnet_1_comment" id="magnet_1_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("magnet_1_name").value = "<?php echo $safety["magnet_1_name"] ?>";
                    document.getElementById("magnet_1_cleaned").value = "<?php echo $safety["magnet_1_cleaned"] ?>";
                    document.getElementById("magnet_1_comment").value = "<?php echo $safety_comments["magnet_1_comment"] ?>";
                </script>
                <tr>
                    <td>Magnet 2 <input type="text" name="magnet_2_name" id="magnet_2_name"
                            placeholder="Magnet ID/ Serial NO" class="inputs" style="margin: 0vw; width: 50%;">
                        (Initial) Clean?</td>
                    <td>
                        <select name="magnet_2_cleaned" id="magnet_2_cleaned" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_2()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="magnet_2_comment" id="magnet_2_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("magnet_2_name").value = "<?php echo $safety["magnet_2_name"] ?>";
                    document.getElementById("magnet_2_cleaned").value = "<?php echo $safety["magnet_2_cleaned"] ?>";
                    document.getElementById("magnet_2_comment").value = "<?php echo $safety_comments["magnet_2_comment"] ?>";
                </script>
                <tr>
                    <td>Oxyacid Concentration verification (Add in spec after validation): </td>
                    <td>
                        <select name="oxyacid_concentration_verification" id="oxyacid_concentration_verification"
                            class="inputs" style="margin: 0vw; width: 100%;" onchange="check_option_3()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td>
                        <input type="text" name="oxyacid_concentration_verification_comment"
                            id="oxyacid_concentration_verification_comment" class="inputs"
                            style="margin: 0vw; width: 100%;">
                    </td>
                </tr>
                <script>
                    document.getElementById("oxyacid_concentration_verification").value = "<?php echo $safety["oxyacid_concentration_verification"] ?>";
                    document.getElementById("oxyacid_concentration_verification_comment").value = "<?php echo $safety_comments["oxyacid_concentration_verification_comment"] ?>";
                </script>
                <tr>
                    <td>Cracking equipment inspected (rollers, blades, hopper)? Yes/ No</td>
                    <td>
                        <select name="cracking_equipment_checked" id="cracking_equipment_checked" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_4()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="creaking_equipment_comment" id="creaking_equipment_comment"
                            class="inputs" style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("cracking_equipment_checked").value = "<?php echo $safety["cracking_equipment_checked"] ?>";
                    document.getElementById("creaking_equipment_comment").value = "<?php echo $safety_comments["creaking_equipment_comment"] ?>";
                </script>
                <tr>
                    <td>No signs of rust, oil leaks, or foreign objects</td>
                    <td>
                        <select name="oil_rust_signs" id="oil_rust_signs" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_5()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="oil_rust_signs_comment" id="oil_rust_signs_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("oil_rust_signs").value = "<?php echo $safety["oil_rust_signs"] ?>";
                    document.getElementById("oil_rust_signs_comment").value = "<?php echo $safety_comments["oil_rust_signs_comment"] ?>";
                </script>
                <tr>
                    <td>Shell separator & sieves clean</td>
                    <td>
                        <select name="shell_sieves_clean" id="shell_sieves_clean" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_6()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="shell_sieves_clean_comment" id="shell_sieves_clean_comment"
                            class="inputs" style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("shell_sieves_clean").value = "<?php echo $safety["shell_sieves_clean"] ?>";
                    document.getElementById("shell_sieves_clean_comment").value = "<?php echo $safety_comments["shell_sieves_clean_comment"] ?>";
                </script>
                <tr>
                    <td>Air filtration/dust control working properly</td>
                    <td>
                        <select name="filter_dust_control_working" id="filter_dust_control_working" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_7()">
                            <option value=""></option>
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </td>
                    <td><input type="text" name="filter_dust_comment" id="filter_dust_comment" class="inputs"
                            style="margin: 0vw; width: 100%;"></td>
                </tr>
                <script>
                    document.getElementById("filter_dust_control_working").value = "<?php echo $safety["filter_dust_control_working"] ?>";
                    document.getElementById("filter_dust_comment").value = "<?php echo $safety_comments["filter_dust_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="check_option_8()">
                            <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 $safety["personal_hygiene"] ?>";
                    document.getElementById("personal_hygiene_comment").value = "<?php echo $safety_comments["personal_hygiene_comment"] ?>";
                </script>
                <tr>
                    <td>Tools sanitized and labelled? </td>
                    <td>
                        <select name="tools_sanitized_labelled" id="tools_sanitized_labelled" class="inputs"
                            style="margin: 0vw; width: 100%;" onchange="check_option_9()">
                            <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_labelled").value = "<?php echo $safety["tools_sanitized_labelled"] ?>";
                    document.getElementById("tools_sanitized_comment").value = "<?php echo $safety_comments["tools_sanitized_comment"] ?>";
                </script>
            </table>
        </div>
        <div style="display: flex; justify-content: center;">
            <button type="button" onclick="halfway_save()" style="width: 100%;" 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>

        <br><br>

        <h1>QUALITY CONTROL HISTORY</h1>
        <div style="width: 90%; display: flex; justify-content: center;">
            <div class="quality_process_content">
                <?php
                $quality_res = $db->query("cracking_quality_process_control", "SELECT * FROM cracking_quality_process_control WHERE cracking_id = '" . $cracking_record_id . "' ORDER BY record_id ASC");
                if ($quality_res->num_rows > 0) {
                    while ($quality = $quality_res->fetch_assoc()) {
                        ?>
                        <!-- <table>
                            <tr>
                                <th>≥ 85–90% (for premium grade)</th>
                                <th colspan="3"></th>
                                <th>
                                    <= 10 - 15%</th>
                                <th>
                                    < 1%</th>
                                <th>
                                    < 1-2%</th>
                            </tr>
                            <tr>
                                <th>Wholes</th>
                                <th>Halves</th>
                                <th>Dust</th>
                                <th>Shells</th>
                                <th>Broken/ Chipped</th>
                                <th>Shell in kernel (adhering)</th>
                                <th>Un-cracked Nuts (shell in tact)</th>
                            </tr>
                            <tr>
                                <td><input type="number" name="whole" id="whole" class="inputs" step="0.01"
                                        style="margin: 0vw;width: 100%;" value="<?php echo $quality['wholes']; ?>">
                                </td>
                                <td><input type="number" name="half" id="half" class="inputs" step="0.01"
                                        style="margin: 0vw;width: 100%;" value="<?php echo $quality['halves']; ?>"></td>
                                <td><input type="number" name="dust" id="dust" class="inputs" step="0.01"
                                        style="margin: 0vw; width: 100%;">
                                </td>
                                <td><input type="number" name="shells" id="shells" class="inputs" step="0.01"
                                        style="margin: 0vw; width: 100%;" value="<?php echo $quality['shells']; ?>">
                                </td>
                                <td><input type="number" name="broken_chipped" id="broken_chipped" step="0.01" class="inputs"
                                        style="margin: 0vw; width: 100%;" value="<?php echo $quality['broken_chipped']; ?>">
                                </td>
                                <td><input type="number" name="shell_in_kernal" id="shell_in_kernal" step="0.01" class="inputs"
                                        style="margin: 0vw; width: 100%;" value="<?php echo $quality['shell_in_kernal']; ?>">
                                </td>
                                <td><input type="number" name="uncracked_nuts" id="uncracked_nuts" step="0.01" class="inputs"
                                        style="margin: 0vw; width: 100%;"
                                        value="<?php echo $quality['uncracked_missing_kernal']; ?>">
                                </td>
                            </tr>
                        </table>
                        <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>
                                <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" name="crushed_missing_kernal" id="crushed_missing_kernal" step="0.01"
                                        class="inputs" style="margin: 0vw;width: 100%;"
                                        value="<?php echo $quality['crushed_missing_kernal']; ?>"></td>
                                <td><input type="number" name="moisture" id="moisture" step="0.01" class="inputs"
                                        style="margin: 0vw;width: 100%;" value="<?php echo $quality['moisture']; ?>"></td>
                                <td><input type="number" name="env_temperature" id="env_temperature" step="0.01" class="inputs"
                                        style="margin: 0vw;width: 100%;" value="<?php echo $quality['env_temperature']; ?>">
                                </td>
                                <td><input type="number" name="env_humidity" id="env_humidity" step="0.01" class="inputs"
                                        style="margin: 0vw;width: 100%;" value="<?php echo $quality['env_humidity']; ?>">
                                </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>
                                    <script>
                                        document.getElementById("magnet_inspection").value = "<?php echo $quality['magnet_inspection']; ?>";
                                    </script>
                                </td>
                                <td>
                                    <?php
                                    $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '" . $quality['person_inspection'] . "'");
                                    $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['cracking_signature']; ?>" alt="signature"
                                        style="width: 100px;">
                                </td>
                            </tr>
                        </table> -->

                        <table>
                            <tr>
                                <th>Person Inspecting</th>
                                <th>Shift</th>
                                <th>Date Time</th>
                                <th>Signature</th>
                                <th></th>
                            </tr>
                            <tr>
                                <td>
                                    <?php
                                    $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '" . $quality['person_inspection'] . "'");
                                    $user = $user_res->fetch_assoc()['username'];
                                    ?>
                                    <?php echo $user ?>
                                </td>
                                <td>
                                    <?php

                                    if ($quality['shift'] == "D") {
                                        $shift = "DAY";
                                    } else {
                                        $shift = "NIGHT";
                                    }
                                    ?>
                                    <?php echo $shift ?>
                                </td>
                                <td>
                                    <?php echo $date_time ?>
                                </td>
                                <td>
                                    <img src="<?php echo $quality['cracking_signature']; ?>" alt="signature"
                                        style="width: 100px;">
                                </td>
                                <td>
                                    <button type="button" class="submit_btn"
                                        onclick="window.location.href='../reports/quality_control.pdf.php?record_id=<?php echo $cracking_record_id; ?>&check_no=<?php echo $equipment['check_no']; ?>'">
                                        PDF
                                    </button>
                                </td>
                            </tr>
                        </table>
                        <br>
                        <?php
                    }
                }
                ?>
            </div>
        </div>

        <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>QUALITY & 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
                        $cracking_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</h4>
                <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>≥ 85–90% (for premium grade)</th>
                        <th colspan="3"></th>
                        <th>
                            <= 10 - 15%</th>
                        <th>
                            < 1%</th>
                        <th>
                            < 1-2%</th>
                    </tr>
                    <tr>
                        <th>Wholes</th>
                        <th>Halves</th>
                        <th>Dust</th>
                        <th>Shells</th>
                        <th>Broken/ Chipped</th>
                        <th>Shell in kernel (adhering)</th>
                        <th>Un-cracked Nuts (shell in tact)</th>
                    </tr>
                    <tr>
                        <td><input type="number" name="whole" id="whole" class="inputs" step="0.01"
                                style="margin: 0vw;width: 100%;">
                        </td>
                        <td><input type="number" name="half" id="half" class="inputs" step="0.01"
                                style="margin: 0vw;width: 100%;"></td>
                        <td><input type="number" name="dust" id="dust" class="inputs" step="0.01"
                                style="margin: 0vw; width: 100%;">
                        </td>
                        <td><input type="number" name="shells" id="shells" class="inputs" step="0.01"
                                style="margin: 0vw; width: 100%;">
                        </td>
                        <td><input type="number" name="broken_chipped" id="broken_chipped" 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>
                <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>

            <br><br>
            <input type="button" value="GUIDANCE SPECS" class="submit_btn" onclick="open_Popup()">
            <br>
            <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.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="QUALITY CONTROL" class="submit_btn" onclick="open_quality_control()">
        <div id="guidance_popup" class="guidance_popup">
            <div class="guidance_content">
                <span class="close-btn" onclick="close_Popup()">&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>

        <div id="batch_output_summary_table" style="width: 90%;">
            <?php
            $summary_res = $db->query("cracking_batch_summary", "SELECT * FROM cracking_batch_summary WHERE cracking_jobcard_id = '$cracking_record_id'");
            if ($summary_res->num_rows > 0) {
                $summary = $summary_res->fetch_assoc();
            } else {
                $summary['whole_kernal'] = 0;
                $summary['halves'] = 0;
                $summary['broken'] = 0;
                $summary['crushed'] = 0;
                $summary['waste'] = 0;
                $summary['kernal_breakage_rate'] = 0;
                $summary['dust_summary'] = 0;
                $summary['moisture_in_shell'] = 0;
                $summary['shell_summary'] = 0;
                $summary['whole_kernal_recovery'] = 0;
                $summary['shell_in_kernal_contamination'] = 0;
                $summary['shell_in_kernal_summary'] = 0;
                $summary['kernal_stuck_in_shell'] = 0;
                $summary['uncracked_nuts_summary'] = 0;
                $summary['crushed_missing_kernal_summary'] = 0;
                $summary['actions_taken'] = 0;
                $summary['chips_broken'] = 0;

            }

            ?>
            <table style="width: 100%;">
                <tr>
                    <th colspan="6">Batch Output Calculation Summary</th>
                </tr>
                <tr>
                    <td>Whole Kernel</td>

                    <td><input type="number" step="0.01" name="whole_kernal" id="whole_kernal" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['whole_kernal']; ?>"></td>
                    <td>Waste</td>

                    <td><input type="number" step="0.01" name="waste" id="waste" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['waste']; ?>"></td>
                    </td>
                </tr>
                <tr>
                    <td>Halves</td>

                    <td><input type="number" step="0.01" name="halves" id="halves" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['halves']; ?>"></td>
                    </td>
                    <td>Kernal Breakage rate (≤ 10–15%)</td>

                    <td><input type="number" step="0.01" name="kernal_breakage_rate" id="kernal_breakage_rate"
                            class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['kernal_breakage_rate']; ?>"></td>
                </tr>
                <tr>
                    <td>Dust</td>

                    <td><input type="number" step="0.01" name="dust_summary" id="dust_summary" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['dust_summary']; ?>"></td>
                    <td>Moisture (in-shell 1.5–3.0%)</td>

                    <td><input type="number" step="0.01" name="moisture_in_shell" id="moisture_in_shell" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['moisture_in_shell']; ?>"></td>
                </tr>
                <tr>
                    <td>Shells</td>

                    <td><input type="number" step="0.01" name="shell_summary" id="shell_summary" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['shell_summary']; ?>"></td>
                    <td>Whole kernel recovery (≥ 85%)</td>

                    <td><input type="number" step="0.01" name="whole_kernal_recovery" id="whole_kernal_recovery"
                            class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['whole_kernal_recovery']; ?>"></td>
                </tr>
                <tr>
                    <td>Chips/Broken</td>

                    <td><input type="number" step="0.01" name="chips_broken" id="chips_broken" class="inputs"
                            style="margin: 0vw;width: 100%;" value="<?php echo $summary['chips_broken']; ?>"></td>
                    <td>Shell in kernel contamination (0%)</td>

                    <td><input type="number" step="0.01" name="shell_in_kernal_contamination"
                            id="shell_in_kernal_contamination" class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['shell_in_kernal_contamination']; ?>"></td>
                </tr>
                <tr>
                    <td>Shell in kernal</td>

                    <td><input type="number" step="0.01" name="shell_in_kernal_summary" id="shell_in_kernal_summary"
                            class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['shell_in_kernal_summary']; ?>"></td>
                    <td>Kernel stuck in shell (< 1–2%)</td>

                    <td><input type="number" step="0.01" name="kernal_stuck_in_shell" id="kernal_stuck_in_shell"
                            class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['kernal_stuck_in_shell']; ?>"></td>
                </tr>
                <tr>
                    <td>Uncracked nuts</td>

                    <td><input type="number" step="0.01" name="uncracked_nuts_summary" id="uncracked_nuts_summary"
                            class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['uncracked_nuts_summary']; ?>"></td>
                    <td colspan="2"></td>

                </tr>
                <tr>
                    <td>Crushed/ missing kernel</td>

                    <td><input type="number" step="0.01" name="crushed_missing_kernal_summary"
                            id="crushed_missing_kernal_summary" class="inputs" style="margin: 0vw;width: 100%;"
                            value="<?php echo $summary['crushed_missing_kernal_summary']; ?>"></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']; ?>"></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($cracking['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->value_from_db("cracking_jobcard", "production_supervisor", "record_id = '" . $cracking_record_id . "'");
                $production_supervisor->style("width: 20vw;");
                $production_supervisor->fill_from_db("users", "record_id", "username");
                $production_supervisor->add();
                ?>

                <?php if ($cracking['supervisor_signature'] != null) { ?>
                    <img src="<?php echo $cracking['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_name");
                $quality_control_name->id("quality_control_name");
                $quality_control_name->class("inputs");
                $quality_control_name->value_from_db("cracking_jobcard", "quality_control", "record_id = '" . $cracking_record_id . "'");
                $quality_control_name->style("width: 20vw;");
                $quality_control_name->fill_from_db("users", "record_id", "username");
                $quality_control_name->add();
                ?>

                <?php if ($cracking['quality_controller_signature'] != null) { ?>
                    <img src="<?php echo $cracking['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" style="width:100%;">UPDATE</button>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
        <script>

            document.getElementById('submit_form_btn').addEventListener('click', function () {
                const form = document.getElementById('cracking_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 equipment_comment(answer, comment) {
                var equipment_answer = document.getElementById(answer);
                var equipment_comment = document.getElementById(comment);

                if (equipment_answer.value === "NO") {
                    equipment_comment.required = true;
                    equipment_comment.readOnly = false;
                    equipment_comment.style.border = "3px solid red";
                } else if (equipment_answer.value === "N/A") {
                    equipment_comment.required = false;
                    equipment_comment.readOnly = true;
                    equipment_comment.style.border = "3px solid grey";
                } else {
                    equipment_comment.required = false;
                    equipment_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option() {
                var equipment_cleaned = document.getElementById("equipment_cleaned");
                var equipment_cleaned_comment = document.getElementById("equipment_cleaned_comment");

                if (equipment_cleaned.value === "NO") {
                    equipment_cleaned_comment.required = true;
                    equipment_cleaned_comment.style.border = "3px solid red";
                } else {
                    equipment_cleaned_comment.required = false;
                    equipment_cleaned_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_1() {
                var magnet_1_cleaned = document.getElementById("magnet_1_cleaned");
                var magnet_1_cleaned_comment = document.getElementById("magnet_1_comment");

                if (magnet_1_cleaned.value === "NO") {
                    magnet_1_cleaned_comment.required = true;
                    magnet_1_cleaned_comment.style.border = "3px solid red";
                } else {
                    magnet_1_cleaned_comment.required = false;
                    magnet_1_cleaned_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_2() {
                var magnet_2_cleaned = document.getElementById("magnet_2_cleaned");
                var magnet_2_cleaned_comment = document.getElementById("magnet_2_comment");

                if (magnet_2_cleaned.value === "NO") {
                    magnet_2_cleaned_comment.required = true;
                    magnet_2_cleaned_comment.style.border = "3px solid red";
                } else {
                    magnet_2_cleaned_comment.required = false;
                    magnet_2_cleaned_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_3() {
                var oxyacid_concentration_verification = document.getElementById("oxyacid_concentration_verification");
                var oxyacid_concentration_verification_comment = document.getElementById("oxyacid_concentration_verification_comment");

                if (oxyacid_concentration_verification.value === "NO") {
                    oxyacid_concentration_verification_comment.required = true;
                    oxyacid_concentration_verification_comment.style.border = "3px solid red";
                } else {
                    oxyacid_concentration_verification_comment.required = false;
                    oxyacid_concentration_verification_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_4() {
                var cracking_equipment_checked = document.getElementById("cracking_equipment_checked");
                var cracking_equipment_checked_comment = document.getElementById("creaking_equipment_comment");

                if (cracking_equipment_checked.value === "NO") {
                    cracking_equipment_checked_comment.required = true;
                    cracking_equipment_checked_comment.style.border = "3px solid red";
                } else {
                    cracking_equipment_checked_comment.required = false;
                    cracking_equipment_checked_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_5() {
                var oil_rust_signs = document.getElementById("oil_rust_signs");
                var oil_rust_signs_comment = document.getElementById("oil_rust_signs_comment");

                if (oil_rust_signs.value === "NO") {
                    oil_rust_signs_comment.required = true;
                    oil_rust_signs_comment.style.border = "3px solid red";
                } else {
                    oil_rust_signs_comment.required = false;
                    oil_rust_signs_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_6() {
                var shell_sieves_clean = document.getElementById("shell_sieves_clean");
                var shell_sieves_clean_comment = document.getElementById("shell_sieves_clean_comment");

                if (shell_sieves_clean.value === "NO") {
                    shell_sieves_clean_comment.required = true;
                    shell_sieves_clean_comment.style.border = "3px solid red";
                } else {
                    shell_sieves_clean_comment.required = false;
                    shell_sieves_clean_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_7() {
                var filter_dust_control_working = document.getElementById("filter_dust_control_working");
                var filter_dust_comment = document.getElementById("filter_dust_comment");

                if (filter_dust_control_working.value === "NO") {
                    filter_dust_comment.required = true;
                    filter_dust_comment.style.border = "3px solid red";
                } else {
                    filter_dust_comment.required = false;
                    filter_dust_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_8() {
                var personal_hygiene = document.getElementById("personal_hygiene");
                var personal_hygiene_comment = document.getElementById("personal_hygiene_comment");

                if (personal_hygiene.value === "NO") {
                    personal_hygiene_comment.required = true;
                    personal_hygiene_comment.style.border = "3px solid red";
                } else {
                    personal_hygiene_comment.required = false;
                    personal_hygiene_comment.style.border = "3px solid #004aad";
                }
            }

            function check_option_9() {
                var tools_sanitized_labelled = document.getElementById("tools_sanitized_labelled");
                var tools_sanitized_comment = document.getElementById("tools_sanitized_comment");

                if (tools_sanitized_labelled.value === "NO") {
                    tools_sanitized_comment.required = true;
                    tools_sanitized_comment.style.border = "3px solid red";
                } else {
                    tools_sanitized_comment.required = false;
                    tools_sanitized_comment.style.border = "3px solid #004aad";
                }
            }

            // Prevent form submission on Enter key press
            document.getElementById("cracking_form").addEventListener("keydown", function (event) {
                if (event.key === "Enter") {
                    event.preventDefault(); // stops the form submission
                }
            });

            function open_Popup() {
                document.getElementById("guidance_popup").style.display = "block";
            }

            function close_Popup() {
                document.getElementById("guidance_popup").style.display = "none";
            }

            function open_equipment() {
                document.getElementById("equipment_popup").style.display = "block";
            }

            function close_equipment() {
                document.getElementById("equipment_popup").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('cracking_form');

                const psInput = document.createElement('input');
                psInput.type = 'hidden';
                psInput.name = 'save_halfway';
                psInput.value = '1';

                form.appendChild(psInput);

                // Submit the form
                form.submit();
            }

            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";
            }


        </script>

</form>