<?php include '../db.php'; ?>

<h2>Client List</h2>
<form method="get">
    <input type="text" name="search" placeholder="Search by name or email" value="<?= $_GET['search'] ?? '' ?>">
    <button type="submit">Search</button>
</form>

<a href="add.php">+ Add Client</a>
<table border="1" cellpadding="5" cellspacing="0">
    <tr>
        <th>ID</th><th>Name</th><th>Company</th><th>Email</th><th>Phone</th><th>Actions</th>
    </tr>

<?php
$limit = 10;
$page = $_GET['page'] ?? 1;
$offset = ($page - 1) * $limit;

$search = $_GET['search'] ?? '';
$searchSQL = $search ? "WHERE name LIKE :s OR email LIKE :s" : "";

$stmt = $conn->prepare("SELECT * FROM clients $searchSQL ORDER BY id DESC LIMIT $limit OFFSET $offset");
if ($search) $stmt->bindValue(':s', "%$search%");
$stmt->execute();
$clients = $stmt->fetchAll();

foreach ($clients as $c) {
    echo "<tr>
        <td>{$c['id']}</td>
        <td>{$c['name']}</td>
        <td>{$c['company_name']}</td>
        <td>{$c['email']}</td>
        <td>{$c['phone']}</td>
        <td>
            <a href='edit.php?id={$c['id']}'>Edit</a> |
            <a href='delete.php?id={$c['id']}' onclick=\"return confirm('Are you sure?')\">Delete</a> |
            <a href='print.php?id={$c['id']}'>Print</a>
        </td>
    </tr>";
}
?>

</table>

<?php
// Pagination Links
$total = $conn->query("SELECT COUNT(*) FROM clients")->fetchColumn();
$totalPages = ceil($total / $limit);

for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='index.php?page=$i&search=$search'>$i</a> ";
}
?>
