<?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(pr.return_date) >= '" . $conn->real_escape_string($start_date) . "'", "DATE(pr.return_date) <= '" . $conn->real_escape_string($end_date) . "'"];
if ($search !== '') {
    $search_sql = $conn->real_escape_string($search);
    $where[] = "(p.purchase_number LIKE '%$search_sql%' OR v.name LIKE '%$search_sql%')";
}
$where_clause = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT pr.id, pr.return_date, pr.total_amount, p.purchase_number, v.name AS vendor
    FROM purchase_returns pr
    JOIN purchases p ON pr.purchase_id = p.id
    JOIN vendors v ON pr.vendor_id = v.id
    $where_clause
    ORDER BY pr.return_date DESC
    LIMIT 100
";
$result = $conn->query($sql);
?>
<div class="page-wrapper">
  <div class="content">
    <h4>Purchase 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="Purchase # or Vendor">
      </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>Purchase #</th>
          <th>Vendor</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['purchase_number']) ?></td>
              <td><?= htmlspecialchars($row['vendor']) ?></td>
              <td><?= number_format($row['total_amount'], 2) ?></td>
              <td>
                <a href="purchase_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 purchase returns found for the selected criteria.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div> 