<?php
require_once 'config/config.php';

session_start();
$user_id = $_SESSION['user_id'] ?? null;
$allowed_ids = [1, 2, 3];

if (!$user_id) exit;

$search = $conn->real_escape_string($_GET['q'] ?? '');

$where = '';
if (!in_array($user_id, $allowed_ids)) {
    $where .= "v.entered_by = $user_id AND ";
}
if ($search !== '') {
    $where .= "(
        v.hotel_name LIKE '%$search%' OR 
        v.customer_name LIKE '%$search%' OR 
        v.voucher_date LIKE '%$search%' OR 
        v.check_in_date LIKE '%$search%' OR 
        v.check_out_date LIKE '%$search%' OR 
        v.nights LIKE '%$search%' OR 
        v.rooms_count LIKE '%$search%' OR 
        v.room_type LIKE '%$search%' OR 
        v.meal_plan LIKE '%$search%' OR 
        v.status LIKE '%$search%' OR 
        v.booking_number LIKE '%$search%'
    )";

} else {
    $where .= "1";
}

$query = "SELECT v.*, u.name AS entered_name 
          FROM vouchers v 
          LEFT JOIN users u ON v.entered_by = u.id 
          WHERE $where 
          ORDER BY v.id DESC 
          LIMIT 25";

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

while ($row = $result->fetch_assoc()):
?>
<tr>
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($row['hotel_name'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['customer_name'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['voucher_date'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['check_in_date'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['check_out_date'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['nights'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['rooms_count'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['room_type'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['meal_plan'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['status'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['booking_number'] ?? '-') ?></td>
    <td><?= htmlspecialchars($row['entered_name'] ?? '-') ?></td>
    <td>
        <a href="generate_pdf.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-primary" target="_blank"><?= $lang['view'] ?></a>
        <?php if (in_array($user_id, [1, 2])): ?>
            <a href="edit_voucher.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-warning"><?= $lang['edit'] ?></a>
            <button onclick="confirmDelete(<?= $row['id'] ?>)" class="btn btn-sm btn-danger"><?= $lang['delete'] ?></button>
        <?php endif; ?>
    </td>
</tr>
<?php endwhile; ?>
