<style>
.surveyor-diary-toolbar {
    gap: .5rem;
}
.surveyor-review-list {
    max-height: 240px;
    overflow: auto;
}
.surveyor-review-note {
    color: #596674;
    max-width: 520px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.surveyor-review-actions {
    align-items: center;
    display: flex;
    flex-wrap: nowrap;
    gap: .35rem;
}
.surveyor-review-actions .btn {
    align-items: center;
    display: inline-flex;
    height: 30px;
    justify-content: center;
    margin: 0 !important;
    padding: 0 .55rem;
    white-space: nowrap;
}
.review-contact-grid {
    display: grid;
    gap: .35rem .75rem;
    grid-template-columns: 120px minmax(0, 1fr);
}
.review-contact-grid dt {
    color: #66717d;
    font-weight: 700;
    margin: 0;
}
.review-contact-grid dd {
    margin: 0;
    min-width: 0;
    overflow-wrap: anywhere;
}
.surveyor-list-subtext {
    color: #6b7580;
    display: block;
    font-size: .8rem;
}
</style>

<div class="card mb-4" id="surveyorReviewCard" style="display:none">
    <div class="card-header d-flex flex-wrap align-items-center justify-content-between surveyor-diary-toolbar">
        <h5 class="mb-0">Report Review Notes <span id="surveyorReviewCount" class="badge bg-warning text-dark ms-1">0</span></h5>
        <button class="btn btn-sm btn-outline-light" type="button" onclick="loadSurveyorReviewNotes()">
            <i class="fad fa-refresh"></i> Refresh
        </button>
    </div>
    <div class="card-body p-3">
        <div class="surveyor-review-list table-responsive">
            <table class="table table-hover table-sm align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th>Client / Report</th>
                        <th>Item</th>
                        <th>Note</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody id="surveyorReviewTableBody"></tbody>
            </table>
        </div>
    </div>
</div>

<script>
var surveyorReviewNotes = [];

function loadSurveyorReviewNotes() {
    fetch(ROOT_URL + '/includes/reports_outstanding/report_review_actions.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=list_surveyor&tenant=${encodeURIComponent(TENANT_URL)}`
    })
    .then(response => response.json())
    .then(data => {
        if (!data || data.ok !== true) {
            renderSurveyorReviewNotes([]);
            return;
        }
        surveyorReviewNotes = data.notes || [];
        renderSurveyorReviewNotes(surveyorReviewNotes);
    })
    .catch(() => renderSurveyorReviewNotes([]));
}

function renderSurveyorReviewNotes(notes) {
    const card = document.getElementById('surveyorReviewCard');
    const body = document.getElementById('surveyorReviewTableBody');
    const count = document.getElementById('surveyorReviewCount');
    if (!card || !body || !count) return;

    count.textContent = String(notes.length);
    card.style.display = notes.length ? '' : 'none';
    body.innerHTML = '';
    notes.forEach(note => {
        const location = [note.locname, note.subloc].filter(Boolean).join(' ');
        const itemText = [
            note.item_name || '',
            note.plantnumber ? 'Plant ' + note.plantnumber : '',
            note.serialnumber ? 'Serial ' + note.serialnumber : ''
        ].filter(Boolean).join(' / ');
        body.innerHTML += `
            <tr>
                <td>
                    ${escapeSurveyorReviewHtml(note.clientname || '')}
                    <span class="surveyor-list-subtext">Report ${escapeSurveyorReviewHtml(note.repnumber || '')}${note.insdate ? ' / ' + surveyorReviewDateValue(note.insdate).split('-').reverse().join('-') : ''}</span>
                </td>
                <td>
                    ${escapeSurveyorReviewHtml(itemText || 'Item ' + note.itemnumber)}
                    ${location ? `<span class="surveyor-list-subtext">${escapeSurveyorReviewHtml(location)}</span>` : ''}
                </td>
                <td><div class="surveyor-review-note">${escapeSurveyorReviewHtml(note.admin_note || '')}</div></td>
                <td><span class="badge ${note.status === 'responded' ? 'bg-info text-white' : 'bg-warning text-dark'}">${note.status === 'responded' ? 'Responded' : 'Pending'}</span></td>
                <td class="text-end">
                    <div class="surveyor-review-actions justify-content-end">
                        <button class="btn btn-secondary btn-sm" type="button" onclick="openSurveyorReviewNote(${Number(note.repitem)})"><i class="fad fa-eye"></i> View</button>
                        <button class="btn btn-success btn-sm" type="button" onclick="completeSurveyorReviewNote(${Number(note.repitem)})"><i class="fad fa-check"></i> Complete</button>
                    </div>
                </td>
            </tr>`;
    });
}

function openSurveyorReviewNote(repitem) {
    const note = surveyorReviewNotes.find(row => Number(row.repitem) === Number(repitem));
    if (!note) return;
    const location = [note.locname, note.subloc].filter(Boolean).join(' ');
    const clientUrl = `index.php?t=includes/master&p=client.php&clientnumber=${encodeURIComponent(note.clientnumber || '')}&view=asset`;
    const reportData = [note.clientnumber || '', note.locnumber || '', note.itemnumber || '']
        .map(value => encodeURIComponent(value))
        .join('|');
    const formnumber = note.formnumber || note.reptype || '';
    const reportUrl = `index.php?t=includes/master&p=formgen.php&mode=reload&formnumber=${encodeURIComponent(formnumber)}&repnumber=${encodeURIComponent(note.repnumber || '')}&data=${reportData}&path=outstanding&savemode=edit`;
    const html = `
        <dl class="review-contact-grid mb-3">
            <dt>Client</dt><dd><a href="${clientUrl}">${escapeSurveyorReviewHtml(note.clientname || '')}</a></dd>
            <dt>Report</dt><dd><a href="${reportUrl}">${escapeSurveyorReviewHtml(note.repnumber || '')}</a></dd>
            <dt>Inspection</dt><dd>${note.insdate ? surveyorReviewDateValue(note.insdate).split('-').reverse().join('-') : ''}</dd>
            <dt>Item</dt><dd>${escapeSurveyorReviewHtml(note.item_name || '')}</dd>
            <dt>Location</dt><dd>${escapeSurveyorReviewHtml(location || '')}</dd>
            <dt>Plant</dt><dd>${escapeSurveyorReviewHtml(note.plantnumber || '')}</dd>
            <dt>Serial</dt><dd>${escapeSurveyorReviewHtml(note.serialnumber || '')}</dd>
        </dl>
        <div class="alert alert-light border"><strong>Admin note</strong><br>${escapeSurveyorReviewHtml(note.admin_note || '').replace(/\n/g, '<br>')}</div>
        <div class="mb-3">
            <label for="surveyorReviewResponse" class="form-label">Response</label>
            <textarea id="surveyorReviewResponse" class="form-control" rows="4">${escapeSurveyorReviewHtml(note.surveyor_response || '')}</textarea>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <button type="button" class="btn btn-info" onclick="respondSurveyorReviewNote(${Number(repitem)})"><i class="fad fa-reply me-1"></i>Respond</button>
            <button type="button" class="btn btn-success" onclick="completeSurveyorReviewNote(${Number(repitem)})"><i class="fad fa-check me-1"></i>Mark Complete</button>
        </div>`;
    loadModalContent(html, 'surveyorReviewNoteBox', 'modal-lg', 1060, 'true', 'Report Review Note', 'close');
}

function surveyorReviewAction(action, repitem, extra) {
    const params = new URLSearchParams(Object.assign({
        action: action,
        repitem: String(repitem),
        tenant: TENANT_URL
    }, extra || {}));
    return fetch(ROOT_URL + '/includes/reports_outstanding/report_review_actions.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: params
    }).then(response => response.json());
}

function respondSurveyorReviewNote(repitem) {
    const response = (document.getElementById('surveyorReviewResponse')?.value || '').trim();
    if (!response) {
        showResponse('warning', 'Please add a response before sending.');
        return;
    }
    surveyorReviewAction('respond', repitem, {response: response}).then(data => {
        if (!data || data.ok !== true) {
            showResponse('danger', data && data.message ? data.message : 'Unable to save response.');
            return;
        }
        showResponse('success', 'Response sent.');
        killModal('surveyorReviewNoteBox');
        loadSurveyorReviewNotes();
    }).catch(() => showResponse('danger', 'Unable to save response.'));
}

function completeSurveyorReviewNote(repitem) {
    surveyorReviewAction('complete', repitem).then(data => {
        if (!data || data.ok !== true) {
            showResponse('danger', data && data.message ? data.message : 'Unable to complete action.');
            return;
        }
        showResponse('success', 'Action marked complete.');
        killModal('surveyorReviewNoteBox');
        loadSurveyorReviewNotes();
    }).catch(() => showResponse('danger', 'Unable to complete action.'));
}

function surveyorReviewDateValue(timestamp) {
    if (!timestamp) return '';
    const date = new Date(Number(timestamp) * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function escapeSurveyorReviewHtml(value) {
    return String(value || '').replace(/[&<>"']/g, function(chr) {
        return ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'}[chr]);
    });
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        loadSurveyorReviewNotes();
        setInterval(loadSurveyorReviewNotes, 30000);
    });
} else {
    loadSurveyorReviewNotes();
    setInterval(loadSurveyorReviewNotes, 30000);
}
</script>
