<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

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

if (isset($_REQUEST["item"])) {
    $item = $_REQUEST["item"];
    $vouchdt = $_REQUEST["vouchdt"];

    $ctr = 0;

    $getexpense = mysqli_query($conn, "SELECT a.*,b.name FROM `order` a
                                       LEFT JOIN accmast b ON a.vendor = b.accode         
                                       WHERE a.`expense` = '$item' AND a.vouchdt <= '$vouchdt' order by vouchdt desc, vouchno desc LIMIT 3") or die(mysqli_error($conn));

    if (mysqli_num_rows($getexpense) > 0) {
        while ($gtpt = mysqli_fetch_array($getexpense)) {
            $ctr++;

            $date = convertDate($gtpt['vouchdt']) ?? '';
            $time = date("g:i a", strtotime($gtpt['time']));            
            $qty = $gtpt['qty'] ?? '';
            $unit = $gtpt['unit'] ?? '';
            $orderby = $gtpt['orderby'] ?? '';
            $vendor = $gtpt['name'] ?? '';

            echo "<tr>";
            echo "<td class='text-center'>$ctr</td>";
            echo "<td class='text-center'>$date</td>";
            echo "<td class='text-center'>$time</td>";
            echo "<td class='text-right'>$qty $unit</td>";
            echo "<td>$vendor</td>";
            echo "<td>$orderby</td>";
            echo "</tr>";
        }
    } else {
        echo "<tr><td colspan='5' style='text-align:center;'>No Record Found</td></tr>";
    }
} else {
    echo "<tr><td colspan='5' style='text-align:center;'>ERROR: Missing parameters</td></tr>";
}
?>