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

requirePermission('master_sales', 'edit', BASE_URL . '/dashboard.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') die('Invalid Request');

$return_id   = (int)$_POST['sales_return_id'];
$return_date = $_POST['return_date'];
$action      = $_POST['action']; // draft | final
$return_qtys = $_POST['return_qty'] ?? [];

// Verify return belongs to a master invoice and is still draft
$sr = $conn->query("
    SELECT sr.*
    FROM sales_returns sr
    JOIN sales_invoices si ON si.id = sr.sales_invoice_id
    WHERE sr.id = $return_id
      AND si.master_invoice_id IS NOT NULL
      AND sr.status = 'draft'
")->fetch_assoc();
if (!$sr) die('Return not found or cannot be edited.');

$conn->begin_transaction();

try {
    $conn->query("DELETE FROM sales_return_items WHERE sales_return_id = $return_id");

    $total_taxable = 0;
    $total_gst     = 0;
    $total_amount  = 0;

    foreach ($return_qtys as $sales_item_id => $qty) {
        $qty = floatval($qty);
        if ($qty <= 0) continue;

        $si = $conn->query("
            SELECT si.*, pi.id AS purchase_item_id
            FROM sales_items si
            JOIN purchase_items pi ON pi.id = si.purchase_item_id
            WHERE si.id = $sales_item_id
        ")->fetch_assoc();
        if (!$si) throw new Exception("Invalid sales item $sales_item_id");

        $rate_incl  = floatval($si['selling_price_incl']);
        $gstp       = floatval($si['gst_percent']);
        $line_total = $qty * $rate_incl;
        $taxable    = $line_total / (1 + $gstp / 100);
        $gst_amt    = $line_total - $taxable;

        $stmtItem = $conn->prepare("
            INSERT INTO sales_return_items
            (sales_return_id, sales_item_id, product_id, batch_no,
             sold_qty, return_qty, rate_incl_gst, gst_percent,
             taxable_amount, gst_amount, total_amount)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmtItem->bind_param("iiisddddddd",
            $return_id, $sales_item_id, $si['product_id'], $si['batch_no'],
            $si['sold_qty'], $qty, $rate_incl, $gstp, $taxable, $gst_amt, $line_total
        );
        $stmtItem->execute();

        if ($action === 'final') {
            $purchase_item_id = (int)$si['purchase_item_id'];
            $conn->query("UPDATE purchase_items SET available_qty = available_qty + $qty WHERE id = $purchase_item_id");

            $stmtMov = $conn->prepare("
                INSERT INTO stock_movements
                (product_id, purchase_item_id, type, quantity, reference_id, reference_type)
                VALUES (?, ?, 'RETURN', ?, ?, 'sales_return')
            ");
            $stmtMov->bind_param("iidd", $si['product_id'], $purchase_item_id, $qty, $return_id);
            $stmtMov->execute();
        }

        $total_taxable += $taxable;
        $total_gst     += $gst_amt;
        $total_amount  += $line_total;
    }

    $status = ($action === 'final') ? 'final' : 'draft';
    $stmtUpd = $conn->prepare("
        UPDATE sales_returns
        SET return_date=?, total_taxable=?, total_gst=?, total_amount=?, status=?
        WHERE id=?
    ");
    $stmtUpd->bind_param("sdddsi", $return_date, $total_taxable, $total_gst, $total_amount, $status, $return_id);
    $stmtUpd->execute();

    $conn->commit();

    header("Location: view.php?id=$return_id");
    exit;

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