<div class="card mb-4">
    <div class="card-header">
        <h5>Surveyor Assignment Management</h5>
    </div>
    <div class="card-body">
        <!-- Toggle Buttons -->
        <div class="d-flex justify-content-end mb-4">
            <button class="btn btn-secondary me-2" id="viewAssignedButton" onclick="toggleView('assigned')">View Assigned Jobs</button>
            <button class="btn btn-primary" id="assignFormButton" onclick="toggleView('assignForm')">Assign Surveyor</button>
        </div>

        <!-- Assigned Jobs List (Default View) -->
        <div id="assignedJobsSection" style="display: block;">
            <h5>Assigned Jobs</h5>
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Job Number</th>
                        <th>Client Name</th>
                        <th>Surveyor</th>
                        <th>Expected Inspections</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="assignedJobsTable">
                    <!-- Jobs will be loaded here via JavaScript -->
                </tbody>
            </table>
        </div>

        <!-- Surveyor Assignment Form -->
        <div id="assignFormSection" style="display: none;">
            <!-- Client Selection -->
            <div class="mb-3">
                <label for="clientSelect" class="form-label">Select Client</label>
                <select id="clientSelect" class="form-select">
                    <option value="" disabled selected>Select Client</option>
                    <!-- Clients will be loaded here via JavaScript -->
                </select>
            </div>

            <!-- Surveyor Selection -->
            <div class="mb-3">
                <label for="surveyorSelect" class="form-label">Select Surveyor</label>
                <select id="surveyorSelect" class="form-select">
                    <option value="" disabled selected>Select Surveyor</option>
                    <!-- Surveyors will be loaded here via JavaScript -->
                </select>
            </div>

            <!-- Appointment Date -->
            <div class="mb-3">
                <label for="appointmentDate" class="form-label">Appointment Date</label>
                <input type="date" id="appointmentDate" class="form-control">
            </div>

            <!-- Assign Button -->
            <button class="btn btn-primary" onclick="assignSurveyor()">Assign Surveyor</button>
        </div>
    </div>
</div>

<!-- Admin's Message Modal -->
<div class="modal fade" id="adminMessageModal" tabindex="-1" aria-labelledby="adminMessageModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="adminMessageModalLabel">Send Message to Surveyor</h5>
            </div>
            <div class="modal-body">
                <form id="adminMessageForm">
                    <!-- Hidden input for assignment_id -->
                    <input type="hidden" id="adminAssignmentId" name="assignment_id">

                    <!-- Hidden input for recipient_id (surveyor id) -->
                    <input type="hidden" id="recipient_id" name="recipient_id"> <!-- Make sure this is filled -->

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

                    <!-- Urgency Selection -->
                    <div class="mb-3">
                        <label for="adminMessageStatus" class="form-label">Priority</label>
                        <select id="adminMessageStatus" 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 to open the message modal for a specific assignment and surveyor
function openAdminMessageModal(assignmentId, recipientId) {
    document.getElementById('adminAssignmentId').value = assignmentId;
    document.getElementById('recipient_id').value = recipientId; // Set recipient (surveyor) ID
    new mdb.Modal(document.getElementById('adminMessageModal')).show();
}

// When the "Send Message" button is clicked in the modal
document.getElementById('adminMessageForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);

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

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

// Load clients and surveyors on page load
window.onload = function() {
    loadClientData(); // Load clients on page load
    loadAssignedJobs(); // Load assigned jobs on page load
};

// Toggle between Assigned Jobs and Assign Form
function toggleView(view) {
    const assignedJobsSection = document.getElementById('assignedJobsSection');
    const assignFormSection = document.getElementById('assignFormSection');
    if (view === 'assignForm') {
        assignedJobsSection.style.display = 'none';
        assignFormSection.style.display = 'block';
    } else {
        assignedJobsSection.style.display = 'block';
        assignFormSection.style.display = 'none';
    }
}

// Load Clients and Surveyors
function loadClientData() {
    fetch(ROOT_URL + '/includes/admin/admin_get_clients.php?tenant=' + TENANT_URL)
        .then(response => response.json())
        .then(data => {
            const clientSelect = document.getElementById('clientSelect');
            clientSelect.innerHTML = '<option value="" disabled selected>Select Client</option>'; // Add placeholder
            data.clients.forEach(client => {
                clientSelect.innerHTML += `<option value="${client.clientnumber}">${client.clientname} - ${client.expected_inspections} Expected Inspections</option>`;
            });
        });

    fetch(ROOT_URL + '/includes/admin/admin_get_surveyors.php?tenant=' + TENANT_URL)
        .then(response => response.json())
        .then(data => {
            const surveyorSelect = document.getElementById('surveyorSelect');
            surveyorSelect.innerHTML = '<option value="" disabled selected>Select Surveyor</option>'; // Add placeholder
            data.surveyors.forEach(surveyor => {
                surveyorSelect.innerHTML += `<option value="${surveyor.id}">${surveyor.forename} ${surveyor.surname}</option>`;
            });
        });
}





// Assign Surveyor
function assignSurveyor() {
    const client_id = document.getElementById('clientSelect').value;
    const surveyor_id = document.getElementById('surveyorSelect').value;
    const appointment_date = new Date(document.getElementById('appointmentDate').value).getTime() / 1000;

    const clientName = document.querySelector('#clientSelect option:checked').textContent.split('-')[0].trim(); // Get client name from the dropdown
    const surveyorName = document.querySelector('#surveyorSelect option:checked').textContent; // Get surveyor name from the dropdown

    if (!client_id || !surveyor_id || !appointment_date) {
        alert('Please fill in all fields.');
        return;
    }

    // Assign the surveyor
    fetch(ROOT_URL + '/includes/admin/admin_assign_surveyor.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `client_id=${client_id}&surveyor_id=${surveyor_id}&appointment_date=${appointment_date}&tenant=${TENANT_URL}`
        })
        .then(response => response.text())
        .then(data => {
            //debug(data)
            if (data === 'success') {
                showResponse('success', `Surveyor ${surveyorName} successfully assigned to ${clientName}.`);

                // Send a notification to the assigned surveyor
                sendAssignmentNotification(surveyor_id, clientName);

                loadAssignedJobs(); // Reload the assigned jobs list after assignment
                toggleView('assigned');
            } else {
                showResponse('danger', 'Error assigning surveyor.');
            }
        });
}



// Function to send notification
function sendAssignmentNotification(surveyor_id, clientName) {
    const message = `You have been assigned to ${clientName}.`;

    // Send notification to the surveyor
    fetch(ROOT_URL + '/includes/admin/admin_send_assignment_notification.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `surveyor_id=${surveyor_id}&message=${encodeURIComponent(message)}&tenant=${TENANT_URL}`
        })
        .then(response => response.text())
        .then(data => {
            if (data !== 'success') {
                console.error('Error sending assignment notification to surveyor.');
            }
        });
}




// Load Assigned Jobs
function loadAssignedJobs() {
    fetch(ROOT_URL + '/includes/admin/admin_get_assigned_jobs.php?tenant=' + TENANT_URL)
        .then(response => response.json())
        .then(data => {
            const assignedJobsTable = document.getElementById('assignedJobsTable');
            assignedJobsTable.innerHTML = ''; // Clear previous jobs

            data.jobs.forEach(job => {
                let badgeClass = '';
                switch (job.status) {
                    case 'Not Started':
                        badgeClass = 'badge-danger';
                        break;
                    case 'In Progress':
                        badgeClass = 'badge-warning';
                        break;
                    case 'Completed':
                        badgeClass = 'badge-success';
                        break;
                }

                // Add row to table with "Send Message" and "Remove" buttons
                assignedJobsTable.innerHTML += `
                    <tr>
                        <td>${job.id}</td>
                        <td>${job.clientname}</td>
                        <td>${job.surveyor}</td>
                        <td>
                            Overdue: ${job.overdue}, Today: ${job.due_today}, 
                            This Week: ${job.due_this_week}, This Month: ${job.due_this_month}
                        </td>
                        <td><span class="badge ${badgeClass}">${job.status}</span></td>
                        <td>
                            <button class="btn btn-info btn-sm" onclick="openAdminMessageModal(${job.id}, '${job.surveyor_id}')">Send Message</button>
                            <button class="btn btn-danger btn-sm" onclick="removeAssignment(${job.id}, '${job.surveyor_id}', '${job.status}', '${job.clientname}')">Remove</button>

                        </td>
                    </tr>
                `;
            });
        });
}




function removeAssignment(assignmentId, surveyorId, status, clientName) {
    if (confirm(`Are you sure you want to remove the assignment for ${clientName}?`)) {
        fetch(ROOT_URL + '/includes/admin/admin_remove_assignment.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `assignment_id=${assignmentId}&surveyor_id=${surveyorId}&status=${status}&client_name=${encodeURIComponent(clientName)}&tenant=${TENANT_URL}`
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    showResponse('success', `Assignment for ${clientName} has been successfully removed.`);
                    loadAssignedJobs(); // Reload the list after removing the job
                } else {
                    showResponse('danger', 'Error removing assignment.');
                }
            });
    }
}
</script>