<div class="card mb-4">
    <div class="card-header">
        <h5>Assignments</h5>
    </div>
    <div class="card-body">
        <div id="assignmentResults">
            <!-- Surveyor assignments will be loaded here via JavaScript -->
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Client Name</th>
                        <th>Appointment Date</th>
                        <th>Items Due</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="assignmentTableBody">
                    <!-- Rows will be dynamically inserted here -->
                </tbody>
            </table>
        </div>
    </div>
</div>
<!-- Surveyor's Message Modal -->
<div class="modal fade" id="surveyorMessageModal" tabindex="-1" aria-labelledby="surveyorMessageModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="surveyorMessageModalLabel">Send Message to Admin</h5>
            </div>
            <div class="modal-body">
                <form id="surveyorMessageForm">
                    <input type="hidden" id="surveyorAssignmentId" name="assignment_id">

                    <!-- Message Content -->
                    <div class="mb-3">
                        <label for="surveyorMessageContent" class="form-label">Message</label>
                        <textarea id="surveyorMessageContent" name="message" class="form-control" rows="4" required></textarea>
                    </div>

                    <!-- Urgency Selection -->
                    <div class="mb-3">
                        <label for="surveyorMessageStatus" class="form-label">Priority</label>
                        <select id="surveyorMessageStatus" name="status" class="form-select">
                            <option value="normal">Normal</option>
                            <option value="urgent">Urgent</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary">Send Message</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function openSurveyorMessageModal(assignmentId) {
    document.getElementById('surveyorAssignmentId').value = assignmentId;
    new mdb.Modal(document.getElementById('surveyorMessageModal')).show();
}

document.getElementById('surveyorMessageForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);

    fetch(ROOT_URL + '/includes/surveyor/send_message_surveyor.php?tenant=' + TENANT_URL, {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {

            if (data === 'success') {
                showResponse('success', 'Message sent successfully!');
                document.getElementById('surveyorMessageContent').value = '';
                killModal('surveyorMessageModal')
            } else {
                showResponse('danger', 'Failed to send message.');
            }
        });
});


// Load the assignments and populate the table
function loadAssignments() {
    fetch(ROOT_URL + '/includes/surveyor/admin_get_assignments.php?tenant=' + TENANT_URL)
        .then(response => response.json())
        .then(data => {
            const assignmentTableBody = document.getElementById('assignmentTableBody');
            assignmentTableBody.innerHTML = ''; // Clear previous assignments

            data.assignments.forEach(assignment => {
                let statusBadge = '';
                let actionButtons = '';

                // Display status as badges based on the current assignment status
                if (assignment.status === 'Not Started') {
                    statusBadge = '<span class="badge bg-danger">Not Started</span>';
                    actionButtons = `<button class="btn btn-success btn-sm me-3" onclick="markStarted(${assignment.id})">Notify Started</button>`;
                } else if (assignment.status === 'In Progress') {
                    statusBadge = '<span class="badge bg-warning">In Progress</span>';
                    actionButtons = `<button class="btn btn-danger btn-sm me-3" onclick="markCompleted(${assignment.id})">Notify Complete</button>`;
                } else if (assignment.status === 'Completed') {
                    statusBadge = '<span class="badge bg-success">Completed</span>';
                    actionButtons = '<span class="text-muted">No Actions Available</span>';
                }

                // Display expected items (overdue, today, this week, and this month)
                const itemsDue = `
                    <span class="text-danger">Overdue: ${assignment.overdue}</span>, 
                    <span class="text-warning">Today: ${assignment.due_today}</span>, 
                    <span class="text-primary">This Week: ${assignment.due_this_week}</span>,
                    <span class="text-info">This Month: ${assignment.due_this_month}</span>
                `;

                // Add row to table
                assignmentTableBody.innerHTML += `
                    <tr>
                        <td>${assignment.clientname}</td>
                        <td>${new Date(assignment.appointment_date * 1000).toLocaleDateString('en-GB', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
})}</td>
                        <td>${itemsDue}</td>
                        <td>${statusBadge}</td>
                        <td>
                            ${actionButtons}
                            <button class="btn btn-info btn-sm me-3" onclick="openSurveyorMessageModal(${assignment.id})">Send Message</button>
                            <a class="btn btn-secondary btn-sm" href="index.php?t=includes/master&p=client.php&clientnumber=${assignment.clientnumber}&view=asset">View schedule</a>
                        </td>
                    </tr>
                `;
            });
        });

}


// Mark the assignment as started
function markStarted(assignmentId) {
    fetch(ROOT_URL + '/includes/surveyor/admin_mark_assignments.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `assignment_id=${assignmentId}&action=started&tenant=${TENANT_URL}`
        }).then(response => response.text())
        .then(data => {
            if (data === 'success') {
                showResponse('success', 'Assignment marked as started.');

                // Send notification to admin
                fetch(ROOT_URL + '/includes/surveyor/send_admin_notification.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `assignment_id=${assignmentId}&action=started&tenant=${TENANT_URL}`
                });

                loadAssignments(); // Reload assignments after updating the status
            } else {
                showResponse('danger', 'Error updating assignment.');
            }
        });
}

// Mark the assignment as completed
function markCompleted(assignmentId) {
    fetch(ROOT_URL + '/includes/surveyor/admin_mark_assignments.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `assignment_id=${assignmentId}&action=completed&tenant=${TENANT_URL}`
        }).then(response => response.text())
        .then(data => {
            if (data === 'success') {
                showResponse('success', 'Assignment marked as completed.');

                // Send notification to admin
                fetch(ROOT_URL + '/includes/surveyor/send_admin_notification.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `assignment_id=${assignmentId}&action=completed&tenant=${TENANT_URL}`
                });

                loadAssignments(); // Reload assignments after updating the status
            } else {
                showResponse('danger', 'Error updating assignment.');
            }
        });
}


// Load assignments on page load
loadAssignments();
startAutoRefresh();


function startAutoRefresh() {
    setInterval(loadAssignments, 30000);
}
</script>