<?php
include("config.php");

$query = isset($_POST['query']) ? trim($_POST['query']) : '';
$searchQuery = mysqli_real_escape_string($conn, $query);
$uploadpath = "uploads/"; // your upload folder path

if (!empty($searchQuery)) {
    // Search across full name (concatenated), phones, email, address, city
    $sql = "SELECT * FROM contact_book
            WHERE CONCAT_WS(' ', first_name, middle_name, last_name) LIKE '%$searchQuery%'
            OR phone1 LIKE '%$searchQuery%'
            OR phone2 LIKE '%$searchQuery%'
            OR email LIKE '%$searchQuery%'
            OR address LIKE '%$searchQuery%'
            OR city LIKE '%$searchQuery%'
            ORDER BY id DESC";
} else {
    $sql = "SELECT * FROM contact_book ORDER BY id DESC";
}

$result = $conn->query($sql);
$response = "";
$count = 0;

if ($result && $result->num_rows > 0) {
    while ($data = mysqli_fetch_assoc($result)) {
        $count++;
        $photo = empty($data['photo_copy']) 
                 ? 'img/vouchersimg_1.png' 
                 : "../admin/" . $uploadpath . $data['photo_copy'];

        $response .= "
        <tr>
            <td>{$count}</td>
            <td><img src='{$photo}' class='img-fluid' style='border-radius:50%;width:50px;height:50px;'></td>
            <td>" . ucfirst($data['gender_typ']) . " " . ucfirst($data['first_name']) . " " . ucfirst($data['middle_name']) . " " . ucfirst($data['last_name']) . "<br>" . $data['phone1'] . ($data['phone2'] ? " / " . $data['phone2'] : "") . "</td>
            <td>
                <a href='add_contact.php?id={$data['id']}&flag=add'><i class='fa fa-edit'></i></a>
                &nbsp;&nbsp;&nbsp;
                <a class='btn3' title='delete' href='submit-contact-book.php?flag=del&id={$data['id']}' onclick=\"return confirm('Do You Want To Delete This?');\">
                    <i class='fa fa-trash icon-white'></i>
                </a>
            </td>
            <td>
                <a href='viewinfo.php?id={$data['id']}&flag=view'><button class='btn5'>View Info</button></a>
            </td>
        </tr>";
    }
} else {
    $response = "<tr><td colspan='8'>No results found</td></tr>";
}

echo $response;
$conn->close();
?>
