<?php
session_start();
header('Content-Type: application/json');
include_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

$userId = $_SESSION['uid'];

// Get all hold bills for current user (or all if admin)
$userType = isset($_SESSION['usertype']) ? $_SESSION['usertype'] : '';
$whereClause = '';

// If not admin, show only own held bills
if ($userType !== 'Admin') {
    $whereClause = "WHERE HeldBy = $userId";
}

$query = "SELECT 
    ID, HoldNumber, CustomerID, CustomerName, SalesType, InvoiceNumber,
    SubTotal, TaxAmount, GrandTotal, Discount, RoundOff, TotalItems,
    HeldBy, HeldDate, Notes
    FROM tblhold_bills 
    $whereClause
    ORDER BY HeldDate DESC";

$result = mysqli_query($con, $query);

if (!$result) {
    echo json_encode(['success' => false, 'message' => 'Query failed: ' . mysqli_error($con)]);
    exit();
}

$holdBills = array();
while ($row = mysqli_fetch_assoc($result)) {
    $holdBills[] = $row;
}

echo json_encode([
    'success' => true,
    'data' => $holdBills,
    'count' => count($holdBills)
]);

mysqli_close($con);
?>
