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

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$return = $conn->query("SELECT sr.*, s.invoice_number, s.customer_name FROM sale_returns sr JOIN sales s ON sr.sale_id = s.id WHERE sr.id = $id")->fetch_assoc();
if (!$return) {
    echo "<div class='alert alert-danger'>Sale return not found.</div>";
    exit;
}
$items = $conn->query("SELECT sri.*, i.name as item_name FROM sale_return_items sri JOIN items i ON sri.item_id = i.id WHERE sri.sale_return_id = $id");
?>
<div class="page-wrapper">
  <div class="content">
    <h4>Sale Return Details</h4>
    <div class="mb-3">
      <strong>Return Date:</strong> <?= htmlspecialchars($return['return_date']) ?><br>
      <strong>Invoice #:</strong> <?= htmlspecialchars($return['invoice_number']) ?><br>
      <strong>Customer:</strong> <?= htmlspecialchars($return['customer_name']) ?><br>
      <strong>Total Amount:</strong> <?= number_format($return['total_amount'], 2) ?><br>
      <strong>Remarks:</strong> <?= htmlspecialchars($return['remarks']) ?><br>
    </div>
    <table class="table table-bordered">
      <thead class="table-light">
        <tr>
          <th>Item</th>
          <th>Return Qty</th>
          <th>Unit Price</th>
          <th>Total</th>
          <th>Tax Rate</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($item = $items->fetch_assoc()): ?>
        <tr>
          <td><?= htmlspecialchars($item['item_name']) ?></td>
          <td><?= $item['quantity'] ?></td>
          <td><?= number_format($item['unit_price'], 2) ?></td>
          <td><?= number_format($item['total_price'], 2) ?></td>
          <td><?= number_format($item['tax_rate'], 2) ?>%</td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
    <a href="sale_return_report.php" class="btn btn-secondary mt-3">Back to Report</a>
  </div>
</div> 