<?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'];
$userType = isset($_SESSION['usertype']) ? $_SESSION['usertype'] : '';

// Get hold bill ID
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['id']) || empty($data['id'])) {
    echo json_encode(['success' => false, 'message' => 'Hold bill ID is required']);
    exit();
}

$holdBillId = intval($data['id']);

// Check if user owns this bill or is admin
$checkQuery = "SELECT HeldBy FROM tblhold_bills WHERE ID = $holdBillId";
$checkResult = mysqli_query($con, $checkQuery);

if (mysqli_num_rows($checkResult) === 0) {
    echo json_encode(['success' => false, 'message' => 'Hold bill not found']);
    exit();
}

$holdBill = mysqli_fetch_assoc($checkResult);

// If not admin, check ownership
if ($userType !== 'Admin' && $holdBill['HeldBy'] != $userId) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to delete this hold bill']);
    exit();
}

// Delete the hold bill
$deleteQuery = "DELETE FROM tblhold_bills WHERE ID = $holdBillId";

if (mysqli_query($con, $deleteQuery)) {
    echo json_encode([
        'success' => true,
        'message' => 'Hold bill deleted successfully'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to delete hold bill: ' . mysqli_error($con)
    ]);
}

mysqli_close($con);
?>
