<?php
require_once(ROOT_URL . '/includes/master/form_functions.php');

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $d[2]);
$stmt->execute();
$rc = $stmt->get_result();
$stmt->close();
$cd = mysqli_fetch_array($rc);
$repid = $d[2];

/* image header/count (match reload) */
$directory = 'images/report_images/';
$pattern   = $d[2] . '_*.jpg';
$images    = glob($directory . $pattern);
$filteredImages = array_filter($images, function ($image) {
    return strpos($image, 'thumb') === false;
});
$imageCount   = count($filteredImages);
$imageMessage = "(" . $imageCount . " images found)";
$imageDisplay = $imageCount > 0 ? "display: block;" : "display: none;";

/* image default mode */
if ($_REQUEST['formnumber'] == '101' || $_REQUEST['formnumber'] == '700' || $_REQUEST['formnumber'] == '701') {
    $iMode = 1;
    $iCheck = "checked";
} else {
    $iMode = 0;
    $iCheck = "";
}
if (file_exists('images/tags/' .  $d[2] . '.jpg')) {
    $tagFound = 1;
} else {
    $tagFound = 0;
}
?>
<script>
$('#navBox').html(
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
    '<li class="breadcrumb-item"><a href="<?= $_SESSION['returnLanding'] ?>"><?= getClientName($cd['clientnumber']) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
    '<li class="breadcrumb-item active">Reporting on : <?= $cd['desc'] ?> / <?= $cd['serialnumber'] ?></li>'
);
</script>
<script src="<?= ROOT_URL ?>/src/main.min.js"></script>
<link rel="stylesheet" href="<?= ROOT_URL ?>/src/style.css?v=5.0.3">
<style>
.lead,
.control-label {
    font-size: 18px
}

.lead {
    font-weight: 400;
    text-transform: uppercase
}

#loadingObject {
    display: none;
    position: fixed;
    width: 100%;
    height: 1vh;
    top: 200px
}

.pointer {
    cursor: pointer
}
</style>

<h2 id="InfoBox" class="alert alert-info text-center m-0">REPORTING ON:
    <?= getReportDesc($_REQUEST['formnumber'], 'formtype') ?> | <?= htmlspecialchars($cd['desc']) ?>
</h2>

<div id="formContainer">
    <div id="D<?= $d[2] ?>" class="itemDetail alert alert-dark mt-n2" style="display:none; margin-bottom:0px">
        <?php require_once(ROOT_URL . '/forms/elements/form_details.php'); ?>
    </div>
    <div class="text-center mb-4">
        <a href="javascript:void(0)" id="B<?= $d[2] ?>" class="btn btn-dark btn-block mt-n2"
            onClick="showDetails('<?= $d[2] ?>')" data-mdb-tooltip-init data-mdb-placement="top"
            data-mdb-trigger="hover" title="Show item details">
            <div class="mt-4">Show item details</div>
        </a>
    </div>

    <form id="F<?= $repid ?>" class="form-horizontal">
        <fieldset>
            <?php require_once('forms/items/' . $_REQUEST['formnumber'] . '.php'); ?>

            <div class="mt-3" style="<?= $displayMode ?>">
                <div class="card border border-info">
                    <div class="card-body">
                        <?php require_once('forms/items/base_data.php'); ?>
                    </div>
                </div>
            </div>

            <input type="hidden" name="clientnumber" id="clientnumber" value="<?= $d[0] ?>" />
            <?php if ($_REQUEST['formnumber'] == '901') { ?>
            <input type="hidden" name="FUNCTION" id="FUNCTION" value="createITE" />
            <?php } else { ?>
            <input type="hidden" name="itemnumber" id="itemnumber" value="<?= $d[2] ?>" />
            <input type="hidden" name="locnumber" id="locnumber" value="<?= $d[1] ?>" />
            <input type="hidden" name="FUNCTION" id="FUNCTION" value="create" />
            <input type="hidden" name="reptype" id="reptype" value="<?= $_REQUEST['formnumber'] ?>" />
            <?php } ?>

            <input type="hidden" name="imageMode" id="imageSet" value="<?= $iMode ?>" />
            <input type="hidden" name="tagMode" id="tagSet" value="" />
            <input type="hidden" name="pageMode" id="pageSet" value="1" />
            <input type="hidden" id="btn_save" value="save" />
            <input type="hidden" id="btn_later" value="save" />
            <input type="hidden" name="tenant" value="<?= TENANT_URL ?>" />
        </fieldset>
    </form>

    <div class="row mt-4">
        <div class="col-12 col-md-12 text-center">
            <div class="card" id="card-<?= $d[2] ?>">
                <div class="card-header" id="notesCardHead-<?= $d[2] ?> pointer" onclick="toggleNotes('<?= $d[2] ?>')">
                    Item Notes
                    <a href="javascript:void(0)" class="float-end me-2 text-light">
                        <i class="fad fa-chevrons-down" id="toggleIcon-<?= $d[2] ?>"></i>
                    </a>
                </div>
                <div class="card-body" id="cardBody-<?= $d[2] ?>" style="display: none;">
                    <?php
                    $notecall = mysqli_query($GLOBALS['con'], "SELECT `itemnotes` FROM `itemdetails` WHERE `itemnumber`='" . $d[2] . "'") or die(mysqli_error($GLOBALS['con']));
                    $notedata = mysqli_fetch_array($notecall);
                    ?>
                    <textarea id="item_notes" class="form-control" rows="10"><?= $notedata['itemnotes'] ?></textarea>
                    <div class="col-12 col-md-12 text-center">
                        <a href="javascript:void(0)" onclick="saveNotes()" class="btn btn-white" data-mdb-tooltip-init
                            data-mdb-placement="top" data-mdb-trigger="hover" title="Save notes">Update Notes</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="spacer"></div>

    <!-- Images -->
    <div class="col-12 col-md-12 text-center">
        <div class="card" id="imageCard-<?= $d[2] ?>">
            <div class="card-header" id="imageCardHead-<?= $d[2] ?>" onclick="toggleImages('<?= $d[2] ?>')">
                Item Images <?= $imageMessage ?>
                <a href="javascript:void(0)" class="float-end me-2 text-light">
                    <i class="fad fa-chevrons-down" id="imageToggleIcon-<?= $d[2] ?>"></i>
                </a>
            </div>
            <div class="card-body" id="imageCardBody-<?= $d[2] ?>" style="<?= $imageDisplay ?>">
                <div class="row">
                    <?php foreach (range(1, 6) as $file) { ?>
                    <div class="col-md-2 mb-4" style="position:relative">
                        <div class="col-12 col-md-12 text-center">
                            <div class="card">
                                <div class="card-header">Report Image #<?= $file ?></div>
                                <div id="crop<?= $file ?>" class="card-body">
                                    <div class="slim" data-ratio="free" data-did-remove="reportImageRemoved"
                                        data-force-type="jpg" data-label="Select Image"
                                        data-service="images/repimage_save.php" data-filter-sharpen="20"
                                        data-push="true" data-meta-userid="<?= $d[2] ?>"
                                        data-meta-imageid="<?= $d[2] ?>_<?= $file ?>" data-size="1024,1024"
                                        data-meta-tenant="<?= TENANT_URL ?>">
                                        <?php if (file_exists('images/report_images/' . $d[2] . '_' . $file . '.jpg')) { ?>
                                        <img src="images/report_images/<?= $d[2] ?>_<?= $file ?>.jpg?<?= rand() ?>"
                                            alt="Report Image #<?= $file ?>">
                                        <?php } ?>
                                        <input type="file" name="file" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="loadingObject" style="display: none">
    <div class="col-12 text-center">
        <h1>
            <i class="fad fa-spinner fa-pulse fa-3x fa-fw"
                style="--fa-primary-color:#0055A6; --fa-secondary-color:gray;"></i><br>
            Saving Inspection Data<br><small>Please wait</small>
        </h1>
    </div>
</div>

<script>
// Notes
function toggleNotes(cardId) {
    const body = document.getElementById(`cardBody-${cardId}`);
    const icon = document.getElementById(`toggleIcon-${cardId}`);
    const head = document.getElementById(`notesCardHead-${cardId}`);
    const open = body.style.display === "none";
    body.style.display = open ? "block" : "none";
    icon.classList.toggle('fa-chevrons-down', !open);
    icon.classList.toggle('fa-chevrons-up', open);
    head.classList.toggle('bg-success', open);
}

// Images
function toggleImages(cardId) {
    const body = document.getElementById(`imageCardBody-${cardId}`);
    const icon = document.getElementById(`imageToggleIcon-${cardId}`);
    const head = document.getElementById(`imageCardHead-${cardId}`);
    const open = body.style.display === "none";
    body.style.display = open ? "block" : "none";
    icon.classList.toggle('fa-chevrons-down', !open);
    icon.classList.toggle('fa-chevrons-up', open);
    head.classList.toggle('bg-success', open);
}

// Notes save
function saveNotes() {
    const notes = document.getElementById('item_notes').value;
    fetch(ROOT_URL + '/functions/notesSave.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            item: '<?= $d[2] ?>',
            notes: notes,
            tenant: TENANT_URL
        })
    }).then(r => r.text()).then(t => {
        if (t.trim() === "success") {
            showResponse('success', 'Notes updated successfully');
        }
    }).catch(console.error);
}

function killcrop() {}

function reportImageRemoved(data) {
    const name = data.input.name;
    fetch('images/repimage_remove.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            image: name
        })
    }).then(r => r.text()).then(() => {
        showResponse('success', 'Image removed successfully');
    }).catch(console.error);
}

// modal switches
function pm() {
    document.getElementById('pageSet').value =
        document.getElementById('pageMode').checked ? '0' : '1';
}

function ia() {
    document.getElementById('imageSet').value =
        document.getElementById('ImageAdd').checked ? '1' : '0';
}

function ta() {
    document.getElementById('tagSet').value =
        document.getElementById('TagAdd').checked ? '1' : '0';
}

document.addEventListener('DOMContentLoaded', function() {
    const btnSave = document.getElementById('btn_save');
    const btnLater = document.getElementById('btn_later');

    // Preflight modal (with Tag toggle)
    btnSave.addEventListener('click', function(event) {
        event.preventDefault();
        const bodyEl = document.getElementById('imageCardBody-<?= $d[2] ?>');
        let hasImages = false;

        if (bodyEl) {
            const slots = bodyEl.querySelectorAll('.slim');
            for (const slot of slots) {
                // saved image present?
                const existing = slot.querySelector('img');
                const saved = existing && /images\/report_images\//.test(existing.src);

                // pending upload selected?
                const inp = slot.querySelector('input[type="file"]');
                const pending = inp && inp.files && inp.files.length > 0;

                if (saved || pending) {
                    hasImages = true;
                    break;
                }
            }
        }
        const attachImagesBlock = hasImages ?
            `
            <div class="col-12 col-md-4 mb-3">
            <h6><i class="fad fa-solid fa-images"></i> Attach Images:</h6>
            <div class="d-flex justify-content-center align-items-center">
                <span class="me-2">No</span>
                <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="ImageAdd" onchange="ia()">
                <label class="form-check-label" for="ImageAdd">Yes</label>
                </div>
            </div>
            </div>` :
            `
            <div class="col-12 col-md-4 mb-3">
            <h6><i class="fad fa-solid fa-images"></i> Attach Images:</h6>
            <div class="d-flex justify-content-center align-items-center">
                <span class="text-warning">No images found</span>
            </div>
            </div>`;

        const dest = `
      <div class="container border mt-3">
        <div class="row">
          <div class="col-12 col-md-6 bg-info text-light py-5 text-center">
            <h5>The status of this Inspection is <strong>${document.getElementById('result').value}</strong></h5>
          </div>
          <div class="col-12 col-md-6 py-5 border-info text-center">
            <h5>The frequency of this Inspection is <strong>${document.getElementById('frequency').value} Months</strong></h5>
          </div>
        </div>
        <div class="row text-center mt-4">
          <div class="col-12 col-md-4 mb-3">
            <h6><i class="fad fa-solid fa-mobile-rotate"></i> Page Orientation:</h6>
            <div class="d-flex justify-content-center align-items-center">
              <span class="me-2">Portrait</span>
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="pageMode" onchange="pm()">
                <label class="form-check-label" for="pageMode">Landscape</label>
              </div>
            </div>
          </div>
          ${attachImagesBlock}
           <?php if ($tagFound == 1) { ?>
                        <div class="col-12 col-md-4 mb-3">
                    <h6><i class="fad fa-solid fa-tags"></i> Insert Asset Tag Image:</h6>
                    <div class="d-flex justify-content-center align-items-center">
                        <span class="me-2">No</span>
                        <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="TagAdd" onchange="ta()">
                        <label class="form-check-label" for="TagAdd">Yes</label>
                        </div>
                    </div>
                    </div>
                    <?php } else { ?>
                        <div class="col-12 col-md-4 mb-3">
                    <h6><i class="fad fa-solid fa-tags"></i> Insert Asset Tag Image:</h6>
                    <div class="d-flex justify-content-center align-items-center">
                       <span class="text-warning">Tag not found</span>
                        </div>
                    </div>
                    </div>
                        <?php } ?>
             </div>

        `;
        loadModalContent(dest, "confirmBox", "modal-xl", 1099, "true", "Report Confirmation",
            "cancelConfirm", saveData);
    });

    let isFetching = false;

    function saveData() {
        if (isFetching) return;

        killModal('confirmBox');
        const suv = document.getElementById('surveyor').value;

        document.querySelectorAll('.actionButton').forEach(b => b.disabled = true);

        const pageSet = document.getElementById('pageSet').value;
        const imageSet = document.getElementById('imageSet').value;
        const tagSet = document.getElementById('tagSet').value;

        if (suv === "NULL") {
            showResponse('danger', 'Please select surveyor before proceeding');
            document.querySelectorAll('.actionButton').forEach(b => b.disabled = false);
            return;
        }

        const formContainer = document.getElementById('formContainer');
        const loadingObject = document.getElementById('loadingObject');
        if (formContainer) {
            formContainer.style.opacity = '0.33';
            formContainer.style.transition = 'opacity 0.5s ease';
        }
        if (loadingObject) {
            loadingObject.style.display = 'block';
        }

        const fd = new FormData(document.getElementById('F<?= $d[2] ?>'));
        fd.append('surveyor', suv);

        isFetching = true;

        fetch(`${ROOT_URL}/includes/master/form_functions.php`, {
                method: 'POST',
                body: fd
            })
            .then(r => r.text())
            .then(result => {
                const sec = result.trim().split('|');
                if (sec[0] === "success") {
                    const postData = {
                        orientation: pageSet,
                        imageMode: imageSet,
                        tagMode: tagSet,
                        clientnumber: '<?= $d[0] ?>',
                        repnumber: sec[1],
                        items: '<?= $d[2] ?>',
                        form: '<?= $_REQUEST['formnumber'] ?>',
                        tenant: TENANT_URL
                    };
                    const genParams = new URLSearchParams(postData);

                    fetch(`${ROOT_URL}/functions/generators/genPDF2.php`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: genParams.toString()
                    }).then(r => r.text()).then(() => {
                        showResponse('success', 'Your data has been saved successfully');
                        //window.location.href = '<?= $_SESSION['returnLanding'] ?>';
                    });
                }
            })
            .catch(err => {
                console.error(err);
                document.querySelectorAll('.actionButton').forEach(b => b.disabled = false);
            })
            .finally(() => {
                isFetching = false;
            });
    }

    // Save for later (kept as-is with jQuery usage in your baseline)
    $("#btn_later").click(function(event) {
        event.preventDefault();
        $('#FUNCTION').val('save_for_later')
        if ($('#surveyor').val() === "NULL") {
            showResponse('danger', 'Please select surveyor before proceeding')
        } else {
            $('#formContainer').fadeTo("slow", 0.33);
            $('#loadingObject').css('display', 'block')
            $.ajax({
                url: ROOT_URL + '/includes/master/form_functions.php',
                type: 'POST',
                data: $('#F<?= $d[2] ?>').serialize(),
                success: function(result) {
                    if ($.trim(result) == "success") {
                        showResponse('success', 'Your data has been saved successfully')
                       // document.location.href = '<?= $_SESSION['returnLanding'] ?>'
                    }
                }
            });
        }
    });

    // Footer controls
    const footerControls = document.getElementById('footerControls');
    footerControls.innerHTML =
        '<button class="actionButton btn btn-secondary" onclick="triggerAction(\'btn_save\')" ' +
        'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Create report">CREATE</button> ' +
        '<button class="btn btn-warning" onclick="triggerAction(\'btn_later\')" ' +
        'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save draft">SAVE FOR LATER</button>';
});
</script>