<?php include "../../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
session_start();

$jobcard_data_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = '{$_GET['record_id']}'");
$jobcard_data = $jobcard_data_res->fetch_assoc();

$user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '{$_SESSION['user_id']}'");
$users = $user_res->fetch_assoc();

/////////////////////////////// NOTES POPUP SECTION ////////////////////////////////////////////////

$jobcard_id = new input();
$jobcard_id->type("hidden");
$jobcard_id->name("jobcard_id");
$jobcard_id->id("jobcard_id");
$jobcard_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");

/////////////////////////////////////////////////////////////////////////////////////////////////////

$make_notes_btn = new button();
$make_notes_btn->value("MAKE NOTES");
$make_notes_btn->onclick("open_notesPopup()");
?>

<style>
    @media screen and (max-width: 651px) {

        .main_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }

        .close-btn {
            position: absolute;
            /* top: 10px; */
            right: 15px;
            font-weight: bolder;
            font-size: 15vw;
            cursor: pointer;
            color: white;
        }

    }

    .main_div {
        display: flex;
        flex-direction: column;
        align-items: center;
        background: white;
        /* justify-content: space-around; */
        flex-wrap: wrap;
        align-content: space-around;
        /* height: 210vw; */
        border-radius: 3vw;
        margin: 1vw;
        padding: 4vw;
    }

    .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;
        }
    }
</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['jobcard_no']}' 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();
        $notes_label->add();
        ?>

        <div style="display: flex; flex-direction: column;">
            <?php
            $reasons_label->add();
            $reasons->add();
            $notes_sub_label->add();
            ?>
        </div>

        <div id="normal_section" style="display: flex; flex-direction: column;align-items: center;">
            <textarea name="note" id="note" class="inputs" style="width: 70vw" rows="5"></textarea>


            <?php
            // $notes->add();
            

            new camera('image', $_GET['record_id'], "../jobcards/notes/", "notes_images");
            ?>
            <input type="text" style="display: none;" id="image" name="image">

            <?php
            $add_notes->add();

            $notes_ajax = new js_ajax();
            $notes_ajax->function_name("add_notes");
            $notes_ajax->insert("notes");
            $notes_ajax->selected_div(".notes_content input , .notes_content select , .notes_content textarea");
            $notes_ajax->submit_btn_id("notes_btn");
            $notes_ajax->on_success("NOTE SAVED");
            ?>


            <?php

            $notes_res = $db->query("notes", "SELECT * FROM notes WHERE jobcard_id = '{$_GET['jobcard_no']}' AND reason NOT LIKE '%BIT%'");

            if ($notes_res->num_rows > 0) {
                while ($row = $notes_res->fetch_assoc()) {
                    $table_data = $table_data . "<tr>
                <td>" . $row['reason'] . "</td>
                <td>" . $row['note'] . "</td>
                <td>" . $row['image'] . "</td>
                <td>" . $row['date_time'] . "</td>
                </tr>";
                }
                $notes = $notes_res->fetch_assoc();

            } else {
                $table_data = $table_data . "<tr>
            <td colspan='4'>NO NOTES RECORDED</td>
            </tr><br>";

            }
            ?>

            <div style="background-color: white;padding-left: 2vw;padding-top: 2vw; width: 100%;">
                <table>
                    <tr>
                        <th>REASON</th>
                        <th>NOTE</th>
                        <th>IMAGE</th>
                        <th>DATE TIME</th>
                    </tr>
                    <?php echo $table_data; ?>
                </table>
                <br>
            </div>
        </div>
    </div>
    <br><br>
</div>


<div class="main_div">
    <!-- <form id="imageForm" enctype="multipart/form-data">
        <label for="" class="create_details_label">UPLOAD IMAGE</label>
        <input type="file" name="images[]" multiple accept="image/*" class="create_details_input">

        <div id="descriptions"></div>

        <button class="submit_btn">Upload</button>
    </form> -->

    <!-- <video style="display: none;" id="camera_install_1" autoplay playsinline></video>
    <br>

    <button id="open_camera_install_1" class="submit_btn" onclick="open_Install_1_Camera()">Open
        Camera</button>

    <div id="load_camera_install_1" style="display: none; width: 100%; justify-content: center;">
        <button class="submit_btn" onclick="capture_Install_1_Photo()">Capture Photo</button>
        <button class="submit_btn" onclick="stop_Install_1_Camera()">Stop Camera</button>
    </div>

    <div id="captured_image_install_1" style="display:none">
        <h3>Captured Image:</h3>
        <canvas id="snapshot_install"></canvas>
    </div>

    <script>
        let stream_install;

        async function open_Install_1_Camera() {
            const video = document.getElementById("camera_install_1");
            const load_camera = document.getElementById("load_camera_install_1");
            const open_camera = document.getElementById("open_camera_install_1");

            try {

                stream_install = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "environment" },
                    audio: false
                });

                const video = document.getElementById("camera_install_1");
                video.srcObject = stream_install;
                video.style.display = "block";

                load_camera.style.display = "flex";
                open_camera.style.display = "none";


            } catch (error) {
                alert("Error accessing camera: " + error.message);
            }
        }

        function capture_Install_1_Photo() {
            const video = document.getElementById("camera_install_1");
            const canvas = document.getElementById("snapshot_install");
            const context = canvas.getContext("2d");
            const captured_image = document.getElementById("captured_image_install_1");
            const load_camera = document.getElementById("load_camera_install_1");
            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");

            stop_Install_1_Camera();
            saveCapturedImage(imageData, jobcard_no);
        }

        function stop_Install_1_Camera() {
            const open_camera = document.getElementById("open_camera_install_1");
            const load_camera = document.getElementById("load_camera_install_1");
            const video = document.getElementById("camera_install_1");

            video.style.display = "none";
            load_camera.style.display = "none";
            open_camera.style.display = "block";
            if (stream_install) {
                stream_install.getTracks().forEach(track => track.stop());
                stream_install = null;
                document.getElementById("camera_install_1").srcObject = null;
            }
        }

        function saveCapturedImage(imageData, jobcard_no) {
            const video = document.getElementById("camera_install_1");
            const folder_path = "../jobcards/pump/install_images/";
            const section_name = "install";

            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) {
                    if (xhr.responseText != '0') {
                        console.log('fileName: ' + xhr.responseText);
                        alert('Photo saved successfully!');
                        if ('install' != '') {

                            const fileName = xhr.responseText.trim();
                            const imagePath = folder_path + fileName;

                            // show image preview
                            const preview = document.getElementById('install_1_preview');
                            preview.src = imagePath;
                            preview.style.display = 'block';
                            preview.style.width = '80%';
                            preview.style.marginTop = '10px';

                            // store filename in hidden input
                            document.getElementById('install_1_image').value = fileName;

                            document.getElementById('install_1_image').style.display = 'block';
                            document.getElementById('install_1_image').value = xhr.responseText;
                        }
                    } else {
                        alert('Error saving photo!');

                    }
                }
            };
            xhr.send(formData);
        }

    </script>

    <img src="" id="install_1_preview" style="display:none;" />
    <input type='text' style="display: none;" class="inputs" id='install_1_image' name='install_1_image'> -->

    <div id="response"></div>


    <div id="install_cameras_container"></div>

    <button class="submit_btn" onclick="addInstallCamera()">Add Camera</button>

    <script>
        let installIndex = 0;
        let streams = {}; // store streams per camera

        function addInstallCamera() {
            installIndex++;

            const i = installIndex;

            const html = `
            <div class="install_camera_block" id="install_block_${i}">
                <hr>

                <video style="display:none;" id="camera_install_${i}" autoplay playsinline></video>
                <br>

                <button id="open_camera_install_${i}" class="submit_btn"
                    onclick="openInstallCamera(${i})">
                    Open Camera ${i}
                </button>

                <div id="load_camera_install_${i}" style="display:none; width:100%; justify-content:center;">
                    <button class="submit_btn" onclick="captureInstallPhoto(${i})">Capture Photo</button>
                    <button class="submit_btn" onclick="stopInstallCamera(${i})">Stop Camera</button>
                </div>

                <div id="captured_image_install_${i}" style="display:none">
                    <h3>Captured Image:</h3>
                    <canvas id="snapshot_install_${i}"></canvas>
                </div>

                <img src="" id="install_${i}_preview" style="display:none; width:80%; margin-top:10px;" />
                <input type="hidden" id="install_${i}_image" name="install_${i}_image">
            </div>
    `;

            document.getElementById("install_cameras_container")
                .insertAdjacentHTML("beforeend", html);
        }

        async function openInstallCamera(i) {
            const video = document.getElementById(`camera_install_${i}`);
            const load = document.getElementById(`load_camera_install_${i}`);
            const openBtn = document.getElementById(`open_camera_install_${i}`);

            try {
                streams[i] = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "environment" },
                    audio: false
                });

                video.srcObject = streams[i];
                video.style.display = "block";

                load.style.display = "flex";
                openBtn.style.display = "none";
            } catch (err) {
                alert("Camera error: " + err.message);
            }
        }

        function captureInstallPhoto(i) {
            const video = document.getElementById(`camera_install_${i}`);
            const canvas = document.getElementById(`snapshot_install_${i}`);
            const ctx = canvas.getContext("2d");
            const load = document.getElementById(`load_camera_install_${i}`);
            const jobcard_no = "<?php echo $_GET['record_id']; ?>";

            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            ctx.drawImage(video, 0, 0);

            load.style.display = "none";

            const imageData = canvas.toDataURL("image/png");

            stopInstallCamera(i);
            saveCapturedImage(imageData, jobcard_no, i);
        }

        function stopInstallCamera(i) {
            const video = document.getElementById(`camera_install_${i}`);
            const load = document.getElementById(`load_camera_install_${i}`);
            const openBtn = document.getElementById(`open_camera_install_${i}`);

            video.style.display = "none";
            load.style.display = "none";
            openBtn.style.display = "block";

            if (streams[i]) {
                streams[i].getTracks().forEach(t => t.stop());
                streams[i] = null;
                video.srcObject = null;
            }
        }

        function saveCapturedImage(imageData, jobcard_no, i) {
            const folder_path = "../jobcards/pump/install_images/";
            const section_name = "install";

            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", "../save_camera.php", true);
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (xhr.responseText != '0') {
                        console.log('fileName: ' + xhr.responseText);
                        alert('Photo saved successfully!');
                        if ('sample' != '') {
                            const fileName = xhr.responseText.trim();
                            const imagePath = folder_path + fileName;

                            const preview = document.getElementById(`install_${i}_preview`);
                            preview.src = imagePath;
                            preview.style.display = "block";
                            preview.style.width = '80%';
                            preview.style.marginTop = '10px';

                            document.getElementById(`install_${i}_image`).value = fileName;

                            document.getElementById(`install_${i}_image`).style.display = 'block';
                            document.getElementById(`install_${i}_image`).value = xhr.responseText;
                        }
                    } else {
                        alert("Error saving image");
                    }
                }
            };
            xhr.send(formData);
        }

    </script>

</div><br>

<div class="main_div">
    <h2 class="create_h2">JOCARD</h2>

    <?php
    $make_notes_btn->add();
    ?>
    <br>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">ATTENDED BY</label>
        <input type="text" name="attended_by" id="attended_by" class="create_details_input"
            value="<?php echo $jobcard_data['attended_by'] ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">CRACK</label>
        <input type="text" name="crack" id="crack" class="create_details_input"
            value="<?php echo $jobcard_data['crack'] ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">CABLE METERS</label>
        <input type="text" name="cable_meters" id="cable_meters" class="create_details_input"
            value="<?php echo $jobcard_data['cable_meters'] ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="hdpe_meters_label" class="create_details_label" style="width: 100%;">HDPE METERS</label>
        <input type="text" name="hdpe_meters" id="hdpe_meters" class="create_details_input"
            value="<?php echo $jobcard_data['hdpe_meters'] ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">BOREHOLE METERS</label>
        <input type="text" name="borehole_meters" id="borehole_meters" class="create_details_input"
            value=" <?php echo $jobcard_data['borehole_meters'] ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">PROBLEM DESCRIPTION</label>
        <textarea name="problem_description" id="problem_description" rows="5" class="create_details_input"
            style="font-size: 3em;" value="<?php echo $jobcard_data['problem_description'] ?>"></textarea>
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">SOLUTION</label>
        <textarea name="problem_solution" id="problem_solution" rows="5" class="create_details_input"
            style="font-size: 3em;" value="<?php echo $jobcard_data['problem_solution'] ?>"></textarea>
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">INSTALLED BY</label>
        <input type="text" name="installed_by" id="installed_by" class="create_details_input"
            value="<?php echo $users['username'] ?>">
    </div>

    <?php
    $complete_jobcard = new button();
    $complete_jobcard->value('COMPLETE');
    $complete_jobcard->onclick('complete()');
    $complete_jobcard->add();

    $complete_ajax = new js_ajax();
    $complete_ajax->function("complete");
    $complete_ajax->update("pump_installation");
    $complete_ajax->selected_div(".main_div input, .main_div select");
    $complete_ajax->on_success("JOBCARD COMPLETED");
    $complete_ajax->redirect('../jobcards/jobcard_summary.php?record_id=' . $_GET['record_id'] . '&jobcard_no=' . $_GET['jobcard_no']);

    ?>
</div>

<script>

    document.querySelector('input[type="file"]').addEventListener('change', function () {
        const container = document.getElementById('descriptions');
        container.innerHTML = "";

        Array.from(this.files).forEach((file, index) => {
            container.innerHTML += `
            <div>
                <strong>${file.name}</strong><br>
                <input type="text" name="descriptions[]" placeholder="Image description">
            </div>
        `;
        });
    });

    document.getElementById('imageForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);

        fetch('upload_images.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.text())
            .then(data => {
                document.getElementById('response').innerHTML = data;
            })
            .catch(err => console.error(err));
    });

    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>