<div class="card">
    <div class="card-header">
        <h5 class="mb-0" id="cardTitle">Today's Jobs</h5>
    </div>
    <div class="card-body">
        <!-- Filter and Sort Buttons -->
        <div class="d-flex justify-content-between mb-4">
            <!-- Date Filters -->
            <div>
                <button class="btn btn-primary" onclick="loadJobs('today')">Today</button>
                <button class="btn btn-secondary" onclick="loadJobs('week')">This Week</button>
                <button class="btn btn-info" onclick="loadJobs('month')">This Month</button>
            </div>
            <!-- Sort Options -->
            <div>
                <button class="btn btn-outline-dark" onclick="setMode('assignment')">Sort by Assignment</button>
                <button class="btn btn-outline-dark" onclick="setMode('client')">Sort by Client</button>
            </div>
        </div>

        <!-- Results Table -->
        <div id="jobResults">
            <div class="text-center">
                <p>Loading...</p>
            </div>
        </div>
    </div>
</div>

<script>
let currentFilter = 'today';
let currentMode = 'assignment'; // Default mode

function loadJobs(filter) {
    currentFilter = filter;
    fetchJobs();
}

function setMode(mode) {
    currentMode = mode;
    fetchJobs();
}

function fetchJobs() {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/jobsheet_functions.php?tenant=' + TENANT_URL, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            document.getElementById('jobResults').innerHTML = xhr.responseText;

            // Update the card title based on the selected filter and mode
            const titles = {
                'today': "Today's assignments",
                'week': "This Week's assignments",
                'month': "This Month's assignments",
                'client_today': "Today's assignments by Client",
                'client_week': "This Week's assignments by Client",
                'client_month': "This Month's assignments by Client",
            };
            const key = (currentMode === 'client' ? 'client_' : '') + currentFilter;
            document.getElementById('cardTitle').innerText = titles[key];
        }
    };

    // Send the surveyor ID, filter type, and mode to the server
    xhr.send('action=getJobs&filter=' + currentFilter + '&mode=' + currentMode);
}

// Load today's jobs in assignment mode by default
fetchJobs();
</script>