<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
session_start();

?>

<button onclick="window.location.href = '../jobcards/jobcard_actions.php?record_id=<?php echo $_GET['record_id']; ?>'"
    class="back_btn"> BACK </button>

<?php

// echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC LIMIT 1";

$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();

//get the current date and time
$current_date_time = date("Y-m-d H:i", strtotime("+2 hours"));

$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->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 = new input();
$notes->class("big_inputs");
$notes->type("text");
$notes->placeholder("NOTES");
$notes->name("note");
$notes->id("note");
$notes->addAttribute("style", "width: 50%;");

$reasons_label = new label();
$reasons_label->class("big_labels");
$reasons_label->for("reasons");
$reasons_label->value("REASONS");
$reasons_label->addAttribute("style", "font-size: 1.5vw; color: white;");

$notes_label = new label();
$notes_label->class("notes_heading");
$notes_label->for("notes");
$notes_label->value("NOTES");
$notes_label->addAttribute("style", "font-size: 4vw; 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_image = new file_upload();
$notes_image->class("inputs");
$notes_image->name("image");
$notes_image->id("image");
$notes_image->file_save_path("../jobcards/notes/");
$notes_image->file_type("png, jpg, jpeg");
$notes_image->style("width: 50%;");

// $add_notes = new button();
// $add_notes->value("ADD NOTES");
// $add_notes->onclick("add_notes()");
// $add_notes->id("notes_btn");

$make_notes_btn = new button();
$make_notes_btn->class("make_notes_btn");
$make_notes_btn->value("MAKE NOTES");
$make_notes_btn->onclick("open_notesPopup()");

$jobcard_id = new input();
$jobcard_id->type("hidden");
$jobcard_id->name("jobcard_id");
$jobcard_id->id("jobcard_id");
$jobcard_id->value($_GET['jc_no']);

$date_time = new input();
$date_time->type("hidden");
$date_time->name("date_time");
$date_time->id("date_time");
$date_time->value($current_date_time);

$blasting_label = new label();
$blasting_label->for("blasting");
$blasting_label->value("BLASTING");
$blasting_label->addAttribute("style", "margin-top: 1vw;font-weight: bold;font-size: 2vw;");

$blasting_start = new button();
$blasting_start->value("START");
$blasting_start->onclick("blasting_start()");

$blasting_stop = new button();
$blasting_stop->value("STOP");
$blasting_stop->onclick("blasting_stop()");

$blasting_meters = new input();
$blasting_meters->type("number");
$blasting_meters->placeholder("METERS");
$blasting_meters->name("meters");
$blasting_meters->class("jobcard_inputs");
$blasting_meters->id("meters");


?>

<div
    style="background-color: whitesmoke; height: fit-content; width: 98%; display: flex; flex-direction: column; margin-top: 1vw; border-radius: 2vw; align-items: center;">
    <br>
    <?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();

    $data_type = new input();
    $data_type->class("inputs");
    $data_type->type("hidden");
    $data_type->readonly();
    $data_type->value($data['type']);
    $data_type->add();

    $jobcard_id->add();

    $date_time->add();

    if ($data['type'] == "BLASTING") {

        $make_notes_btn->add();

        ?>

        <h1 class="heading_h1">BLASTING</h1>
        <div class="action_content">
            <?php
            $blasting_start->add();
            ?>
        </div>

        <?php
        // $next->add();

        $blasting_start_ajax = new js_ajax();
        $blasting_start_ajax->function_name("blasting_start");
        $blasting_start_ajax->insert("jobcard_timeline");
        $blasting_start_ajax->selected_div(".form_down input");
        $blasting_start_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=BLASTING_START,user_id={$_SESSION['user_id']}");
        $blasting_start_ajax->on_success("BLASTING STARTED");

    } else if ($data['type'] == "BLASTING_START") {

        ?>
            <h1 class="heading_h1">BLASTING</h1>
            <div class="action_content">
                <?php
                $blasting_stop->add();
                $make_notes_btn->add();
                ?>
            </div>

            <div class="blasting">
                <?php
                $blasting_meters->add();
                ?>
            </div>
            <br>

            <?php


            $blasting_stop_ajax = new js_ajax();
            $blasting_stop_ajax->function_name("blasting_stop");
            $blasting_stop_ajax->insert("jobcard_timeline");
            $blasting_stop_ajax->selected_div(".blasting input");
            $blasting_stop_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=BLASTING_STOP,user_id={$_SESSION['user_id']}");
            $blasting_stop_ajax->on_success("BLASTING STOPPED");

    } elseif ($data['type'] == "BLASTING_STOP") {

        ?>

            <h1 class="heading_h1">BLASTING</h1>
            <div class="action_content">
                <?php
                $blasting_start->add();
                $make_notes_btn->add();
                ?>
            </div>

            <br>

            <?php

            $blasting_start_ajax = new js_ajax();
            $blasting_start_ajax->function_name("blasting_start");
            $blasting_start_ajax->insert("jobcard_timeline");
            $blasting_start_ajax->selected_div(".form_down input");
            $blasting_start_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=BLASTING_START,meters=0,user_id={$_SESSION['user_id']}");
            $blasting_start_ajax->on_success("BLASTING STARTED");

    } else {

        ?>

            <h1 class="heading_h1">BLASTING</h1>
            <div class="action_content">
                <?php
                $blasting_start->add();
                $make_notes_btn->add();
                ?>
            </div>

            <?php

            $blasting_start_ajax = new js_ajax();
            $blasting_start_ajax->function_name("blasting_start");
            $blasting_start_ajax->insert("jobcard_timeline");
            $blasting_start_ajax->selected_div(".form_down input");
            $blasting_start_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=BLASTING_START,user_id={$_SESSION['user_id']}");
            $blasting_start_ajax->on_success("BLASTING STARTED");
    }

    ?>
</div>

<script>
    function next() {
        window.location.href = "../jobcards/jobcard_actions.php?record_id=<?php echo $_GET['record_id']; ?>&jobcard_id=<?php echo $_GET['jc_no']; ?>";
    }
    function open_notesPopup() {
        document.getElementById("notes_popup").style.display = "block";
    }

    function close_notesPopup() {
        document.getElementById("notes_popup").style.display = "none";
    }

</script>

<style>
    .notes_popup {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .notes_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;
    }

    .notes_images {
        width: 10vw;
        height: 10vw;
    }

    .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 {
        padding: 10px;
        border: 3px solid black;
        text-align: left;
        background-color: white;

        @media all and (min-width: 651px) and (max-width: 1050px) {
            font-size: 1.5em;
        }
    }

    td {
        padding: 10px;
        border: 3px solid black;
        text-align: left;
        background-color: white;

        @media all and (min-width: 651px) and (max-width: 1050px) {
            font-size: 1.5em;
        }
    }

    @media all and (min-width: 651px) and (max-width: 1050px) {

        .notes_content {
            width: 90%;
            height: 95%;
        }

        .close-btn {
            top: 0px;
            font-size: 15vw;
        }
    }
</style>

<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>
<br><br>

<div id="floating-block" style="position: none;">
    <?php
    $last_meters = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} AND type LIKE 'BLASTING%' ORDER BY record_id DESC");

    // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} AND type LIKE 'BLASTING%' ORDER BY record_id DESC";
    
    $total_meters = 0;
    while ($meters_data = $last_meters->fetch_assoc()) {
        $total_meters += $meters_data['meters'];
    }

    echo "<h3>CURRENT TOTAL METERS BLASTING: </h3>";

    echo "<h3>" . $total_meters . " METERS</h3>";

    ?>
</div>