<?php
include("dbconfig.php");

// Check if BillNo is passed in the URL
if (isset($_GET['Billno'])) {
    $billNo = $_GET['Billno'];

    // Identify the source table (bill, finalbill, or advance)
    // Query each table to check where the BillNo exists
    $query1 = mysqli_query($db, "SELECT * FROM `bill` WHERE BillNo = '$billNo' AND is_deleted != 0");
    $query2 = mysqli_query($db, "SELECT * FROM `finalbill` WHERE FinalBillNo = '$billNo' AND is_deleted != 0");
    $query3 = mysqli_query($db, "SELECT * FROM `advance` WHERE BillNo = '$billNo' AND is_deleted != 0");

    if (mysqli_num_rows($query1) > 0) {
        // Mark record as deleted in `bill` table (set is_deleted = 0)
        $deleteQuery = mysqli_query($db, "UPDATE `bill` SET is_deleted = 0 WHERE BillNo = '$billNo'");
        if ($deleteQuery) {
            echo "<script>alert('Bill record marked as deleted successfully!'); window.location.href = 'SearchBill.php';</script>";
        } else {
            echo "<script>alert('Failed to mark bill record as deleted.'); window.location.href = 'SearchBill.php';</script>";
        }
    } elseif (mysqli_num_rows($query2) > 0) {
        // Mark record as deleted in `finalbill` table (set is_deleted = 0)
        $deleteQuery = mysqli_query($db, "UPDATE `finalbill` SET is_deleted = 0 WHERE FinalBillNo = '$billNo'");
        if ($deleteQuery) {
            echo "<script>alert('Final Bill record marked as deleted successfully!'); window.location.href = 'SearchBill.php';</script>";
        } else {
            echo "<script>alert('Failed to mark final bill record as deleted.'); window.location.href = 'SearchBill.php';</script>";
        }
    } elseif (mysqli_num_rows($query3) > 0) {
        // Mark record as deleted in `advance` table (set is_deleted = 0)
        $deleteQuery = mysqli_query($db, "UPDATE `advance` SET is_deleted = 0 WHERE BillNo = '$billNo'");
        if ($deleteQuery) {
            echo "<script>alert('Advance record marked as deleted successfully!'); window.location.href = 'SearchBill.php';</script>";
        } else {
            echo "<script>alert('Failed to mark advance record as deleted.'); window.location.href = 'SearchBill.php';</script>";
        }
    } else {
        // BillNo not found in any table
        echo "<script>alert('Record not found or already marked as deleted!'); window.location.href = 'SearchBill.php';</script>";
    }
} else {
    echo "<script>alert('Invalid request!'); window.location.href = 'SearchBill.php';</script>";
}
?>
