<div class="card mb-4">
    <div class="card-header">
        <h5>Surveyor Assignment Management</h5>
    </div>
    <div class="card-body">
        <!-- Search Bar for Surveyor Filtering -->
        <!-- Filters row -->
        <div class="row align-items-end gy-2 mb-3">
            <div class="col-12 col-md-6 col-lg-4">
                <div class="input-group">
                    <input type="text" id="surveyorFilter" class="form-control" placeholder="Filter by Surveyor Name"
                        onkeyup="filterJobsBySurveyor()">
                    <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear filters">
                        <i class="fad fa-broom"></i>
                    </button>
                </div>
            </div>
            <div class="col-12 col-md-6 col-lg-8">
                <div class="d-flex flex-wrap justify-content-md-end gap-2">
                    <button class="btn btn-sm btn-outline-danger" onclick="filterJobsByStatus('Not Started')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Show Not Started">Not Started</button>
                    <button class="btn btn-sm btn-outline-warning" onclick="filterJobsByStatus('In Progress')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Show In Progress">In Progress</button>
                    <button class="btn btn-sm btn-outline-success" onclick="filterJobsByStatus('Completed')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Show Completed">Completed</button>
                    <!--<button class="btn btn-sm btn-secondary" id="viewAssignedButton" onclick="toggleView('assigned')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="View assigned jobs">
                        View Assigned Jobs
                    </button>-->
                    <button class="btn btn-info" id="assignFormButton" onclick="toggleView('assignForm')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Open assignment form">
                        Assign Surveyor
                    </button>
                </div>
            </div>
        </div>


        <!-- Assigned Jobs List (Default View) -->
        <div id="assignedJobsSection">
            <h5>Assigned Jobs</h5>
            <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                <table class="table table-striped table-sm">
                    <thead class="table-dark bg-dark" style="position: sticky; top: 0; z-index: 1;">
                        <tr>
                            <th>Job Number</th>
                            <th>Client Name</th>
                            <th>Surveyor</th>
                            <th>Appointment Date</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>
        </div>
        <style>
        /* Basic customization */
        input[type="date"] {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;

            cursor: pointer;

        }

        /* Hiding the default calendar icon */
        input[type="date"]::-webkit-calendar-picker-indicator {
            display: none;
        }

        input[type="date"]::-moz-calendar-picker-indicator {
            display: none;
        }

        /* Add a custom calendar icon */
        .custom-date {
            position: relative;
        }

        .custom-date::before {
            content: "\f073";
            /* Font Awesome icon (calendar) */
            font-family: "Font Awesome 6 Pro";
            position: absolute;
            right: 15px;
            top: 10px;
            font-size: 18px;
            color: #888;
            pointer-events: none;
        }
        </style>
        <!-- Surveyor Assignment Form -->
        <div id="assignFormSection" style="display: none;">
            <div class="row">
                <div class="col-4 mb-3">
                    <label for="clientSelect" class="form-label">Select Client</label>
                    <select id="clientSelect" class="form-select" data-mdb-select-init data-mdb-filter="true">
                        <option value="" disabled selected>Select Client</option>
                    </select>
                </div>
                <div class="col-4  mb-3">
                    <label for="surveyorSelect" class="form-label">Select Surveyor</label>
                    <select id="surveyorSelect" class="form-select" data-mdb-select-init data-mdb-filter="true">
                        <option value="" disabled selected>Select Surveyor</option>
                    </select>
                </div>
                <div class="col-4 mb-3">
                    <div class="col-12 col-md-6 date-picker" data-date-type="open" data-mdb-toggle-button="false"
                        data-mdb-format="dd-mm-yyyy">
                        <label for="appointmentDate" class="form-label">Appointment Date</label>
                        <input type="text" id="appointmentDate" class="form-control" data-mdb-confirmDateOnSelect
                            data-mdb-toggle="datepicker" value="">
                    </div>
                </div>
            </div>
            <button class="btn btn-primary" onclick="assignSurveyor()">Assign Surveyor</button>
        </div>
    </div>
</div>
<script>
// Trigger date picker on input focus
document.getElementById('appointmentDate').addEventListener('click', function() {
    this.showPicker();
});
</script>
<!-- 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">
                <a href="javascript:void(0)" class="sa">Send Message to Surveyor</a>
            </div>
            <div class="modal-body">
                <form id="adminMessageForm">
                    <input type="hidden" id="adminAssignmentId" name="assignment_id">
                    <input type="hidden" id="recipient_id" name="recipient_id">
                    <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>
                    <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>

<!-- Remove Assignment Modal -->
<div class="modal fade" id="removeAssignmentModal" tabindex="-1" aria-labelledby="removeAssignmentModalLabel"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <a href="javascript:void(0)" class="sa">Confirm Assignment Removal</a>
            </div>
            <div class="modal-body">
                <p id="confirmMessage">Are you sure you want to remove this assignment?</p>

                <!-- Pause Permissions Checkbox -->
                <div class="form-check mb-3">
                    <input class="form-check-input" type="checkbox" id="pauseSurveyorAssignmentsToggle"
                        onclick="toggleOtherCheckbox('pause')">
                    <label id="pauseMessage" class="form-check-label" for="pauseSurveyorAssignmentsToggle">

                    </label>
                </div>

                <!-- Remove Permissions Checkbox -->
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="removeSurveyorAssignmentsToggle"
                        onclick="toggleOtherCheckbox('remove')">
                    <label class="form-check-label" for="removeSurveyorAssignmentsToggle">
                        Also remove all surveyor-client assignments from the managed surveyor permissions system?
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Cancel</button>
                <button type="button" id="confirmRemoveButton" class="btn btn-danger">Remove</button>
            </div>
        </div>
    </div>
</div>

<script>
function openAdminMessageModal(assignmentId, recipientId) {
    document.getElementById('adminAssignmentId').value = assignmentId;
    document.getElementById('recipient_id').value = recipientId;
    new mdb.Modal(document.getElementById('adminMessageModal')).show();
}

function toggleOtherCheckbox(action) {
    if (action === 'pause') {
        document.getElementById('removeSurveyorAssignmentsToggle').checked = false;
    } else if (action === 'remove') {
        document.getElementById('pauseSurveyorAssignmentsToggle').checked = false;
    }
}

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.');
            }
        });
});

window.onload = function() {
    loadClientData();
    loadAssignedJobs();
    startAutoRefresh();
};

function startAutoRefresh() {
    setInterval(loadAssignedJobs, 30000);
}


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 = '';
            data.jobs.forEach(job => {
                let badgeClass = '';
                switch (job.status) {
                    case 'Not Started':
                        badgeClass = 'bg-danger';
                        break;
                    case 'In Progress':
                        badgeClass = 'bg-warning';
                        break;
                    case 'Completed':
                        badgeClass = 'bg-success';
                        break;
                }
                let clientName = job.clientname
                clientName = clientName.replace(/&#39;/g, "'").replace(/['’]/g, "");

                const itemsDue = `
                    <span class="text-danger">Overdue: ${job.overdue}</span>,
                    <span class="text-warning">Today: ${job.due_today}</span>,
                    <span class="text-primary">This Week: ${job.due_this_week}</span>,
                    <span class="text-info">This Month: ${job.due_this_month}</span>
                `;
                assignedJobsTable.innerHTML += `
                    <tr>
                        <td>${job.id}</td>
                        <td><a href="index.php?t=includes/master&p=client.php&clientnumber=${job.clientnumber}&view=asset">${job.clientname}</a></td>
                        <td>${job.surveyor}</td>
                        <td>${new Date(job.appointment_date * 1000).toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })}</td>
                        <td>${itemsDue}</td>
                        <td><span class="badge ${badgeClass}">${job.status}</span></td>
                        <td>
                        <a class="btn btn-secondary btn-sm me-2 mb-2" data-mdb-toggle="tooltip" data-mdb-placement="top" data-mdb-trigger="hover" title="Manage Assignments for ${job.surveyor}" href="index.php?t=includes/master&p=surveyor.php&id=${job.surveyor_id}&view=assign"><i class="fad fa-pencil"></i></a>
                            <button class="btn btn-info btn-sm me-2 mb-2" data-mdb-toggle="tooltip" data-mdb-placement="top" data-mdb-trigger="hover" onclick="openAdminMessageModal(${job.id}, '${job.surveyor_id}')" title="Send message to ${job.surveyor}"><i class="fad fa-envelope"></i></button>
                            <button class="btn btn-danger btn-sm mb-2" onclick="openRemoveModal(${job.id}, '${job.surveyor_id}', '${job.clientnumber}', '${clientName}')"><i class="fad fa-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-mdb-toggle="tooltip"]'));
            tooltipTriggerList.forEach(function(tooltipTriggerEl) {
                new mdb.Tooltip(tooltipTriggerEl);
            });
        });
}

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>';
            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>';
            data.surveyors.forEach(surveyor => {
                surveyorSelect.innerHTML +=
                    `<option value="${surveyor.id}">${surveyor.forename} ${surveyor.surname}</option>`;
            });
        });
}

function parseDMY(dateStr) {
    const parts = dateStr.split('-'); // expects dd-mm-yyyy
    if (parts.length !== 3) return NaN;
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1; // JS months 0–11
    const year = parseInt(parts[2], 10);

    const d = new Date(year, month, day);
    return isNaN(d) ? NaN : Math.floor(d.getTime() / 1000);
}


function assignSurveyor() {
    const client_id = document.getElementById('clientSelect').value;
    const surveyor_id = document.getElementById('surveyorSelect').value;
    const rawDate = document.getElementById('appointmentDate').value.trim();
    const appointment_date = parseDMY(rawDate);


    // Retrieve the selected client's name from the dropdown
    const clientName = document.getElementById('clientSelect').options[document.getElementById('clientSelect')
        .selectedIndex].text.split(' - ')[0];

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


    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 => {
            // alert(data) // Debugging: shows server response

            if (data.includes('success')) {
                // Handle success messages
                if (data.includes('has access permissions')) {
                    showResponse('success',
                        `Assignment successful, surveyor already has access permissions set for  ${clientName}.`
                    );
                } else if (data.includes('permissions have been reinstated')) {
                    showResponse('success',
                        `Assignment successful, permissions have been reinstated for ${clientName}`);
                } else if (data.includes('to access the full schedule')) {
                    showResponse('success',
                        `Assignment successful, permissions given for the surveyor to access ${clientName}'s full schedule.`
                    );
                } else {
                    showResponse('success', 'Surveyor assigned successfully.');
                }
                sendAssignmentNotification(surveyor_id, clientName);
                loadAssignedJobs();
                toggleView('assigned');
            } else if (data.includes('already exists')) {
                // Handle the case where the assignment already exists
                showResponse('warning', 'Surveyor is already assigned to this client on the given date.');
            } else {
                // Handle error or other unexpected messages
                showResponse('danger', 'Error assigning surveyor.');
            }
        });
}

function sendAssignmentNotification(surveyor_id, clientName) {
    const message = `You have been assigned to ${clientName}.`;
    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}`
    });
}

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';
    }
}

function openRemoveModal(assignmentId, surveyorId, clientId, clientName) {
    // Set the modal message to include the correct client name
    document.getElementById('confirmMessage').textContent =
        `Are you sure you want to remove the assignment for ${clientName}?`;
    document.getElementById('pauseMessage').textContent = `Pause access permissions for ${clientName}?`;
    // Show the modal
    const removeModal = new mdb.Modal(document.getElementById('removeAssignmentModal'));
    removeModal.show();

    // Set up the confirmation button click handler
    document.getElementById('confirmRemoveButton').onclick = function() {
        confirmRemoveAssignment(assignmentId, surveyorId, clientId, clientName); // Pass clientId and clientName
        removeModal.hide();
    };
}

function confirmRemoveAssignment(assignmentId, surveyorId, clientId, clientName) {
    const pauseSurveyorClient = document.getElementById('pauseSurveyorAssignmentsToggle').checked;
    const removeSurveyorClient = document.getElementById('removeSurveyorAssignmentsToggle').checked;

    let body =
        `assignment_id=${assignmentId}&surveyor_id=${surveyorId}&client_id=${clientId}&client_name=${encodeURIComponent(clientName)}&tenant=${TENANT_URL}`;

    // Add the pause or remove parameters only if they are selected
    if (pauseSurveyorClient) {
        body += '&pause_surveyor_client=true';
    }

    if (removeSurveyorClient) {
        body += '&remove_surveyor_client=true';
    }

    fetch(ROOT_URL + '/includes/admin/admin_remove_assignment.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: body
        })
        .then(response => response.text())
        .then(data => {
            if (data === 'success') {
                if (pauseSurveyorClient) {
                    showResponse('success', `Access permissions for ${clientName} have been paused.`);
                } else if (removeSurveyorClient) {
                    showResponse('success', `Assignment for ${clientName} has been successfully removed.`);
                } else {
                    showResponse('success',
                        `Assignment for ${clientName} has been successfully removed from the admin assignments.`
                    );
                }
                loadAssignedJobs(); // Reload the assigned jobs list after the operation
            } else {
                showResponse('danger', 'Error processing the request.');
            }
        });
}



// Function to clear the search input
function clearSearch() {
    document.getElementById('surveyorFilter').value = ''; // Clear the input value
    filterJobsBySurveyor(); // Reset the job list
}

// Function to filter jobs by surveyor name
function filterJobsBySurveyor() {
    const input = document.getElementById('surveyorFilter').value.toLowerCase();
    const table = document.getElementById('assignedJobsTable');
    const rows = table.getElementsByTagName('tr');

    for (let i = 0; i < rows.length; i++) {
        const surveyorCell = rows[i].getElementsByTagName('td')[2]; // Surveyor name is in the 3rd column (index 2)
        if (surveyorCell) {
            const surveyorName = surveyorCell.textContent || surveyorCell.innerText;
            if (surveyorName.toLowerCase().indexOf(input) > -1) {
                rows[i].style.display = ''; // Show row
            } else {
                rows[i].style.display = 'none'; // Hide row
            }
        }
    }
}

function filterJobsByStatus(status) {

    const tableBody = document.getElementById('assignedJobsTable'); // Get the tbody
    const rows = tableBody.getElementsByTagName('tr'); // Get all rows in the tbody

    for (let i = 0; i < rows.length; i++) {
        const statusCell = rows[i].getElementsByTagName('td')[5]; // Status is in the 5th column (index 4)
        if (statusCell) {
            const jobStatus = statusCell.textContent.trim()
                .toLowerCase(); // Trim spaces and make comparison case-insensitive
            if (jobStatus === status.toLowerCase()) {
                rows[i].style.display = ''; // Show row if status matches
            } else {
                rows[i].style.display = 'none'; // Hide row if status does not match
            }
        }
    }
}
</script>