<?php
include('../includes/config.php');
session_start();

$originalTxnId = $_POST['original_txn_id'];
$returnIds = $_POST['return_ids'] ?? [];

if (empty($returnIds)) {
    die("No items selected.");
}

// Create return transaction
$conn->query("INSERT INTO sales_transactions (store_id, sold_by, customer_id, receipt_number, transaction_type, status, total_amount, payment_method)
    SELECT store_id, sold_by, customer_id, CONCAT(receipt_number, '-R'), 'return', 'completed', 0, payment_method 
    FROM sales_transactions WHERE id = $originalTxnId");

$returnTxnId = $conn->insert_id;

$totalReturnAmount = 0;

foreach ($returnIds as $itemId) {
    $qty = (int)$_POST['return_qty'][$itemId];

    $item = $conn->query("SELECT * FROM sales_items WHERE id = $itemId")->fetch_assoc();
    $returnPrice = $qty * $item['unit_price'];
    $totalReturnAmount += $returnPrice;

    // Negative entry
    $stmt = $conn->prepare("INSERT INTO sales_items (transaction_id, product_id, quantity, unit_price, discount, vat_rate, total_price)
                            VALUES (?, ?, ?, ?, ?, ?, ?)");
    $negativeQty = -$qty;
    $total = -($returnPrice);
    $stmt->bind_param("iiidddd", $returnTxnId, $item['product_id'], $negativeQty, $item['unit_price'], $item['discount'], $item['vat_rate'], $total);
    $stmt->execute();

    // Optional: restock inventory
    $conn->query("UPDATE inventory SET quantity = quantity + $qty WHERE product_id = {$item['product_id']}");
}

// Update total amount of the return transaction
$conn->query("UPDATE sales_transactions SET total_amount = $totalReturnAmount WHERE id = $returnTxnId");

header("Location: ../pages/sales/returns.php?success=1");
