<div class="row">

    <div class="col-12"><span><i class="fad fa-bolt-lightning fa-2x"></i></span>
        <span class="float-end">
            <a class="btn btn-secondary btn-sm mb-3" onclick="createDistro()" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" data-mdb-original-title="New Distribution Board"
               data-mdb-tooltip-initialized="true"><i
                   class="fad fa-plus" aria-hidden="true"></i> New Distro</a>
            <a id="newSite" href="index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber']?>&clientname=<?= getClientName($_REQUEST['clientnumber'])?>&view=new&ref=asset"
               class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="New Location"><i class="fad fa-building" aria-hidden="true"></i> New Location</a>

            <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber']?>&view=asset&filter=archive" class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
               data-mdb-placement="bottom"
               title="View Archived Assets"><i class="fad fa-archive" aria-hidden="true"></i> View Archived Items</a>

            <?php if($_SESSION['access']==1 || $_SESSION['access']==2 || $_SESSION['access']==999){?>
            <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber']?>&view=edit" class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
               title="View Client Details"><i class="fad fa-info-circle"></i></a>
            <?php }else{?>
            <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber']?>&view=load" class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
               title="View Client Details"><i class="fad fa-info-circle"></i></a>
            <?php }?></span>
    </div>
</div>
<div class="container-fluid">

    <table id="boardsTable" class="dt-print-table table table-striped table-sm table-bordered table-hover responsive dataTable dtr-inline" style="width:100%">
        <thead>
            <tr>
                <th>Board Name</th>
                <th>Board Type</th>
                <th>Location</th>
                <th>Postcode</th>
                <th>Number of Circuits</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<script>
const clientNumber = <?=$_REQUEST['clientnumber']?>;

document.addEventListener("DOMContentLoaded", () => {
    const table = $('#boardsTable').DataTable({
        ajax: {
            url: `${ROOT_URL}/includes/elec/fetch_client_boards.php`,
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            processData: true,
            data: {
                clientnumber: clientNumber,
                tenant: TENANT_URL
            },
            dataSrc: function(json) {
                if (json.success) {
                    return json.boards;
                } else {
                    console.error(json.message);
                    alert('Failed to load boards.');
                    return [];
                }
            }
        },
        columns: [{
                data: 'board_name'
            }, {
                data: 'board_type'
            },
            {
                data: 'location_name'
            },
            {
                data: 'postcode'
            },
            {
                data: 'circuits_count'
            },
            {
                data: 'board_id',
                render: function(data, type, row) {
                    // Determine if there is an active report.
                    // You must have your fetch_client_boards.php include this property.
                    // For example, if row.active_report_status is 'active', then an active report exists.
                    var reportBtnLabel = '<i class="fad fa-file-alt" aria-hidden="true"></i>';
                    var reportBtnTitle = 'New report'
                    var indicator = "";
                    if (row.active_report_status && row.active_report_status === 'active') {
                        reportBtnLabel = '<i class="fad fa-file-alt" aria-hidden="true"></i>';
                        reportBtnTitle = "Resume Report";
                        // You can use a Font Awesome icon or a Bootstrap badge as an indicator.
                        // Here we use a Bootstrap badge with a warning background.
                        indicator = ' <i class="fad fa-spinner-third text-info fa-spin"></i>';
                    }

                    return `
<div class="float-end">
<button data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Edit Board: ${row.board_name}" class="btn btn-secondary noprint me-2" onclick="editDistro('${row.link_chain}')"><i class="fad fa-pen-to-square"></i></button>
    <button class="btn btn-secondary noprint me-2" onclick="newCircuit('${row.link_chain}')" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="New Circuit"><i class="fa-kit-duotone fa-duotone-solid-plug-circle-plus"></i></button>
    <button class="btn btn-secondary noprint me-2" onclick="viewCircuits('${row.link_chain}')" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View Circuits"><i class="fa-kit-duotone fa-duotone-solid-plug-circle-question"></i></button>
    <button class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="${reportBtnTitle}" onclick="generateSystemReport('${row.link_chain}')">${reportBtnLabel}${indicator}</button>
    <button class="btn btn-secondary noprint me-2" onclick="viewSystemReports('${row.board_id}')" data-mdb-tooltip-init="" data-mdb-trigger="hover" data-mdb-placement="top" aria-label="Completed Report" data-mdb-original-title="Completed Report" data-mdb-tooltip-initialized="true"><i class="fad fa-copy" aria-hidden="true"></i></button>
    <button class="btn btn-secondary noprint" onclick="archiveBoard('${row.link_chain}')" data-mdb-tooltip-init="" data-mdb-trigger="hover" data-mdb-placement="top" aria-label="Archive Board" data-mdb-original-title="Archive Item" data-mdb-tooltip-initialized="true"><i class="fad fa-archive" aria-hidden="true"></i></button>
</div>
`;
                }
            }

        ],
        responsive: true,
        "drawCallback": function(settings) {
            // Re-initialize MDBootstrap tooltips after the table has been redrawn
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-mdb-tooltip-init]'));
            tooltipTriggerList.map(function(tooltipTriggerEl) {
                return mdb.Tooltip.getOrCreateInstance(tooltipTriggerEl);
            });
        }
    });
});

// Action Handlers
function editDistro(chain) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_distro_edit&data=${chain}`;
}

function createDistro(chain) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_distro&action=create_distro&clientnumber=<?=$_REQUEST['clientnumber']?>`;
}

function newCircuit(chain) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_new_circuit&data=${chain}`;
}

function viewCircuits(chain) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_list_circuit&data=${chain}`;
}

function viewDistros(chain) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_distro&action=view_distros&data=${chain}`;
}

function generateSystemReport(boardId) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_new_report&data=${boardId}`;
}

function viewSystemReports(boardId) {
    window.location.href = `index.php?t=includes/master&p=elec.php&view=elec_list_reports&board_id=${boardId}`;
}

function archiveBoard(boardId) {
    if (confirm("Are you sure you want to archive this board?")) {
        fetch(`${ROOT_URL}/includes/elec/archive_board.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    board_id: boardId,
                    clientnumber: clientNumber
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Board archived successfully.');
                    $('#boardsTable').DataTable().ajax.reload();
                } else {
                    alert(`Error archiving board: ${data.message}`);
                }
            })
            .catch(error => {
                console.error('Error archiving board:', error);
                alert('An unexpected error occurred.');
            });
    }
}

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('navBox').innerHTML =
        '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Clients</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
        '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=elec.php&clientnumber=<?= $_REQUEST['clientnumber']?>"><?= getClientName($_REQUEST['clientnumber'])?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>' +
        '<li class="breadcrumb-item active">Distribution Boards</li>'


});
</script>