<?php
require 'db.php';
include 'layout.php'; // Or your header/navbar include

// Get filter values
$date = $_GET['date'] ?? date('Y-m-d');
$search = trim($_GET['search'] ?? '');

$where = ["DATE(sale_date) = '" . $conn->real_escape_string($date) . "'"];
if ($search !== '') {
    $search_sql = $conn->real_escape_string($search);
    $where[] = "(invoice_number LIKE '%$search_sql%' OR customer_name LIKE '%$search_sql%')";
}
$where_clause = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT id, invoice_number, sale_date, customer_name
    FROM sales
    $where_clause
    ORDER BY sale_date DESC
    LIMIT 50
";
$result = $conn->query($sql);
?>

<div class="page-wrapper">
  <div class="content">
    <h4>Sales Return - Search Invoice</h4>
    <form method="get" class="row g-2 mb-3">
        <div class="col-md-3">
            <input type="date" name="date" class="form-control" value="<?= htmlspecialchars($date) ?>">
        </div>
        <div class="col-md-5">
            <input type="text" name="search" class="form-control" placeholder="Invoice # or Customer" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary w-100">Filter</button>
        </div>
    </form>
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Invoice #</th>
                    <th>Date</th>
                    <th>Customer</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result && $result->num_rows): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['invoice_number']) ?></td>
                            <td><?= htmlspecialchars($row['sale_date']) ?></td>
                            <td><?= htmlspecialchars($row['customer_name']) ?></td>
                            <td>
                                <a href="sale_return.php?sale_id=<?= urlencode($row['id']) ?>" class="btn btn-warning btn-sm">Return</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="4" class="text-center">No invoices found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
  </div>
</div> 