<?php
include 'auth_check.php';

if (!isAdmin()) {
    header("Location: sale.php");
    exit();
}

$bill_number = isset($_GET['bill_number']) ? trim($_GET['bill_number']) : '';
$entered_date = isset($_GET['entered_date']) ? trim($_GET['entered_date']) : '';
$entered_user = isset($_GET['entered_user']) ? trim($_GET['entered_user']) : '';

$where = [];
if ($bill_number !== '') {
    $where[] = "s.bill_number LIKE '%" . $conn->real_escape_string($bill_number) . "%'";
}
if ($entered_date !== '') {
    $where[] = "s.entered_date = '" . $conn->real_escape_string($entered_date) . "'";
}
if ($entered_user !== '') {
    $where[] = "s.entered_user LIKE '%" . $conn->real_escape_string($entered_user) . "%'";
}

$whereSql = '';
if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

$query = "SELECT s.bill_number, s.entered_date, s.entered_time, s.entered_user, s.total_amount, s.received_amount, s.balance_amount, s.total_discount,
                 b.product_name, b.unit, b.selling_price, b.qty, b.discount, b.line_total
          FROM selling_data s
          LEFT JOIN billing_data b ON s.bill_number = b.bill_number
          $whereSql
          ORDER BY CASE WHEN s.balance_amount < 0 THEN 0 ELSE 1 END, s.entered_date DESC, s.entered_time DESC, s.bill_number DESC";
$result = $conn->query($query);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Bill Search</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('bill_search'); ?>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <div class="table-card">
            <h2>Bill Search</h2>
            <form method="GET" class="search-bar">
                <input type="text" name="bill_number" placeholder="Search Bill Number" value="<?php echo htmlspecialchars($bill_number); ?>">
                <input type="date" name="entered_date" value="<?php echo htmlspecialchars($entered_date); ?>">
                <input type="text" name="entered_user" placeholder="Search Entered User" value="<?php echo htmlspecialchars($entered_user); ?>">
                <button type="submit">Search</button>
                <?php if ($bill_number !== '') { ?>
                    <button type="button" onclick="printSearchedBill()">Bill Print</button>
                <?php } ?>
            </form>

            <div class="table-scroll">
                <table id="billSearchTable">
                    <tr>
                        <th>Bill No</th>
                        <th>Date</th>
                        <th>User</th>
                        <th>Product</th>
                        <th>Unit</th>
                        <th>Unit Price</th>
                        <th>Qty</th>
                        <th>Discount</th>
                        <th>Line Total</th>
                        <th>Bill Total</th>
                        <th>Received</th>
                        <th>Balance</th>
                    </tr>
                    <?php while($row = $result->fetch_assoc()) { ?>
                    <tr class="<?php echo ($row['balance_amount'] < 0) ? 'negative-balance' : ''; ?>">
                        <td><?php echo $row['bill_number']; ?></td>
                        <td><?php echo $row['entered_date'] . ' ' . $row['entered_time']; ?></td>
                        <td><?php echo $row['entered_user']; ?></td>
                        <td><?php echo $row['product_name']; ?></td>
                        <td><?php echo $row['unit']; ?></td>
                        <td><?php echo number_format((float)$row['selling_price'], 2); ?></td>
                        <td><?php echo $row['qty']; ?></td>
                        <td><?php echo number_format((float)$row['discount'], 2); ?></td>
                        <td><?php echo number_format((float)$row['line_total'], 2); ?></td>
                        <td><?php echo number_format((float)$row['total_amount'], 2); ?></td>
                        <td><?php echo number_format((float)$row['received_amount'], 2); ?></td>
                        <td><?php echo number_format((float)$row['balance_amount'], 2); ?></td>
                    </tr>
                    <?php } ?>
                </table>
            </div>
        </div>
    </main>
</div>

<script>
function printSearchedBill() {
    const billNo = <?php echo json_encode($bill_number); ?>;
    if (!billNo) {
        alert('Please search a bill first.');
        return;
    }

    let oldFrame = document.getElementById('bill_search_print_frame');
    if (oldFrame) oldFrame.remove();

    const iframe = document.createElement('iframe');
    iframe.id = 'bill_search_print_frame';
    iframe.style.position = 'absolute';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    iframe.src = 'print_bill.php?bill_number=' + encodeURIComponent(billNo);
    document.body.appendChild(iframe);
}
</script>
</body>
</html>