<?php
/**
 * includes/notes_popup.php
 *
 * Reusable notes popup — include once per page.
 *
 * Required before including:
 *   $record_id  (int)  — the jobcard record_id
 *
 * Provides these JS functions to the page:
 *   open_notesPopup()   — show the popup
 *   close_notesPopup()  — hide the popup
 *   add_notes()         — save a note via AJAX
 *   loadNotes()         — refresh the notes table
 *
 * Usage:
 *   $record_id = intval($_GET['record_id']);
 *   include '../../includes/notes_popup.php';
 */

if (!isset($record_id)) {
    $record_id = intval($_GET['record_id'] ?? 0);
}
?>

<style>
.notes-popup {
    display: none;
    position: fixed;
    z-index: 1000;
    inset: 0;
    background-color: rgba(0, 0, 0, 0.5);
}
.notes-popup.is-open {
    display: block;
}
.notes-popup__content {
    background: linear-gradient(90deg, #110151, #3331e7);
    margin: 3% auto;
    padding: 20px;
    border-radius: 10px;
    width: 80%;
    max-height: 85vh;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    position: relative;
    overflow-y: auto;
}
.notes-popup__close {
    position: absolute;
    top: 10px;
    right: 15px;
    font-size: 5vw;
    font-weight: bold;
    cursor: pointer;
    color: white;
    background: none;
    border: none;
    line-height: 1;
}
.notes-popup__table-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: white;
    padding: 2vw;
    width: 100%;
    margin-top: 20px;
    overflow-x: auto;
    box-sizing: border-box;
}
@media (min-width: 651px) and (max-width: 1050px) {
    .notes-popup__content { width: 90%; max-height: 95vh; }
    .notes-popup__close { font-size: 15vw; top: 0; }
}
</style>

<div class="notes-popup" id="notes_popup">
    <div class="notes-popup__content">

        <button class="notes-popup__close" onclick="close_notesPopup()" aria-label="Close">&times;</button>

        <!-- Hidden fields read by add_notes() -->
        <input type="hidden" id="jobcard_no" name="jobcard_no" value="<?= $record_id ?>">

        <label for="notes" class="notes_heading" style="color:white;margin:1px;">NOTES</label>

        <div style="display:flex;flex-direction:column;">
            <label for="reason" class="big_labels" style="color:white;">REASONS</label>
            <select id="reason" name="reason" class="big_inputs">
                <option value="">-- SELECT --</option>
                <option>ARRIVED AT LOCATION</option>
                <option>WAITING FOR CLIENT</option>
                <option>TRAVELING TO SITE</option>
                <option>ARRIVED ON SITE</option>
                <option>TALKING TO CLIENT</option>
                <option>FETCHING MONEY</option>
                <option>BRAKING</option>
                <option>CHANGING RIEMER</option>
                <option>STOP</option>
                <option>PENDING</option>
                <option>START</option>
                <option>INSTALLING</option>
                <option>RECEIVED</option>
                <option>BACK TO WORKSHOP</option>
                <option>OTHER</option>
            </select>

            <label for="note" class="big_labels" style="color:white;">NOTES</label>
        </div>

        <div style="display:flex;flex-direction:column;align-items:center;">
            <textarea id="note" name="note" class="inputs"
                      style="width:70vw;font-size:3em;" rows="5"></textarea>

            <label for="image_type" class="big_labels" style="color:white;">UPLOAD TYPE</label>
            <select id="image_type" name="image_type" onchange="notes_file_camera_type()" class="big_inputs">
                <option value="">-- SELECT --</option>
                <option value="file">ATTACH FILE</option>
                <option value="camera">CAMERA</option>
            </select>

            <div style="background:white;padding:2vw;display:flex;flex-direction:column;align-items:center;width:100%;">

                <!-- File upload -->
                <div id="notes_attach_file_div" style="display:none;flex-direction:column;align-items:center;width:100%;">
                    <label class="big_labels">ATTACH FILE</label>
                    <input type="file" id="attach_note" name="attach_note"
                           style="width:90%;" class="big_inputs"
                           onchange="notes_upload_file()">
                </div>

                <!-- Camera capture -->
                <div id="notes_camera_div" style="display:none;flex-direction:column;align-items:center;width:100%;">
                    <video id="camera_notes" style="display:none;width:400px;height:300px;border:3px solid #ccc;border-radius:2vw;margin-top:10px;" autoplay playsinline></video>

                    <button id="open_camera_notes" class="submit_btn" onclick="notes_openCamera()">Open Camera</button>

                    <div id="load_camera_notes" style="display:none;width:100%;justify-content:center;">
                        <button class="submit_btn" onclick="notes_capturePhoto()">Capture Photo</button>
                        <button class="submit_btn" onclick="notes_stopCamera()">Stop Camera</button>
                    </div>

                    <canvas id="snapshot_notes" style="display:none;width:400px;height:300px;border:3px solid #ccc;border-radius:2vw;margin-top:10px;"></canvas>
                </div>

            </div>

            <!-- Stores the uploaded/captured filename -->
            <input type="hidden" id="notes_image" name="notes_image" value="">

            <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 id="notes_table" class="notes-popup__table-wrap"></div>

    </div>
</div>

<script>
(function () {

    /* ── Popup open / close ─────────────────────────────── */
    window.open_notesPopup = function (e) {
        if (e && e.preventDefault) e.preventDefault();
        document.getElementById('notes_popup').classList.add('is-open');
        loadNotes();
    };
    window.close_notesPopup = function () {
        document.getElementById('notes_popup').classList.remove('is-open');
        notes_stopCamera();
    };

    /* ── Toggle file vs camera ──────────────────────────── */
    window.notes_file_camera_type = function () {
        var v  = document.getElementById('image_type').value;
        var fd = document.getElementById('notes_attach_file_div');
        var cd = document.getElementById('notes_camera_div');
        fd.style.display = (v === 'file')   ? 'flex' : 'none';
        cd.style.display = (v === 'camera') ? 'flex' : 'none';
    };

    /* ── Camera helpers ─────────────────────────────────── */
    var _stream = null;

    window.notes_openCamera = function () {
        navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
            .then(function (stream) {
                _stream = stream;
                var v = document.getElementById('camera_notes');
                v.srcObject = stream;
                v.style.display = 'block';
                document.getElementById('load_camera_notes').style.display = 'flex';
                document.getElementById('open_camera_notes').style.display = 'none';
            })
            .catch(function (err) { alert('Camera error: ' + err.message); });
    };

    window.notes_stopCamera = function () {
        if (_stream) {
            _stream.getTracks().forEach(function (t) { t.stop(); });
            _stream = null;
        }
        var v = document.getElementById('camera_notes');
        if (v) { v.srcObject = null; v.style.display = 'none'; }
        var lc = document.getElementById('load_camera_notes');
        if (lc) lc.style.display = 'none';
        var oc = document.getElementById('open_camera_notes');
        if (oc) oc.style.display = 'block';
    };

    window.notes_capturePhoto = function () {
        var video    = document.getElementById('camera_notes');
        var canvas   = document.getElementById('snapshot_notes');
        var ctx      = canvas.getContext('2d');
        var jobcard  = document.getElementById('jobcard_no').value;

        canvas.width  = video.videoWidth;
        canvas.height = video.videoHeight;
        ctx.drawImage(video, 0, 0);
        canvas.style.display = 'block';

        var imageData = canvas.toDataURL('image/png');
        notes_stopCamera();
        _saveCapture(imageData, jobcard);
    };

    function _saveCapture(imageData, jobcard_no) {
        var fd = new FormData();
        fd.append('image',        imageData);
        fd.append('jobcard_no',   jobcard_no);
        fd.append('folder_path',  '../jobcards/notes/');
        fd.append('section_name', 'notes');

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '../jobcards/save_camera.php', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var r = xhr.responseText.trim();
                if (r && r !== '0') {
                    document.getElementById('notes_image').value = r;
                    alert('Photo saved successfully!');
                } else {
                    alert('Error saving photo.');
                }
            }
        };
        xhr.send(fd);
    }

    /* ── File upload helper ─────────────────────────────── */
    window.notes_upload_file = function () {
        var input     = document.getElementById('attach_note');
        var file      = input.files[0];
        var jobcard   = document.getElementById('jobcard_no').value;
        if (!file) return;

        var fd = new FormData();
        fd.append('file',           file);
        fd.append('jobcard_no',     jobcard);
        fd.append('ajax_type',      'note_section');
        fd.append('section_name',   'notes');
        fd.append('file_save_path', '../jobcards/notes/');

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText.includes('OK')) {
                    var filename = xhr.responseText.replace('OK | ', '').trim();
                    document.getElementById('notes_image').value = filename;
                    alert('File uploaded successfully!');
                } else {
                    alert('Upload failed. Try again.');
                }
            }
        };
        xhr.open('POST', '../jobcards/upload_slip.php', true);
        xhr.send(fd);
    };

    /* ── Load notes table ───────────────────────────────── */
    window.loadNotes = function () {
        var jobcard = 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));
    };

    /* ── Save note ──────────────────────────────────────── */
    window.add_notes = function () {
        var jobcard = document.getElementById('jobcard_no').value;
        var reason  = document.getElementById('reason').value;
        var note    = document.getElementById('note').value.trim();
        var image   = document.getElementById('notes_image').value;

        if (!reason) { alert('Please select a reason.');   return; }
        if (!note)   { alert('Please enter a note.');       return; }

        var fd = new FormData();
        fd.append('jobcard_no', jobcard);
        fd.append('reason',     reason);
        fd.append('note',       note);
        fd.append('image',      image);

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText.trim() === 'success') {
                    /* clear form */
                    document.getElementById('reason').value      = '';
                    document.getElementById('note').value        = '';
                    document.getElementById('notes_image').value = '';
                    document.getElementById('attach_note').value = '';
                    document.getElementById('image_type').value  = '';
                    document.getElementById('notes_attach_file_div').style.display = 'none';
                    document.getElementById('notes_camera_div').style.display      = 'none';
                    notes_stopCamera();
                    loadNotes();
                } else {
                    console.error(xhr.responseText);
                    alert('Error saving note. Please try again.');
                }
            }
        };
        xhr.open('POST', '../jobcards/save_notes.ajax.php', true);
        xhr.send(fd);
    };

}());
</script>