<?php
require 'db.php';
require 'journal_entry_handler.php';

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

    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;
    
    // Start transaction for data integrity
    $conn->begin_transaction();
    
    try {
        // Create purchase return record
        $conn->query("INSERT INTO purchase_returns (purchase_id, vendor_id, total_amount, remarks, customer_remarks, store_id) VALUES ($purchase_id, $vendor_id, 0, '', '" . $conn->real_escape_string($customer_remarks) . "', $store_id)");
        $purchase_return_id = $conn->insert_id;

        // Process return items
        $items = $conn->query("SELECT * FROM purchase_items WHERE purchase_id = $purchase_id");
        $has_valid_returns = false;
        
        while ($item = $items->fetch_assoc()) {
            $item_id = $item['id'];
            $qty = isset($return_qtys[$item_id]) ? intval($return_qtys[$item_id]) : 0;
            
            // Validate return quantity
            if ($qty > 0 && $qty <= $item['quantity']) {
                $has_valid_returns = true;
                $unit_cost = $item['unit_cost'];
                $total_cost = $qty * $unit_cost;
                $total_return += $total_cost;
                
                // Insert return item
                $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, store_id) VALUES ({$item['item_id']}, 'out', 'purchase_return', $purchase_return_id, $qty, $store_id)");
            } elseif ($qty > $item['quantity']) {
                throw new Exception("Return quantity for item '{$item['item_name']}' cannot exceed purchased quantity ({$item['quantity']})");
            }
        }
        
        // Check if any valid returns were processed
        if (!$has_valid_returns) {
            throw new Exception("No valid return quantities specified. Please select items to return.");
        }
        
        // Update purchase return with total amount
        $conn->query("UPDATE purchase_returns SET total_amount = $total_return, remarks = 'Purchase Return #$purchase_return_id' WHERE id = $purchase_return_id");
        
        // ✅ CRITICAL FIX: Update supplier outstanding amount
        if ($total_return > 0) {
            // Get current outstanding amount for this purchase
            $outstanding_result = $conn->query("SELECT amount, status FROM sup_outstanding WHERE purchase_id = $purchase_id");
            if ($outstanding_result && $outstanding_row = $outstanding_result->fetch_assoc()) {
                $current_outstanding = floatval($outstanding_row['amount']);
                $current_status = $outstanding_row['status'];
                
                // Handle edge cases
                if ($current_status === 'paid' && $current_outstanding == 0) {
                    // Purchase was already fully paid - create credit balance (negative amount)
                    $conn->query("UPDATE sup_outstanding SET amount = -$total_return, status = 'paid' WHERE purchase_id = $purchase_id");
                } else {
                    // Normal case - reduce outstanding amount
                    $new_outstanding = $current_outstanding - $total_return;
                    
                    if ($new_outstanding > 0) {
                        $conn->query("UPDATE sup_outstanding SET amount = $new_outstanding, status = 'partial' WHERE purchase_id = $purchase_id");
                    } elseif ($new_outstanding == 0) {
                        $conn->query("UPDATE sup_outstanding SET amount = 0, status = 'paid' WHERE purchase_id = $purchase_id");
                    } else {
                        // Return amount exceeds outstanding - create credit (negative amount, status remains 'paid')
                        $conn->query("UPDATE sup_outstanding SET amount = $new_outstanding, status = 'paid' WHERE purchase_id = $purchase_id");
                    }
                }
            } else {
                // No outstanding record found - create one with negative amount (credit)
                $conn->query("INSERT INTO sup_outstanding (purchase_id, vendor_id, amount, status) VALUES ($purchase_id, $vendor_id, -$total_return, 'paid')");
            }
            
            // ✅ Create journal entry for purchase return
            if (function_exists('createPurchaseReturnJournalEntry')) {
                $journal_success = createPurchaseReturnJournalEntry($conn, $purchase_return_id, $total_return, $store_id);
                if (!$journal_success) {
                    error_log("Failed to create journal entry for purchase return #$purchase_return_id");
                }
            }
            
            // ✅ Log financial transaction
            $desc = "Purchase return #$purchase_return_id - Amount: $total_return";
            $log_stmt = $conn->prepare("INSERT INTO account_transactions 
                (sale_id, account_type, account_id, amount, description)
                VALUES (?, 'purchase_return', ?, ?, ?)");
            $log_stmt->bind_param("iids", $purchase_return_id, $vendor_id, $total_return, $desc);
            $log_stmt->execute();
            $log_stmt->close();
        }
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => "Purchase return processed successfully! Return amount: Rs " . number_format($total_return, 2)
        ]);
        exit;
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        error_log("Purchase return error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Error processing return: ' . $e->getMessage()]);
        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>Customer Remarks (optional)</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> 