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

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: auth/login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$allowed_ids = [1, 2, 3];

$limit = 25;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// استعلام حسب صلاحيات المستخدم
if (in_array($user_id, $allowed_ids)) {
    $query = "SELECT v.*, u.name AS entered_name FROM vouchers v
              LEFT JOIN users u ON v.entered_by = u.id
              ORDER BY v.id DESC LIMIT $limit OFFSET $offset";
    $count_query = "SELECT COUNT(*) as total FROM vouchers";
} else {
    $query = "SELECT v.*, u.name AS entered_name FROM vouchers v
              LEFT JOIN users u ON v.entered_by = u.id
              WHERE v.entered_by = $user_id
              ORDER BY v.id DESC LIMIT $limit OFFSET $offset";
    $count_query = "SELECT COUNT(*) as total FROM vouchers WHERE entered_by = $user_id";
}

$result = $conn->query($query);
$total_result = $conn->query($count_query);
$total = $total_result->fetch_assoc()['total'];
$total_pages = ceil($total / $limit);
?>

<?php include 'header.php'; ?>

<div class="main-content p-4" style="flex: 1;">

<h2 class="mb-4"><?= $lang['view_vouchers'] ?></h2>

<!-- مربع البحث -->
<input type="text" id="search" class="form-control mb-3" placeholder="<?= $lang['search'] ?>">

<?php if ($result->num_rows > 0): ?>
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead class="table-dark">
                <tr>
                    <th>#</th>
                    <th><?= $lang['hotel_name'] ?></th>
                    <th><?= $lang['customer_name'] ?></th>
                    <th><?= $lang['voucher_date'] ?></th>
                    <th><?= $lang['check_in'] ?></th>
                    <th><?= $lang['check_out'] ?></th>
                    <th><?= $lang['nights2'] ?></th>
                    <th><?= $lang['rooms_count2'] ?></th>
                    <th><?= $lang['room_type'] ?></th>
                    <th><?= $lang['meal_plan2'] ?></th>
                    <th><?= $lang['status'] ?></th>
                    <th><?= $lang['booking_number2'] ?></th>
                    <th><?= $lang['hotel_confirmation_number2'] ?></th>

                    <th><?= $lang['entered_by'] ?></th>
                    <th><?= $lang['actions'] ?></th>
                </tr>
            </thead>
            <tbody id="voucher-body">
                <?php $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['hotel_confirmation_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['download'] ?></a>
                                                            <a href="edit_voucher.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-warning"><?= $lang['edit'] ?></a>
<a href="edit_confirmation_number.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-info"><?= $lang['edit_conf_number2'] ?></a>

                            <?php if (in_array($user_id, [1, 2])): ?>
                                <button onclick="confirmDelete(<?= $row['id'] ?>)" class="btn btn-sm btn-danger"><?= $lang['delete'] ?></button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <!-- ترقيم الصفحات -->
    <?php if ($total_pages > 1): ?>
    <form method="get" class="mt-3 d-flex align-items-center gap-2 flex-wrap">
        <button type="submit" name="page" value="1" class="btn btn-outline-primary btn-sm" <?= $page == 1 ? 'disabled' : '' ?>>
            &laquo; <?= $lang['first'] ?? 'First' ?>
        </button>
        <button type="submit" name="page" value="<?= max(1, $page - 1) ?>" class="btn btn-outline-primary btn-sm" <?= $page == 1 ? 'disabled' : '' ?>>
            &lsaquo; <?= $lang['prev'] ?? 'Previous' ?>
        </button>
        <label for="page-select" class="mb-0"><?= $lang['page'] ?>:</label>
        <select name="page" id="page-select" onchange="this.form.submit()" class="form-select form-select-sm w-auto d-inline-block">
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <option value="<?= $i ?>" <?= $i == $page ? 'selected' : '' ?>><?= $i ?></option>
            <?php endfor; ?>
        </select>
        <button type="submit" name="page" value="<?= min($total_pages, $page + 1) ?>" class="btn btn-outline-primary btn-sm" <?= $page == $total_pages ? 'disabled' : '' ?>>
            <?= $lang['next'] ?? 'Next' ?> &rsaquo;
        </button>
        <button type="submit" name="page" value="<?= $total_pages ?>" class="btn btn-outline-primary btn-sm" <?= $page == $total_pages ? 'disabled' : '' ?>>
            <?= $lang['last'] ?? 'Last' ?> &raquo;
        </button>
    </form>
    <?php endif; ?>

<?php else: ?>
    <div class="alert alert-info"><?= $lang['no_data'] ?></div>
<?php endif; ?>
</div> <!-- Close main-content -->

<?php include 'includes/footer.php'; ?>

<script>
// تأكيد الحذف مرتين
function confirmDelete(id) {
    if (confirm("<?= $lang['confirm_delete_once'] ?>")) {
        if (confirm("<?= $lang['confirm_delete_twice'] ?>")) {
            window.location.href = 'delete_voucher.php?id=' + id;
        }
    }
}

// البحث عبر أجاكس
document.getElementById('search').addEventListener('input', function() {
    let keyword = this.value;
    fetch('search_vouchers.php?q=' + encodeURIComponent(keyword))
        .then(res => res.text())
        .then(data => {
            document.getElementById('voucher-body').innerHTML = data;
        });
});
</script>
