<?php 
require(ROOT_URL.'/includes/address/address_functions.php'); ?>

<style>
/* Flexbox and tighter gutter control */
.card-container {
    display: flex;
    flex-wrap: wrap;
    margin-left: -10px;
    margin-right: -10px;
}

.card-item {
    flex: 1 1 25%;
    max-width: 25%;
    padding-left: 10px;
    padding-right: 10px;
    margin-bottom: 20px;
}

/* Responsiveness */
@media (max-width: 1200px) {
    .card-item {
        flex: 1 1 33.33%;
        max-width: 33.33%;
    }
}

@media (max-width: 768px) {
    .card-item {
        flex: 1 1 50%;
        max-width: 50%;
    }
}

@media (max-width: 576px) {
    .card-item {
        flex: 1 1 100%;
        max-width: 100%;
    }
}
</style>

<div class="">
    <!-- Filter Row -->
    <div class="row">
        <div class="col-12">
            <nav>
                <ul class="pagination pg-blue justify-content-center" id="filterRow">
                    <!-- Dynamically filled via PHP -->
                    <li id="R" class="page-item active">
                        <a class="page-link" href="javascript:void(0)" onclick="filterlist('')">ALL</a>
                    </li>
                    <?= listChar() ?>
                    <!-- Alphabetical filter links -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- Search Box -->
    <div class="row">
        <div class="col-12 col-md-6 offset-md-3 form-group">
            <div class="input-group">
                <input id="adSearch" type="text" class="form-control form-control-sm" placeholder="Search by client name: Results appear as you type..">
            </div>
        </div>
    </div>

    <!-- Address List -->
    <div class="row" id="addressList">
        <?= getFilteredListByLetter('') ?>
        <!-- Load all clients initially -->
    </div>

    <!-- Pagination Controls (populated by JavaScript and PHP) -->
    <div id="paginationControls" class="text-center"></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Search input handling
    const adSearch = document.getElementById('adSearch');
    adSearch.addEventListener('input', function() {
        const query = adSearch.value;
        searchClients(query, 1); // Start from page 1 when searching
    });

    // Global function for filterlist, paginated
    window.filterlist = function(letter, page = 1) {
        document.querySelectorAll('.page-item').forEach(el => el.classList.remove('active'));
        filterByLetter(letter, page); // Filter by letter, paginated
        if (letter) {
            document.getElementById('R' + letter).classList.add('active');
        }
    }

    function searchClients(searchTerm, page) {
        fetch(ROOT_URL + '/includes/address/address_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    search: searchTerm,
                    page: page,
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('addressList').innerHTML = data;
            })
            .catch(error => console.error('Error:', error));
    }

    // Function to filter clients by first letter with pagination
    function filterByLetter(letter, page) {
        fetch(ROOT_URL + '/includes/address/address_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    filter: letter,
                    page: page,
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('addressList').innerHTML = data;
            })
            .catch(error => console.error('Error:', error));
    }
});

document.body.addEventListener('click', function(event) { // Event delegation on body
    if (event.target.classList.contains('emailButton')) {
        const target = event.target.dataset.href;
        const string = event.target.dataset.values;
        var dest = encodeURI(target + "?data=" + string + "&tenant=" + TENANT_URL);
        loadModalContent(dest, "mailerBox", "modal-xl", 1060, "true", "Direct Mailer");

    }
});
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">Global Client Addressbook</li>'

</script>