<!--
    This HTML and JavaScript snippet is designed to be embedded directly into your
    existing PHP framework's page. It does not include a full <html>, <head>, or <body>
    wrapper.

    Assumptions:
    - MDBootstrap 5 CSS and JavaScript are already loaded by your framework (UMD version).
    - Font Awesome 6 Pro CSS (specifically fad faand fad classes) is already loaded.
-->

<div id="dashboard-container" class="container-fluid py-4">
    <h3 class="mb-4">System Totals</h3>

    <div class="row mb-4 g-3 align-items-end">
        <div class="col-md-6 offset-md-3">
            <label class="form-label select-label" for="clientSelect">Select Client</label>
            <select class="form-select" id="clientSelect" data-mdb-filter="true">
                <option value="all">All Clients (Global)</option>
            </select>

        </div>
        <div class="col-md-3 hidden">
            <button id="applyFiltersBtn" class="btn btn-primary ">
                <i class="fad fafa-filter me-2"></i>Apply Client Filter
            </button>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-md-4 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-primary"><i class="fad fafa-users me-2"></i>Active Clients</h5>
                    <p class="card-text fs-2 fw-bold" id="totalActiveClients">0</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-secondary"><i class="fad fafa-archive me-2"></i>Archived Clients</h5>
                    <p class="card-text fs-2 fw-bold" id="totalArchivedClients">0</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-success"><i class="fad fafa-boxes me-2"></i>Total Assets</h5>
                    <p class="card-text fs-2 fw-bold" id="totalAssets">0</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-warning"><i class="fad fafa-scroll me-2"></i>Written Schemes</h5>
                    <p class="card-text fs-2 fw-bold" id="totalWrittenSchemes">0</p>
                </div>
            </div>
        </div>

        <div class="col-12 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-dark"><i class="fad fafa-calendar-alt me-2"></i>Report Date Range</h5>
                    <div class="row g-3 mt-2 align-items-end">
                        <div class="col-md-4">
                            <div class="date-picker" data-date-type="open" data-mdb-toggle-button="false" data-mdb-format="dd-mm-yyyy">
                                <input type="text" class="form-control" data-mdb-confirmDateOnSelect data-mdb-format="dd-mm-yyyy" data-mdb-toggle="datepicker" name="reportStartDate" id="reportStartDate" placeholder="Start Date" value="" />

                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="date-picker" data-date-type="open" data-mdb-toggle-button="false" data-mdb-format="dd-mm-yyyy">
                                <input type="text" class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" name="reportEndDate" id="reportEndDate" placeholder="End Date" value="" />

                            </div>
                        </div>
                        <div class="col-md-4">
                            <button id="applyReportDateFilterBtn" class="btn btn-secondary">
                                <i class="fad fafa-calendar-check me-2"></i>Apply Report Date Filter
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-info"><i class="fad fafa-file-alt me-2"></i>Reports Created</h5>
                    <p class="card-text fs-2 fw-bold" id="totalReportsCreated">0</p>
                </div>
            </div>
        </div>

        <div class="col-12 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-dark"><i class="fad fafa-chart-pie me-2"></i>Reports by Result</h5>
                    <div class="row g-3 mt-2">
                        <div class="col-md-2">
                            <div class="text-center">
                                <p class="mb-0 text-success fw-bold">PASS</p>
                                <p class="fs-4" id="reportsPass">0</p>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="text-center">
                                <p class="mb-0 text-warning fw-bold">WARNING</p>
                                <p class="fs-4" id="reportsWarning">0</p>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="text-center">
                                <p class="mb-0 text-danger fw-bold">URGENT</p>
                                <p class="fs-4" id="reportsUrgent">0</p>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="text-center">
                                <p class="mb-0 text-info fw-bold">OBS</p>
                                <p class="fs-4" id="reportsObs">0</p>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="text-center">
                                <p class="mb-0 text-muted fw-bold">PNA</p>
                                <p class="fs-4" id="reportsPna">0</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 mb-3">
            <div class="card shadow-0 border rounded-3">
                <div class="card-body">
                    <h5 class="card-title text-dark"><i class="fad fafa-cogs me-2"></i>Assets by Type</h5>
                    <div id="assetTypesContainer" class="row g-3 mt-2">
                        <div class="col-12 text-center text-muted">
                            <i class="fad fafa-spinner fa-spin me-2"></i>Loading asset types...
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Ensure all external scripts (like MDBootstrap) are fully loaded before initializing components.
window.onload = function() {
    // Check if MDBootstrap's global 'mdb' object is available
    if (typeof mdb === 'undefined') {
        console.error("MDBootstrap JavaScript library (mdb) is not defined. Please ensure it is loaded before this script.");
        document.getElementById('dashboard-container').innerHTML = `
                <div class="alert alert-danger" role="alert">
                    Error: MDBootstrap library not loaded. Dashboard functionality is limited.
                </div>
            `;
        return;
    }

    // Get references to input elements directly, as MDBootstrap UMD auto-initializes datepickers.
    const reportStartDateInput = document.getElementById('reportStartDate');
    const reportEndDateInput = document.getElementById('reportEndDate');

    // Get references to other interactive elements
    const clientSelect = document.getElementById('clientSelect');
    const applyFiltersBtn = document.getElementById('applyFiltersBtn'); // For client filter only
    const applyReportDateFilterBtn = document.getElementById('applyReportDateFilterBtn'); // For report date filter
    const assetTypesContainer = document.getElementById('assetTypesContainer');

    async function fetchTotals() {
        const clientId = clientSelect.value;
        const reportStartDate = reportStartDateInput.value;
        const reportEndDate = reportEndDateInput.value;

        let params = new URLSearchParams();

        // Always append client_id if selected
        if (clientId && clientId !== 'all') {
            params.append('client_id', clientId);
        }

        // Always append report dates
        if (reportStartDate) params.append('report_start_date', reportStartDate);
        if (reportEndDate) params.append('report_end_date', reportEndDate);

        // Assuming TENANT_URL and ROOT_URL are globally defined in your framework
        if (typeof TENANT_URL !== 'undefined') params.append('tenant', TENANT_URL);

        // Show loading state in the UI while data is being fetched
        document.querySelectorAll('.card-text.fs-2.fw-bold, .fs-4').forEach(el => el.textContent = '...');
        assetTypesContainer.innerHTML = `
                <div class="col-12 text-center text-muted">
                    <i class="fad fafa-spinner fa-spin me-2"></i>Loading asset types...
                </div>
            `;

        try {
            const response = await fetch(ROOT_URL + '/functions/get_system_totals.php?' + params.toString());
            const data = await response.json();

            if (data.success) {
                updateUI(data.data);
            } else {
                console.error('Error fetching data from PHP:', data.message);
                resetUI('Error: ' + data.message);
            }
        } catch (error) {
            console.error('Network or parsing error during fetch:', error);
            resetUI('Network Error. Please try again.');
        }
    }


    function updateUI(data) {
        document.getElementById('totalActiveClients').textContent = data.totalActiveClients ?? 0;
        document.getElementById('totalArchivedClients').textContent = data.totalArchivedClients ?? 0;
        document.getElementById('totalAssets').textContent = data.totalAssets ?? 0;
        document.getElementById('totalReportsCreated').textContent = data.totalReportsCreated ?? 0;
        document.getElementById('totalWrittenSchemes').textContent = data.totalWrittenSchemes ?? 0;

        document.getElementById('reportsPass').textContent = data.reportsByResult.PASS ?? 0;
        document.getElementById('reportsWarning').textContent = data.reportsByResult.WARNING ?? 0;
        document.getElementById('reportsUrgent').textContent = data.reportsByResult.URGENT ?? 0;
        document.getElementById('reportsObs').textContent = data.reportsByResult.OBS ?? 0;
        document.getElementById('reportsPna').textContent = data.reportsByResult.PNA ?? 0;

        assetTypesContainer.innerHTML = '';
        if (data.assetTypes && Object.keys(data.assetTypes).length > 0) {
            for (const type in data.assetTypes) {
                const col = document.createElement('div');
                col.className = 'col-md-3';
                col.innerHTML = `
                        <div class="text-center">
                            <p class="mb-0 text-dark fw-bold">${type}</p>
                            <p class="fs-4">${data.assetTypes[type]}</p>
                        </div>
                    `;
                assetTypesContainer.appendChild(col);
            }
        } else {
            assetTypesContainer.innerHTML = `
                    <div class="col-12 text-center text-muted">
                        No asset types found for the selected criteria.
                    </div>
                `;
        }

        // Populate client select dropdown only on initial load or if empty
        if (clientSelect.options.length === 1 && data.activeClientsList) {
            data.activeClientsList.forEach(client => {
                const option = document.createElement('option');
                option.value = client.id;
                option.textContent = client.name;
                clientSelect.appendChild(option);
            });
            // Update the MDBootstrap Select UI after adding new options

        }
    }


    function resetUI(message = 'No data available.') {
        document.getElementById('totalActiveClients').textContent = 0;
        document.getElementById('totalArchivedClients').textContent = 0;
        document.getElementById('totalAssets').textContent = 0;
        document.getElementById('totalReportsCreated').textContent = 0;
        document.getElementById('totalWrittenSchemes').textContent = 0;

        document.getElementById('reportsPass').textContent = 0;
        document.getElementById('reportsWarning').textContent = 0;
        document.getElementById('reportsUrgent').textContent = 0;
        document.getElementById('reportsObs').textContent = 0;
        document.getElementById('reportsPna').textContent = 0;

        assetTypesContainer.innerHTML = `
                <div class="col-12 text-center text-muted">
                    ${message}
                </div>
            `;
    }


    applyFiltersBtn.addEventListener('click', fetchTotals);
    clientSelect.addEventListener('change', fetchTotals);
    applyReportDateFilterBtn.addEventListener('click', fetchTotals);

    // --- Initial Load ---
    fetchTotals();
};

document.getElementById('navBox').innerHTML =
    ' <li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">1000ft View</li>'
</script>