<?php
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $purchase_id = intval($_POST['purchase_id'] ?? 0);
    $remarks = trim($_POST['remarks'] ?? '');
    $return_qtys = $_POST['return_qty'] ?? [];
    $return_type = $_POST['return_type'] ?? 'whole';

    if ($purchase_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid purchase selected.']);
        exit;
    }
    $purchase = $conn->query("SELECT * FROM purchases WHERE id = $purchase_id")->fetch_assoc();
    if (!$purchase) {
        echo json_encode(['success' => false, 'message' => 'Purchase not found.']);
        exit;
    }
    $vendor_id = $purchase['vendor_id'];
    $total_return = 0;
    $conn->query("INSERT INTO purchase_returns (purchase_id, vendor_id, total_amount, remarks) VALUES ($purchase_id, $vendor_id, 0, '" . $conn->real_escape_string($remarks) . "')");
    $purchase_return_id = $conn->insert_id;

    $items = $conn->query("SELECT * FROM purchase_items WHERE purchase_id = $purchase_id");
    while ($item = $items->fetch_assoc()) {
        $item_id = $item['id'];
        $qty = isset($return_qtys[$item_id]) ? intval($return_qtys[$item_id]) : 0;
        if ($qty > 0 && $qty <= $item['quantity']) {
            $unit_cost = $item['unit_cost'];
            $total_cost = $qty * $unit_cost;
            $total_return += $total_cost;
            $conn->query("INSERT INTO purchase_return_items (purchase_return_id, item_id, quantity, unit_cost, total_cost, tax_rate) VALUES ($purchase_return_id, {$item['item_id']}, $qty, $unit_cost, $total_cost, {$item['tax_rate']})");
            // Add inventory movement (out)
            $conn->query("INSERT INTO inventory_movements (item_id, movement_type, reference_type, reference_id, quantity) VALUES ({$item['item_id']}, 'out', 'purchase_return', $purchase_return_id, $qty)");
        }
    }
    $conn->query("UPDATE purchase_returns SET total_amount = $total_return WHERE id = $purchase_return_id");
    echo json_encode(['success' => true, 'message' => 'Purchase return processed successfully!']);
    exit;
}

$purchase_id = isset($_GET['purchase_id']) ? intval($_GET['purchase_id']) : 0;
if ($purchase_id <= 0) {
    echo '<div class="alert alert-danger">Invalid purchase selected.</div>';
    exit;
}
$purchase = $conn->query("SELECT p.*, v.name AS vendor FROM purchases p JOIN vendors v ON p.vendor_id = v.id WHERE p.id = $purchase_id")->fetch_assoc();
if (!$purchase) {
    echo '<div class="alert alert-danger">Purchase not found.</div>';
    exit;
}
$items = $conn->query("SELECT * FROM purchase_items WHERE purchase_id = $purchase_id");
?>
<div>
  <h5>Return for Purchase: <?= htmlspecialchars($purchase['purchase_number']) ?></h5>
  <p>Supplier: <?= htmlspecialchars($purchase['vendor']) ?> | Date: <?= htmlspecialchars($purchase['purchase_date']) ?></p>
  <form id="purchase-return-form">
    <input type="hidden" name="purchase_id" value="<?= $purchase_id ?>">
    <div class="mb-3">
      <label class="form-label">Return Type:</label>
      <div>
        <input type="radio" name="return_type" value="whole" id="return_whole" checked>
        <label for="return_whole" style="margin-right: 20px;">Return Whole Bill</label>
        <input type="radio" name="return_type" value="itemwise" id="return_itemwise">
        <label for="return_itemwise">Return Item-wise</label>
      </div>
    </div>
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>Item</th>
          <th>Purchased Qty</th>
          <th>Return Qty</th>
          <th>Unit Cost</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($item = $items->fetch_assoc()): ?>
        <tr>
          <td><?= htmlspecialchars($item['item_name']) ?></td>
          <td><?= $item['quantity'] ?></td>
          <td>
            <input type="number" name="return_qty[<?= $item['id'] ?>]" min="0" max="<?= $item['quantity'] ?>" value="0" class="form-control return-qty-input" style="width:80px;">
          </td>
          <td><?= number_format($item['unit_cost'], 2) ?></td>
          <td><?= number_format($item['total_cost'], 2) ?></td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
    <div class="mb-3">
      <label>Remarks</label>
      <input type="text" name="remarks" class="form-control">
    </div>
    <button type="submit" class="btn btn-warning">Process Return</button>
  </form>
</div>
<script>
(function() {
  function setReturnType() {
    var isWhole = document.getElementById('return_whole').checked;
    document.querySelectorAll('.return-qty-input').forEach(function(input) {
      if (isWhole) {
        input.value = input.max;
        input.readOnly = true;
      } else {
        input.value = 0;
        input.readOnly = false;
      }
    });
  }
  document.getElementById('return_whole').addEventListener('change', setReturnType);
  document.getElementById('return_itemwise').addEventListener('change', setReturnType);
  setReturnType();
})();
</script> 