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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request");
}

$purchase_order_id = (int)$_POST['purchase_order_id'];
$vendor_id = (int)$_POST['vendor_id'];
$return_no = $_POST['return_no'];
$return_date = date('Y-m-d');
$action = $_POST['action'] ?? 'save'; // save | final
$round_off = floatval($_POST['round_off'] ?? 0);

$return_qtys = $_POST['return_qty']; // [purchase_item_id => qty]

$conn->begin_transaction();

try {

    // 1) Insert return header
    $stmt = $conn->prepare("
        INSERT INTO purchase_returns
        (return_no, purchase_order_id, vendor_id, return_date, status, company_id)
        VALUES (?, ?, ?, ?, 'draft', ?)
    ");
    $stmt->bind_param("siisi", $return_no, $purchase_order_id, $vendor_id, $return_date, $cid);
    $stmt->execute();

    $purchase_return_id = $stmt->insert_id;

    $total_taxable = 0;
    $total_gst = 0;

    // 2) Loop through return quantities
    foreach ($return_qtys as $purchase_item_id => $qty) {

        $qty = (float)$qty;
        if ($qty <= 0) continue;

        // Fetch purchase item (batch)
        $pi = $conn->query("
            SELECT pi.*, p.id AS product_id
            FROM purchase_items pi
            JOIN products p ON p.id = pi.product_id
            WHERE pi.id = $purchase_item_id
        ")->fetch_assoc();

        if (!$pi) continue;

        if ($qty > $pi['available_qty']) {
            throw new Exception("Return quantity exceeds available stock for batch {$pi['batch_no']}");
        }

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

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

        // 3) Insert return item
        $stmtItem = $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmtItem->bind_param(
            "iiisdddddd",
            $purchase_return_id,
            $purchase_item_id,
            $pi['product_id'],
            $pi['batch_no'],
            $qty,
            $price,
            $gstp,
            $taxable,
            $gstAmt,
            $total
        );
        $stmtItem->execute();

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

        // 4) Reduce stock if finalized
        if ($action === 'final') {

			$newAvail = $pi['available_qty'] - $qty;

					$conn->query("
						UPDATE purchase_items
						SET available_qty = $newAvail
						WHERE id = $purchase_item_id
					");

					// Insert stock OUT movement (purchase return means stock going out)
					$stmtMove = $conn->prepare("
						INSERT INTO stock_movements 
						(product_id, purchase_item_id, type, quantity, reference_id, reference_type)
						VALUES (?, ?, 'OUT', ?, ?, 'purchase_return')
					");
					$stmtMove->bind_param("iiii", $pi['product_id'], $purchase_item_id, $qty, $purchase_return_id);
					$stmtMove->execute();
				}
    }

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

    // 5) Update totals & status
    if ($action === 'final') {
        $status = 'final';
    } else {
        $status = 'draft';
    }

    $stmtUpd = $conn->prepare("
        UPDATE purchase_returns
        SET total_amount = ?, gst_amount = ?, net_amount = ?, round_off = ?, status = ?
        WHERE id = ?
    ");
    $stmtUpd->bind_param(
        "ddddsi",
        $total_taxable,
        $total_gst,
        $net_total,
        $round_off,
        $status,
        $purchase_return_id
    );
    $stmtUpd->execute();

    $conn->commit();

    header("Location: index.php");
    exit;

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