<?php 
    include "../../root.class.php";
    $html = new html();
    $html->add_styles_page();
    // $html->check_user_type("ADMIN");
    $db = new db_safeguard();

    $current_date_time = date("Y-m-d H:i", strtotime("+2 hours"));

    $make_notes_btn = new button();
    $make_notes_btn->value("MAKE NOTES");
    $make_notes_btn->onclick("open_notesPopup()");

    $jobcard_id_record_id = new input();
    $jobcard_id_record_id->type("hidden");
    $jobcard_id_record_id->name("jobcard_id");
    $jobcard_id_record_id->id("jobcard_id");
    $jobcard_id_record_id->value($_GET['record_id']);

    $date_time = new input();
    $date_time->type("hidden");
    $date_time->name("date_time");
    $date_time->id("date_time");
    $date_time->value($current_date_time);

    $reasons_label = new label();
    $reasons_label->class("big_labels");
    $reasons_label->for("reasons");
    $reasons_label->value("REASONS");
    $reasons_label->addAttribute("style", " color: white;");

    $reasons = new select();
    $reasons->class("big_inputs");
    $reasons->name("reason");
    $reasons->id("reason");
    $reasons->addAttribute("style", "width: 20%;");
    $reasons->add_option("ARRIVED AT LOCATION", "ARRIVED AT LOCATION");
    $reasons->add_option("WAITING FOR CLIENT", "WAITING FOR CLIENT");
    $reasons->add_option("TRAVELING TO SITE", "TRAVELING TO SITE");
    $reasons->add_option("ARRIVED ON SITE", "ARRIVED ON SITE");
    $reasons->add_option("TALKING TO CLIENT", "TALKING TO CLIENT");
    $reasons->add_option("FETCHING MONEY", "FETCHING MONEY");
    $reasons->add_option("BRAKING", "BRAKING");
    $reasons->add_option("CHANGING RIEMER", "CHANGING RIEMER");
    $reasons->add_option("STOP", "STOP");
    $reasons->add_option("PENDING", "PENDING");
    $reasons->add_option("START", "START");
    $reasons->add_option("INSTALLING", "INSTALLING");
    $reasons->add_option("RECEIVED", "RECEIVED");
    $reasons->add_option("BACK TO WORKSHOP", "BACK TO WORKSHOP");
    $reasons->add_option("OTHER", "OTHER");

    $notes_label = new label();
    $notes_label->class("notes_heading");
    $notes_label->for("notes");
    $notes_label->value("NOTES");
    $notes_label->addAttribute("style", "color: white; margin:1px;");

    $notes_sub_label = new label();
    $notes_sub_label->class("big_labels");
    $notes_sub_label->for("notes");
    $notes_sub_label->value("NOTES");
    $notes_sub_label->addAttribute("style", " color: white;");

    $notes = new input();
    $notes->class("big_inputs");
    $notes->type("text");
    $notes->placeholder("NOTES");
    $notes->name("note");
    $notes->id("note");
    $notes->addAttribute("style", "width: 50%;");

    $add_notes = new button();
    $add_notes->value("ADD NOTES");
    $add_notes->onclick("add_notes()");
    $add_notes->style("width: 100%;");
    $add_notes->id("notes_btn");

    $image = new file_upload();
    $image->file_save_path("../jobcards/notes/");
    $image->file_type("png, jpg, jpeg");
    $image->name("image");
    $image->id("image");
    $image->class("inputs");
    $image->style("width: 50%;");

    $ajax = new js_ajax();
    $ajax->function_name("add_notes");
    $ajax->insert("notes");
    $ajax->selected_div(".notes_content input , .notes_content select ");
    $ajax->submit_btn_id("notes_btn");
    $ajax->on_success("NOTE SAVED");

?>

<style>
    .summary_popup {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .summary_content {
        background: linear-gradient(90deg, #110151, #3331e7);
        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;
    }

    .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;
        font-size: 4vw;
    }
</style>

<div
    style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw;">
    <?php

    $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id ASC");

    if ($res_data->num_rows > 0) {

        $jobcard_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
        $jobcard = $jobcard_res->fetch_assoc();

        // echo $jobcard['record_id'];
    
        ?>

        <h1 style="font-size: 3em;">CLIENT INFORMATION</h1>

        <div style="display: flex; flex-direction: column; width: 90%; align-items: center;">
            <label for="_label" class="create_details_label style='width: 100%;'">CLIENT NAME : </label>
            <input type="text" name="client_name" style="" class="create_details_input"
                value="<?php echo $jobcard['client_name']; ?>">
        </div>

        <div style="display: flex; flex-direction: column; width: 90%; align-items: center;">
            <label for="_label" class="create_details_label" style='width: 100%;'>CONTACT NUMBER : </label>
            <input type="text" name="contact_number" style="" class="create_details_input"
                value="<?php echo $jobcard['contact_number']; ?>">
        </div>

        <div style="display: flex; flex-direction: column; width: 90%; align-items: center;">
            <label for="_label" class="create_details_label" style='width: 100%;'>ADDRESS : </label>
            <input type="text" name="address" style="" class="create_details_input"
                value="<?php echo $jobcard['address']; ?>">
        </div><br>

        <div style="display: flex; flex-direction: column; width: 90%; align-items: center;">
            <label for="_label" class="create_details_label" style='width: 100%;'>SLIP NO : </label>
            <input type="text" name="slip_no" class="create_details_input"
                value="<?php echo $jobcard['slip_no']; ?>">
        </div><br>

        <?php
        $make_notes_btn->add();
        ?>
    </div>

    <div
        style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw;">

        <h1 style="font-size: 3em;">JOBCARD SUMMARY</h1>

        <table
            style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:95%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
            <tr>
                <th>TYPE</th>
                <th>METERS</th>
                <th>DATE</th>
            </tr>
            <?php
            $riem_meters = 0;
            $drilling_meters = 0;
            $casing_meters = 0;
            $blasting_meters = 0;

            while ($jc_timeline = $res_data->fetch_assoc()) {

                if ($jc_timeline['type'] == "RIEM_STOP" || $jc_timeline['type'] == "RIEMING_STOP" || $jc_timeline['type'] == "RIEMING_PAUSED") {
                    $riem_meters += $jc_timeline['meters'];
                }

                if ($jc_timeline['type'] == "DRILLING_STOP" || $jc_timeline['type'] == "DRILLING_PAUSE") {
                    $drilling_meters += $jc_timeline['meters'];
                }

                if ($jc_timeline['type'] == "CASING_STOP" || $jc_timeline['type'] == "CASING_PAUSE") {
                    $casing_meters += $jc_timeline['meters'];
                }

                if ($jc_timeline['type'] == "BLASTING_START" || $jc_timeline['type'] == "BLASTING_STOP") {
                    $blasting_meters += $jc_timeline['meters'];
                }

                ?>
                <tr>
                    <td> <?php echo str_replace("_", " ", $jc_timeline['type']) ?> </td>
                    <td> <?php echo $jc_timeline['meters'] ?> </td>
                    <td> <?php echo $jc_timeline['date_time'] ?> </td>
                </tr>
                <?php
            }
            ?>
        </table><br><br>

    </div>

    <div
        style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; padding: 2vw;">

        <table style="width:95%;">
            <tr>
                <th> TOTALS </th>
                <th> METERS </th>
            </tr>
            <tr>
                <td> TOTAL RIEM METERS </td>
                <td> <?php echo $riem_meters ?> </td>
            </tr>
            <tr>
                <td> TOTAL DRILLING METERS </td>
                <td> <?php echo $drilling_meters ?> </td>
            </tr>
            <tr>
                <td> TOTAL CASING METERS </td>
                <td> <?php echo $casing_meters ?> </td>
            </tr>
            <tr>
                <td> TOTAL BLASTING METERS</td>
                <td> <?php echo $blasting_meters ?></td>
            </tr>
            <tr>
                <td> TOTAL </td>
                <td> <?php echo $riem_meters + $drilling_meters + $casing_meters + $blasting_meters ?> </td>
            </tr>
        </table>

        <br><br>

        <table
            style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:95%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
            <tr>
                <th></th>
                <th>VALUE</th>
            </tr>
            <tr>
                <td>Interested in Pump: </td>
                <td><?php echo $jobcard['interested_in_pump']; ?></td>
            </tr>
            <tr>
                <td>Water Flow: </td>
                <td> <?php echo $jobcard['water_flow']; ?> </td>
            </tr>
            <tr>
                <td>Compressor Hours: </td>
                <td> <?php echo $jobcard['compressor_hours'] ?> </td>
            </tr>
            <tr>
                <td>Diesel Start: </td>
                <td> <?php echo $jobcard['diesel_start'] ?> </td>
            </tr>
            <tr>
                <td>Diesel Stop: </td>
                <td> <?php echo $jobcard['diesel_stop'] ?> </td>
            </tr>
            <tr>
                <td>Water Strike: </td>
                <td> <?php echo $jobcard['water_strike'] ?> </td>
            </tr>
        </table>

        <br><br>

        <table
            style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:95%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
            <tr>
                <th></th>
                <th>LITERS</th>
            </tr>
            <tr>
                <td>Diesel Start : </td>
                <td>
                    <?php echo $jobcard['diesel_start']; ?>
                </td>
            </tr>
            <tr>
                <td>Diesel Stop : </td>
                <td>
                    <?php echo $jobcard['diesel_stop']; ?>
                </td>
            </tr>
            <tr>
                <td>Diesl Used : </td>
                <td>
                    <?php echo $used = $jobcard['diesel_start'] - $jobcard['diesel_stop']; ?>
                </td>
            </tr>
        </table>
    </div>

    <div
        style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; padding: 2vw;">

        <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

        <h1 style="font-size: 3em;">SIGNATURES</h1>
        <?php
            $jobcard_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
            $jobcard_data = $jobcard_data_res->fetch_assoc();

            // echo "../jobcards/signatures/employee-jc" . $jobcard_data['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
            if (file_exists("../jobcards/signatures/employee-jc" . $jobcard_data['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {

                ?>
                <div style='margin-bottom:1vw; display:flex; flex-direction:column; align-items:center;'>
                    <h2 style="font-size: 2em;">EMPLOYEE SIGNATURE</h2>
                    <input type='image'
                        src='../jobcards/signatures/employee-jc<?php echo $jobcard_data['jc_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png'
                        alt='employee signature' class="signature_image"
                        style="width: 80vw;  height:auto; border:2px solid black; border-radius:1vw;">
                </div>
                <?php
            } else {
                ?>
                <div style='margin-bottom:1vw; display:flex; flex-direction:column; align-items:center;'>
                    <h2 style="font-size: 2em;">EMPLOYEE SIGNATURE</h2>
                    <div
                        style="width:80vw; height:20vw; border:2px solid black; border-radius:1vw; display:flex; justify-content:center; align-items:center; background-color:#f0f0f0;">
                        <span style="color:#888888; font-size:1.5vw;">NO SIGNATURE FOUND</span>
                    </div>
                    <?php
            }

            // echo "<br><br>";
        
            // echo "../jobcards/signatures/client-jc" . $jobcard_data['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
            if (file_exists("../jobcards/signatures/client-jc" . $jobcard_data['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                ?>

                    <div style="margin-bottom:1vw; display:flex; flex-direction:column; align-items:center;">
                        <h2 style="font-size: 2em;">CLIENT SIGNATURE</h2>

                        <input type="image"
                            src="../jobcards/signatures/client-jc<?php echo $jobcard_data['jc_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png"
                            alt="client signature" class="signature_image"
                            style="width: 80vw;  height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php
            } else {
                ?>
                    <div style="margin-bottom:1vw; display:flex; flex-direction:column; align-items:center;">
                        <h2 style="font-size: 2em;">CLIENT SIGNATURE</h2>
                        <div
                            style="width:80vw; height:20vw; border:2px solid black; border-radius:1vw; display:flex; justify-content:center; align-items:center; background-color:#f0f0f0;">
                            <span style="color:#888888; font-size:1.5vw;">NO SIGNATURE FOUND</span>
                        </div>
                        <?php
            }
        ?>
            </div>

            <div
                style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; padding: 2vw;">
                <?php
                // echo "../jobcards/client_merch/". $jobcard_data['client_merch_image'];
                if (file_exists("../jobcards/client_merch/" . $jobcard_data['client_merch_image'])) {
                    ?>
                    <div style="display:flex; flex-direction:column; align-items:center; margin-top:2vw;">
                        <h2 style="font-size: 2em;">CLIENT MERCHANDISE IMAGE</h2>
                        <input type="image" src="../jobcards/client_merch/<?php echo $jobcard_data['client_merch_image']; ?>"
                            alt="client merchandise image"
                            style="width:80vw; height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php

                }

                // echo "../jobcards/samples/". $jobcard_data['samples_image'];
                if (file_exists("../jobcards/samples/" . $jobcard_data['samples_image'])) {
                    ?>
                    <div style="display:flex; flex-direction:column; align-items:center; margin-top:2vw;">
                        <h2 style="font-size: 2em;">SAMPLES IMAGE</h2>
                        <input type="image" src="../jobcards/samples/<?php echo $jobcard_data['samples_image']; ?>"
                            alt="samples_image" style="width:80vw; height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php

                }

                // echo "../jobcards/casing_report/". $jobcard_data['casing_report_image'];
                if (file_exists("../jobcards/casing_report/" . $jobcard_data['casing_report_image'])) {
                    ?>
                    <div style="display:flex; flex-direction:column; align-items:center; margin-top:2vw;">
                        <h2 style="font-size: 2em;">CASING REPORT IMAGE</h2>
                        <input type="image" src="../jobcards/casing_report/<?php echo $jobcard_data['casing_report_image']; ?>"
                            alt="casing_report image"
                            style="width:80vw; height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php

                }

                // echo "../jobcards/bytel_report/". $jobcard_data['bytel_report_image'];
                if (file_exists("../jobcards/bytel_report/" . $jobcard_data['bytel_report_image'])) {
                    ?>
                    <div style="display:flex; flex-direction:column; align-items:center; margin-top:2vw;">
                        <h2 style="font-size: 2em;">BYTEL REPORT IMAGE</h2>
                        <input type="image" src="../jobcards/bytel_report/<?php echo $jobcard_data['bytel_report_image']; ?>"
                            alt="bytel_report image"
                            style="width:80vw; height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php

                }

                // echo "../jobcards/board/". $jobcard_data['board_image'];
                if (file_exists("../jobcards/board/" . $jobcard_data['board_image'])) {
                    ?>
                    <div style="display:flex; flex-direction:column; align-items:center; margin-top:2vw;">
                        <h2 style="font-size: 2em;">BOARD IMAGE</h2>
                        <input type="image" src="../jobcards/board/<?php echo $jobcard_data['board_image']; ?>"
                            alt="board image" style="width:80vw; height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php

                }

                // echo "../jobcards/slip_no/". $jobcard_data['slip_no_image'];
                if (file_exists("../jobcards/slip_no/" . $jobcard_data['slip_no_image'])) {
                    ?>
                    <div style="display:flex; flex-direction:column; align-items:center; margin-top:2vw;">
                        <h2 style="font-size: 2em;">SLIP NO IMAGE</h2>
                        <input type="image" src="../jobcards/slip_no/<?php echo $jobcard_data['slip_no_image']; ?>"
                            alt="slip_no image"
                            style="width:80vw; height:auto; border:2px solid black; border-radius:1vw;">
                    </div>
                    <?php

                }

                ?>

                <br>
                <?php
                    $done_btn = new button();
                    $done_btn->value("DONE");
                    $done_btn->onclick("complete()");
                    $done_btn->add();

                    $done_ajax = new js_ajax();
                    $done_ajax->function_name("complete");
                    $done_ajax->insert("jobcards");
                    $done_ajax->selected_div("complete_div");
                    $done_ajax->add_column_and_value("status=1");
                    $done_ajax->on_success("JOBCARD COMPLETED");
                    $done_ajax->redirect('../home.php');
                ?>
            </div>

            <?php

    } else {
        ?>
            <table
                style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:50%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
                <tr>
                    <th>NAME</th>
                    <th>VALUE</th>
                </tr>
                <tr>
                    <td></td>
                    <td> DATA NOT FOUND </td>
                    <td></td>
                </tr>

            </table>

            <?php
    }
    ?>

    <div class="notes_popup" id="notes_popup">
        <div class="notes_content">
            <span class="close-btn" onclick="close_notesPopup()">&times;</span>

            <?php
                $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['record_id']}' ORDER BY record_id DESC LIMIT 1");
                $data = $res_data->fetch_assoc();
            ?>

            <input type="text" class="inputs" value="<?php echo $data['type'] ?>" readonly hidden/>
            <input type="text" class="inputs" name="jobcard_no" id="jobcard_no" value="<?php echo $_GET['record_id']; ?>" hidden/>

            <label for="notes" class="notes_heading" style="color: white;margin:1px;">NOTES</label>

            <div style="display: flex; flex-direction: column;">
                <label for="reasons" class="big_labels" style="color: white;">REASONS</label>
                <select id="reason" name="reason" class="big_inputs">
                    <option value="">--SELECT--</option>
                    <option value="ARRIVED AT LOCATION">ARRIVED AT LOCATION</option>
                    <option value="WAITING FOR CLIENT">WAITING FOR CLIENT</option>
                    <option value="TRAVELING TO SITE">TRAVELING TO SITE</option>
                    <option value="ARRIVED ON SITE">ARRIVED ON SITE</option>
                    <option value="TALKING TO CLIENT">TALKING TO CLIENT</option>
                    <option value="ARRIVED ON SITE">ARRIVED ON SITE</option>
                    <option value="TALKING TO CLIENT">TALKING TO CLIENT</option>
                    <option value="FETCHING MONEY">FETCHING MONEY</option>
                    <option value="BRAKING">BRAKING</option>
                    <option value="CHANGING RIEMER">CHANGING RIEMER</option>
                    <option value="STOP">STOP</option>
                    <option value="PENDING">PENDING</option>
                    <option value="START">START</option>
                    <option value="INSTALLING">INSTALLING</option>
                    <option value="RECEIVED">RECEIVED</option>
                    <option value="BACK TO WORKSHOP">BACK TO WORKSHOP</option>
                    <option value="OTHER">OTHER</option>
                </select>

                <label for="notes" class="big_labels" style="color: white">NOTES</label>
            </div>

            <div id="normal_section" style="display: flex; flex-direction: column; align-items: center;">
                <textarea name="note" id="note" class="inputs" style="width: 70vw; font-size: 3em;" rows="5"></textarea>
                <label for="reasons" class="big_labels" style="color: white;">UPLOAD TYPE</label>
                <select id="image_type" name="image_type" onchange="file_camera_type()" class="big_inputs">
                    <option></option>
                    <option value="file">ATTACH FILE</option>
                    <option value="camera">CAMERA</option>
                </select>

                    <style>
                        video,
                        canvas {
                            width: 400px;
                            height: 300px;
                            border: 3px solid #ccc;
                            border-radius: 2vw;
                            margin-top: 10px;
                        }

                        @media all and (max-width: 600px) {

                            video,
                            canvas {
                                width: 600px;
                                height: 450px;
                                margin-top: -5vw;
                            }
                        }
                    </style>

                <div style="background-color: white; padding: 2vw; display: flex; flex-direction: column; align-items: center;">
                    <div id="attach_file_div" style="display:none; flex-direction: column; align-items: center;">
                        <label for="proof" class="big_labels">ATTACH FILE</label>
                        <input type="file" name="attach_note" id="attach_note" style="width: 90%;" class="big_inputs" onchange="upload_file()">
                    </div>

                    <div id="camera_div" style="display:none; flex-direction: column; align-items: center;">
                        <video style="display: none;" id="camera_notes" autoplay playsinline></video>
                        <br>

                        <button id="open_camera_notes" class="submit_btn"
                            onclick="open_notes_Camera()">Open
                            Camera</button>

                        <div id="load_camera_notes"
                            style="display: none; width: 100%; justify-content: center;">
                            <button class="submit_btn" onclick="capture_notes_Photo()">Capture
                                Photo</button>
                            <button class="submit_btn" onclick="stop_notes_Camera()">Stop
                                Camera</button>
                        </div>

                        <div id="captured_image_notes" style="display:none">
                            <h3>Captured Image:</h3>
                            <canvas id="snapshot_notes"></canvas>
                        </div>

                        <script>
                            let stream_notes;

                            async function open_notes_Camera() {
                                const video = document.getElementById("camera_notes");
                                const load_camera = document.getElementById("load_camera_notes");
                                const open_camera = document.getElementById("open_camera_notes");

                                try {

                                    stream_notes = await navigator.mediaDevices.getUserMedia({
                                        video: { facingMode: "environment" },
                                        audio: false
                                    });

                                    const video = document.getElementById("camera_notes");
                                    video.srcObject = stream_notes;
                                    video.style.display = "block";

                                    load_camera.style.display = "flex";
                                    open_camera.style.display = "none";


                                } catch (error) {
                                    alert("Error accessing camera: " + error.message);
                                }
                            }

                            function stop_notes_Camera() {
                                const open_camera = document.getElementById("open_camera_notes");
                                const load_camera = document.getElementById("load_camera_notes");
                                const video = document.getElementById("camera_notes");

                                video.style.display = "none";
                                load_camera.style.display = "none";
                                open_camera.style.display = "block";
                                if (stream_notes) {
                                    stream_notes.getTracks().forEach(track => track.stop());
                                    stream_notes = null;
                                    document.getElementById("camera_notes").srcObject = null;
                                }
                            }

                            function capture_notes_Photo() {
                                const video = document.getElementById("camera_notes");
                                const canvas = document.getElementById("snapshot_notes");
                                const context = canvas.getContext("2d");
                                const captured_image = document.getElementById("captured_image_notes");
                                const load_camera = document.getElementById("load_camera_notes");
                                const jobcard_no = "<?php echo $_GET['record_id']; ?>";

                                load_camera.style.display = "none";
                                canvas.width = video.videoWidth;
                                canvas.height = video.videoHeight;
                                context.drawImage(video, 0, 0, canvas.width, canvas.height);

                                captured_image.style.display = "none";

                                const imageData = canvas.toDataURL("image/png");
                                // console.log("Captured image data:", imageData);

                                stop_notes_Camera();
                                save_notes_CapturedImage(imageData, jobcard_no);
                            }

                            function save_notes_CapturedImage(imageData, jobcard_no) {
                                const video = document.getElementById("camera_notes");
                                const folder_path = "/notes/";
                                const section_name = "notes";

                                video.style.display = "none";

                                var formData = new FormData();

                                formData.append('image', imageData);
                                formData.append('jobcard_no', jobcard_no);
                                formData.append('folder_path', folder_path);
                                formData.append('section_name', section_name);

                                const xhr = new XMLHttpRequest();
                                xhr.open('POST', '../jobcards/save_camera.php', true);
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState == 4 && xhr.status == 200) {
                                        const response = xhr.responseText.trim();
                                        // FIX: previously used || which made the check always true
                                        if (response !== '0' && response !== '') {
                                            console.log('fileName: ' + response);
                                            alert('Photo saved successfully!');

                                            document.getElementById('image').style.display = 'block';
                                            document.getElementById('image').value = response;
                                        } else {
                                            alert('Error saving photo!');
                                        }
                                    }
                                };
                                xhr.send(formData);
                            }
                        </script>
                    </div>
                </div>

                <input type="text" id="image" name="image" style="display: none;"/>

                <button type="button" class="submit_btn" onclick="add_notes()">ADD</button>

            </div>


            <div id="note_save_response" style="color:white; margin-top:10px; font-weight:bold;"></div>
                <div
                style="display:flex; flex-direction: column; align-items: center; background-color: white; padding: 2vw 2vw 2vw 4vw; width: 100%; margin-top:20px; overflow-x: auto; box-sizing: border-box;" id="notes_table">
                </div>
            </div>
        </div>
        <script>

            function file_camera_type(){
                var image_type = document.getElementById("image_type").value;

                if (image_type == "file") {
                    document.getElementById("attach_file_div").style.display = "flex";
                    document.getElementById("camera_div").style.display = "none";
                } else if (image_type == "camera") {
                    document.getElementById("attach_file_div").style.display = "none";
                    document.getElementById("camera_div").style.display = "flex";
                } else {
                    document.getElementById("attach_file_div").style.display = "none";
                    document.getElementById("camera_div").style.display = "none";
                }
            }

            function upload_file() {
                var attach_note = document.getElementById("attach_note");
                var file = attach_note.files[0];
                var jobcard_no = "<?php echo $_GET['record_id']; ?>";

                if (file) {
                    var formData = new FormData();
                    formData.append('file', file);
                    formData.append('jobcard_no', jobcard_no);
                    formData.append('ajax_type', "note_section");
                    formData.append('section_name', "notes");
                    formData.append('file_save_path', "../jobcards/notes/");

                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                                console.log(xhr.responseText);

                            if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                var filename = xhr.responseText.replace('OK | ', '').trim();
                            
                                var uploadedFileInput = document.getElementById('uploaded_file_name');
                                if (!uploadedFileInput) {
                                    uploadedFileInput = document.createElement('input');
                                    uploadedFileInput.type = 'hidden';
                                    uploadedFileInput.id = 'uploaded_file_name';
                                    uploadedFileInput.name = 'uploaded_file_name';
                                    document.getElementById('attach_file_div').appendChild(uploadedFileInput);
                                }
                                uploadedFileInput.value = filename;
                                document.getElementById('image').value = filename;
                                alert("File uploaded successfully!");
                            } else {
                                alert('Error uploading file! Try again.');
                            }
                        }
                    };
                    xhr.open("POST", "../jobcards/upload_slip.php", true);
                    xhr.send(formData);
                }
            }

            function loadNotes() {
                var jobcard_id = document.getElementById("jobcard_no").value;

                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        document.getElementById("notes_table").innerHTML = xhr.responseText;
                    }
                };
                xhr.open("POST", "../jobcards/notes_table.ajax.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send("jobcard_id=" + encodeURIComponent(jobcard_id));
            }

            loadNotes();

            function add_notes() {
                var jobcard_no  = document.getElementById("jobcard_no").value;
                var reason      = document.getElementById("reason").value;
                var note        = document.getElementById("note").value;
                var image       = document.getElementById("image").value;

                if (reason === "") {
                    alert("Please select a reason.");
                    return false;
                }

                if (note.trim() === "") {
                    alert("Please enter a note.");
                    return false;
                }

                var form = new FormData();
                form.append("jobcard_no", jobcard_no);
                form.append("reason", reason);
                form.append("note", note);
                form.append("image", image);

                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (xhr.responseText.trim() === "success") {
                            // Clear inputs
                            document.getElementById("reason").value = "";
                            document.getElementById("note").value   = "";
                            document.getElementById("image").value  = "";
                            document.getElementById("attach_note").value  = "";
                            document.getElementById("camera_div").style.display = "none";
                            document.getElementById("attach_file_div").style.display = "none";
                            document.getElementById("image").style.display = "none";

                            stop_notes_Camera();
                            loadNotes(); // 👈 refresh the notes table
                        } else {
                            console.log(xhr.responseText);
                            alert("Error saving note, please try again.");
                        }
                    }
                };
                xhr.open("POST", "../jobcards/save_notes.ajax.php", true);
                xhr.send(form);
            }
        </script>
    </div>

        <script>
            function open_notesPopup() {
                event.preventDefault ? event.preventDefault() : (event.returnValue = false, event.stopPropagation());
                document.getElementById("notes_popup").style.display = "block";

            }

            function close_notesPopup() {
                document.getElementById("notes_popup").style.display = "none";
            }
        </script>