<?php
// Include configuration for database access
if (file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../../'.$_REQUEST['tenant'].'/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Pagination settings
$resultsPerPage = 16;

// Function to generate clickable letter filters (A, B, C, etc.)
function listChar() {
    $ret = '';
    $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT UPPER(SUBSTRING(clientname, 1, 1)) AS firstLetter 
                                       FROM `clientdetails` 
                                       WHERE `statuslive` = '1' 
                                       ORDER BY firstLetter ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();

    while ($row = mysqli_fetch_array($result)) {
        $ret .= '<li id="R'.$row['firstLetter'].'" class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="filterlist(\''.$row['firstLetter'].'\')">'.$row['firstLetter'].'</a>
                 </li>';
    }
    return $ret;
}

// Function to handle filtering by first letter and pagination
function getFilteredListByLetter($filter = '', $page = 1) {
    global $resultsPerPage;
    $offset = ($page - 1) * $resultsPerPage;
    $filterValue = $filter . '%'; 

    if ($filter === '') {
        // No filter, show all active clients with pagination
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `statuslive` = '1' LIMIT ? OFFSET ?")
                                          or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $resultsPerPage, $offset);
    } else {
        // Filter by clientname starting with selected letter or matching "The <letter>"
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails`
                                          WHERE (`clientname` LIKE ? 
                                          OR (`clientname` LIKE 'The %' AND SUBSTRING(clientname, 5, 1) = ?)) 
                                          AND `statuslive` = '1' LIMIT ? OFFSET ?")
                                          or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ssii', $filterValue, $filter, $resultsPerPage, $offset);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();

    // Pagination above the results
    $ret = getPaginationLinks($filter, $page);

    // Card container with client details
    $ret .= '<div class="card-container">';
    while ($row = mysqli_fetch_array($result)) {
$email_values = [
    0 => $row['clientnumber'], //client
    1 => $row['clientname'], //type
    2 => $row['email'], //recipient
    3 => '', //subject
    4 => '', //message
    5 => '', //attachment
    6 => '' //source
];
$email64_values = base64_encode(json_encode($email_values));
        // Check if the client logo exists
        $logoCheck = '../../..'.TENANT_URL.'/images/client/'.$row['clientnumber'].'.jpg';
        $logoPath = 'images/client/'.$row['clientnumber'].'.jpg';
        $logoExists = file_exists($logoCheck) ? $logoPath : 'images/profile/noimage.png';

        $ret .= '
        <div class="card-item">
            <div id="'.$row['clientnumber'].'A" class="card h-100">
                <div class="card-body">
                    <div class="text-center mb-3">
                        <img src="'.$logoExists.'" alt="Client Logo" class="rounded-circle img-fluid" style="max-width: 100px;">
                    </div>
                    <div class="lead"><i>'.$row['clientname'].'</i></div>
                    <p>'.$row['address1'].'<br>';
                    if ($row['address2'] != "") { $ret .= $row['address2'].'<br>'; }
                    if ($row['town'] != "") { $ret .= $row['town'].'<br>'; }
                    if ($row['counry'] != "") { $ret .= $row['counry'].'<br>'; }
                    if ($row['postcode'] != "") { $ret .= $row['postcode'].'<br>'; }
                    if (!filter_var($row['email'], FILTER_VALIDATE_EMAIL) === false) {
                        $ret .= '<i class="fa fa-envelope"></i> Email: <a href="javascript:void(0)" class="emailButton"
                        data-values="'.$email64_values.'" data-href="'.ROOT_URL.'/includes/master/mailer.php">'.$row['email'].'</a><br>';
                    }
                    if ($row['phone1'] != "") { $ret .= '<i class="fa fa-phone"></i> Phone: <a href="tel:'.$row['phone1'].'">'.$row['phone1'].'</a><br>'; }
                    if ($row['mobile'] != "") { $ret .= '<i class="fa fa-mobile"></i> Mobile: <a href="tel:'.$row['mobile'].'">'.$row['mobile'].'</a><br>'; }
                    $ret .= '</p>
                </div>
                  <div class="card-footer text-center">';
                if (!filter_var($row['email'], FILTER_VALIDATE_EMAIL) === false) {
                    $ret .= '<a href="javascript:void(0)" class="btn btn-secondary noprint emailButton me-4" data-values="'.$email64_values.'" data-href="enrepcore/includes/master/mailer.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" aria-label="Email Client" data-mdb-original-title="Email Client" data-mdb-tooltip-initialized="true"><i class="fad fa-envelope"></i></a>';
                }
                if ($row['phone1'] != "") {
                    $ret .= '<a href="tel:'.$row['phone1'].'" class="btn btn-secondary me-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" aria-label="Phone Client" title="Phone Client"><i class="fa fa-phone"></i></a>';
                }
                $ret .= '<a href="index.php?t=includes/master&p=client.php&clientnumber='.$row['clientnumber'].'&view=edit" class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" aria-label="Edit Client" title="Edit Client"><i class="fad fa-pencil"></i></a>';
        $ret .= '</div>
            </div>
        </div>';
    }
    $ret .= '</div>'; // End of card container

    // Pagination below the results
    $ret .= getPaginationLinks($filter, $page);

    return $ret;
}

// Function to search clients with pagination support
function searchClients($searchTerm = '', $page = 1) {
    global $resultsPerPage;
    $offset = ($page - 1) * $resultsPerPage;
    $searchTermValue = '%' . $searchTerm . '%';

    if ($searchTerm === '') {
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `statuslive` = '1' LIMIT ? OFFSET ?")
                                          or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $resultsPerPage, $offset);
    } else {
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails`
                                          WHERE (`clientname` LIKE ?
                                          OR (clientname LIKE 'The %' AND SUBSTRING(clientname, 5) LIKE ?))
                                          AND `statuslive` = '1' LIMIT ? OFFSET ?")
                                          or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ssii', $searchTermValue, $searchTermValue, $resultsPerPage, $offset);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();

    // Pagination above the results
    $ret = getPaginationLinks($searchTerm, $page, true); // Pass isSearch = true for search

    // Card container with client details
    $ret .= '<div class="card-container">';
    while ($row = mysqli_fetch_array($result)) {
        $email_values = [
            0 => '0',
            1 => $row['clientname'],
            2 => $row['email'],
            3 => 'Subject',
            4 => NULL,
            5 => NULL,
            6 => NULL
        ];
        $email64_values = base64_encode(json_encode($email_values));
print_r($email_values);
        // Check if the client logo exists
        $logoCheck = '../../..'.TENANT_URL.'/images/client/'.$row['clientnumber'].'.jpg';
        $logoPath = 'images/client/'.$row['clientnumber'].'.jpg';
        $logoExists = file_exists($logoCheck) ? $logoPath : 'images/profile/noimage.png';

        $ret .= '
        <div class="card-item">
            <div id="'.$row['clientnumber'].'A" class="card h-100">
                <div class="card-body">
                    <div class="text-center mb-3">
                        <img src="'.$logoExists.'" alt="Client Logo" class="rounded-circle img-fluid" style="max-width: 100px;">
                    </div>
                    <div class="lead"><i>'.$row['clientname'].'</i></div>
                    <p>'.$row['address1'].'<br>';
                    if ($row['address2'] != "") { $ret .= $row['address2'].'<br>'; }
                    if ($row['town'] != "") { $ret .= $row['town'].'<br>'; }
                    if ($row['counry'] != "") { $ret .= $row['counry'].'<br>'; }
                    if ($row['postcode'] != "") { $ret .= $row['postcode'].'<br>'; }
                    if (!filter_var($row['email'], FILTER_VALIDATE_EMAIL) === false) {
                        $ret .= '<i class="fa fa-envelope"></i> Email: <a href="javascript:void(0)" class="emailButton"
                        data-values="'.$email64_values.'" data-href="'.ROOT_URL.'/includes/master/mailer.php">'.$row['email'].'</a><br>';
                    }
                    if ($row['phone1'] != "") { $ret .= '<i class="fa fa-phone"></i> Phone: <a href="tel:'.$row['phone1'].'">'.$row['phone1'].'</a><br>'; }
                    if ($row['mobile'] != "") { $ret .= '<i class="fa fa-mobile"></i> Mobile: <a href="tel:'.$row['mobile'].'">'.$row['mobile'].'</a><br>'; }
                    $ret .= '</p>
                </div>
                  <div class="card-footer text-center">';
                if (!filter_var($row['email'], FILTER_VALIDATE_EMAIL) === false) {
                    $ret .= '<a href="javascript:void(0)" class="btn btn-secondary noprint emailButton me-4" data-values="'.$email64_values.'" data-href="enrepcore/includes/master/mailer.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" aria-label="Email Client" data-mdb-original-title="Email Client" data-mdb-tooltip-initialized="true"><i class="fad fa-envelope"></i></a>';
                }
                if ($row['phone1'] != "") {
                    $ret .= '<a href="tel:'.$row['phone1'].'" class="btn btn-secondary me-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" aria-label="Phone Client" title="Phone Client"><i class="fa fa-phone"></i></a>';
                }
                $ret .= '<a href="index.php?t=includes/master&p=client.php&clientnumber='.$row['clientnumber'].'&view=edit" class="btn btn-secondary" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" aria-label="Edit Client" title="Edit Client"><i class="fad fa-pencil"></i></a>';
        $ret .= '</div>
            </div>
        </div>';
    }
    $ret .= '</div>'; // End of card container

    // Pagination below the results
    $ret .= getPaginationLinks($searchTerm, $page, true); // Pass isSearch = true for search

    return $ret;
}

// Function to create pagination links with truncation (updated for both filter and search)
function getPaginationLinks($termOrFilter = '', $currentPage = 1, $isSearch = false) {
    global $resultsPerPage;

    // Prepare the correct query for counting results based on whether it's a search or filter
    if ($isSearch) {
        $searchTermValue = '%' . $termOrFilter . '%';
        $stmt = $GLOBALS['con']->prepare("SELECT COUNT(*) as total FROM `clientdetails`
                                          WHERE (`clientname` LIKE ?
                                          OR (clientname LIKE 'The %' AND SUBSTRING(clientname, 5) LIKE ?))
                                          AND `statuslive` = '1'")
                                          or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ss', $searchTermValue, $searchTermValue);
    } else {
        $filterValue = $termOrFilter . '%';
        $stmt = $GLOBALS['con']->prepare("SELECT COUNT(*) as total FROM `clientdetails`
                                          WHERE (`clientname` LIKE ? 
                                          OR (`clientname` LIKE 'The %' AND SUBSTRING(clientname, 5, 1) = ?)) 
                                          AND `statuslive` = '1'")
                                          or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ss', $filterValue, $termOrFilter);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    $row = mysqli_fetch_assoc($result);
    $totalClients = $row['total'];
    $stmt->close();

    // Calculate total pages
    $totalPages = ceil($totalClients / $resultsPerPage);
    $pagination = '<nav class="mt-4"><ul class="pagination justify-content-center">';

    if ($totalPages > 1) {
        $maxVisibleLinks = 5; // Show 5 pagination links around the current page

        // Previous page link
        if ($currentPage > 1) {
            $pagination .= '<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="'.($isSearch ? 'searchClients' : 'filterlist').'(\''.$termOrFilter.'\', '.($currentPage - 1).')">Previous</a></li>';
        }

        // First page link
        if ($currentPage > ($maxVisibleLinks + 1)) {
            $pagination .= '<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="'.($isSearch ? 'searchClients' : 'filterlist').'(\''.$termOrFilter.'\', 1)">1</a></li>';
            $pagination .= '<li class="page-item disabled"><span class="page-link">...</span></li>'; // Ellipsis
        }

        // Display the pagination links around the current page
        $start = max(1, $currentPage - $maxVisibleLinks);
        $end = min($totalPages, $currentPage + $maxVisibleLinks);

        for ($i = $start; $i <= $end; $i++) {
            if ($i == $currentPage) {
                $pagination .= '<li class="page-item active"><a class="page-link" href="javascript:void(0)">'.$i.'</a></li>';
            } else {
                $pagination .= '<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="'.($isSearch ? 'searchClients' : 'filterlist').'(\''.$termOrFilter.'\', '.$i.')">'.$i.'</a></li>';
            }
        }

        // Last page link
        if ($currentPage < ($totalPages - $maxVisibleLinks)) {
            $pagination .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
            $pagination .= '<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="'.($isSearch ? 'searchClients' : 'filterlist').'(\''.$termOrFilter.'\', '.$totalPages.')">'.$totalPages.'</a></li>';
        }

        // Next page link
        if ($currentPage < $totalPages) {
            $pagination .= '<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="'.($isSearch ? 'searchClients' : 'filterlist').'(\''.$termOrFilter.'\', '.($currentPage + 1).')">Next</a></li>';
        }
    }

    $pagination .= '</ul></nav>';

    return $pagination;
}

// Handle AJAX requests for search and filter
if (isset($_POST['search'])) {
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    echo searchClients($_POST['search'], $page);
} elseif (isset($_POST['filter'])) {
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    echo getFilteredListByLetter($_POST['filter'], $page);
}