<?php
require_once "../config/db.php";
require_once "../config/helpers.php";

$search = trim($_GET['search'] ?? '');

$where = "";

if($search){
    $search = $conn->real_escape_string($search);
    $where = "WHERE s.service_name LIKE '%$search%' OR c.name LIKE '%$search%'";
}

$query = "
SELECT s.*, c.name as customer_name
FROM services s
JOIN customers c ON s.customer_id = c.id
$where
ORDER BY s.id DESC
LIMIT 50
";

$result = $conn->query($query);

if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
?>
<tr>
    <td><?= e($row['customer_name']) ?></td>
    <td><?= e($row['service_name']) ?></td>
    <td><?= ucfirst($row['type']) ?></td>
    <td>₹<?= number_format($row['amount'],2) ?></td>
    <td><?= $row['renewal_date'] ?></td>

    <td>
        <a href="edit_service.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</a>
        <a href="../actions/delete_service.php?id=<?= $row['id'] ?>"
           class="btn btn-danger btn-sm"
           onclick="return confirm('Delete?')">Delete</a>
    </td>
</tr>
<?php
    }
} else {
    echo "<tr><td colspan='6' class='text-center'>No data found</td></tr>";
}