<?php
require_once '../includes/auth.php';
require_once '../db.php';

$return_id = (int)$_POST['return_id'];
$action = $_POST['action'] ?? 'save';
$reason = trim($_POST['reason'] ?? '');
$round_off = floatval($_POST['round_off'] ?? 0);
$return_qtys = $_POST['return_qty']; // [purchase_item_id => qty]

$conn->begin_transaction();

try {

    // Load return header
    $pr = $conn->query("SELECT * FROM purchase_returns WHERE id = $return_id AND company_id = $cid")->fetch_assoc();
    if (!$pr) throw new Exception("Return not found");
    if ($pr['status'] === 'final') throw new Exception("Return already finalized");

    $total_taxable = 0;
    $total_gst = 0;

    foreach ($return_qtys as $purchase_item_id => $qty) {

        $qty = (float)$qty;

        // Get purchase batch
        $pi = $conn->query("
            SELECT * FROM purchase_items 
            WHERE id = $purchase_item_id
        ")->fetch_assoc();

        if (!$pi) continue;

        // Check if already exists in return
        $pri = $conn->query("
            SELECT * FROM purchase_return_items 
            WHERE purchase_return_id = $return_id 
            AND purchase_item_id = $purchase_item_id
        ")->fetch_assoc();

        $maxQty = $pi['available_qty'] + ($pri['return_qty'] ?? 0);
        if ($qty > $maxQty) {
            throw new Exception("Return qty exceeds available for batch {$pi['batch_no']}");
        }

        if ($qty <= 0) {
            // Remove if exists
            if ($pri) {
                $conn->query("DELETE FROM purchase_return_items WHERE id = {$pri['id']}");
            }
            continue;
        }

        $price = $pi['purchase_price'];
        $gstp  = $pi['gst_percent'];

        $taxable = $qty * $price;
        $gstAmt  = $taxable * $gstp / 100;
        $total   = $taxable + $gstAmt;

        if ($pri) {
            // Update existing return row
            $stmt = $conn->prepare("
                UPDATE purchase_return_items
                SET return_qty=?, taxable_amount=?, gst_amount=?, total_amount=?
                WHERE id=?
            ");
            $stmt->bind_param("ddddi", $qty, $taxable, $gstAmt, $total, $pri['id']);
            $stmt->execute();
        } else {
            // Insert new return row
            $stmt = $conn->prepare("
                INSERT INTO purchase_return_items
                (purchase_return_id, purchase_item_id, product_id, batch_no,
                 return_qty, purchase_price, gst_percent,
                 taxable_amount, gst_amount, total_amount)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param(
                "iiisdddddd",
                $return_id,
                $purchase_item_id,
                $pi['product_id'],
                $pi['batch_no'],
                $qty,
                $price,
                $gstp,
                $taxable,
                $gstAmt,
                $total
            );
            $stmt->execute();
        }

        $total_taxable += $taxable;
        $total_gst += $gstAmt;
    }

    $net_total = round($total_taxable + $total_gst + $round_off, 2);

    // If final, reduce stock
    if ($action === 'final') {
        $items = $conn->query("
            SELECT * FROM purchase_return_items 
            WHERE purchase_return_id = $return_id
        ");

        while ($r = $items->fetch_assoc()) {
            $conn->query("
                UPDATE purchase_items 
                SET available_qty = available_qty - {$r['return_qty']}
                WHERE id = {$r['purchase_item_id']}
            ");
        }
        $status = 'final';
    } else {
        $status = 'draft';
    }

    // Update return header
    $stmt = $conn->prepare("
        UPDATE purchase_returns
        SET reason=?, total_amount=?, gst_amount=?, net_amount=?, round_off=?, status=?
        WHERE id=?
    ");
    $stmt->bind_param(
        "sddddsi",
        $reason,
        $total_taxable,
        $total_gst,
        $net_total,
        $round_off,
        $status,
        $return_id
    );
    $stmt->execute();

    $conn->commit();

    if ($status === 'final') {
        header("Location: view.php?id=" . $return_id);
    } else {
        header("Location: edit.php?id=" . $return_id);
    }
    exit;

} catch (Exception $e) {
    $conn->rollback();
    die("Update failed: " . $e->getMessage());
}
