<?php
require 'db.php';
include 'layout.php';

// Filters
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$search = trim($_GET['search'] ?? '');

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

$sql = "
    SELECT sr.id, sr.return_date, sr.total_amount, s.invoice_number, s.customer_name
    FROM sale_returns sr
    JOIN sales s ON sr.sale_id = s.id
    $where_clause
    ORDER BY sr.return_date DESC
    LIMIT 100
";
$result = $conn->query($sql);
?>
<div class="page-wrapper">
  <div class="content">
    <h4>Sales Return Report</h4>
    <form method="get" class="row g-2 mb-3">
      <div class="col-md-3">
        <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" class="form-control">
      </div>
      <div class="col-md-3">
        <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" class="form-control">
      </div>
      <div class="col-md-4">
        <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" class="form-control" placeholder="Invoice # or Customer">
      </div>
      <div class="col-md-2">
        <button type="submit" class="btn btn-primary w-100">Filter</button>
      </div>
    </form>
    <table class="table table-bordered table-striped">
      <thead class="table-light">
        <tr>
          <th>Return Date</th>
          <th>Invoice #</th>
          <th>Customer</th>
          <th>Total Amount</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($result && $result->num_rows > 0): ?>
          <?php while ($row = $result->fetch_assoc()): ?>
            <tr>
              <td><?= htmlspecialchars($row['return_date']) ?></td>
              <td><?= htmlspecialchars($row['invoice_number']) ?></td>
              <td><?= htmlspecialchars($row['customer_name']) ?></td>
              <td><?= number_format($row['total_amount'], 2) ?></td>
              <td>
                <a href="sale_return_view.php?id=<?= $row['id'] ?>" class="btn btn-info btn-sm">View</a>
              </td>
            </tr>
          <?php endwhile; ?>
        <?php else: ?>
          <tr><td colspan="5" class="text-center">No sale returns found for the selected criteria.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div> 