<?php
require("includes/dbconnect.php");

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

$startdate = $_POST['start'];
$enddate = $_POST['end'];

$page = $_POST['page'];
$limit = 10;
$offset = ($page - 1) * $limit;

/* ===== DATA ===== */

$q = mysqli_query($conn, "
SELECT vouchno, pname, date,
(tiktamt+hotelinramt+foodinramt+laundinramt+transinramt+visaamt) as total
FROM pax
WHERE date BETWEEN '$startdate' AND '$enddate'
ORDER BY date DESC
LIMIT $limit OFFSET $offset
");

$output = "";

/* ===== TABLE ROWS ===== */

if (mysqli_num_rows($q) > 0) {

    while ($r = mysqli_fetch_assoc($q)) {

        $output .= "<tr>

<td class='text-primary fw-bold'>{$r['vouchno']}</td>
<td>{$r['pname']}</td>
<td>" . date("M d, Y", strtotime($r['date'])) . "</td>
<td>₹ " . number_format($r['total']) . "</td>

<td>
<a href='view_booking.php?vouchno={$r['vouchno']}' 
class='btn btn-sm btn-primary'>View</a>
</td>

</tr>";
    }

} else {
    $output .= "<tr><td colspan='5' class='text-center'>No data found</td></tr>";
}

/* ===== PAGINATION ===== */

$totalQ = mysqli_query($conn, "
SELECT COUNT(*) as total FROM pax
WHERE date BETWEEN '$startdate' AND '$enddate'
");

$totalRow = mysqli_fetch_assoc($totalQ);
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $limit);

$pagination = "";

for ($i = 1; $i <= $totalPages; $i++) {
    $active = ($i == $page) ? "active" : "";
    $pagination .= "<li class='page-item $active'>
<a class='page-link pageBtn' data-page='$i'>$i</a>
</li>";
}

echo json_encode([
    "rows" => $output,
    "pagination" => $pagination
]);