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

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

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

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

// Load invoice — no company_id restriction (master can access all)
$inv = $conn->query("SELECT * FROM sales_invoices WHERE id = $sales_invoice_id AND status = 'final'")->fetch_assoc();
if (!$inv) die('Invoice not found or not finalized.');

$client_id  = $inv['client_id'];
$company_id = $inv['company_id']; // Return is scoped to invoice's company

$conn->begin_transaction();

try {
    $seqRes = $conn->query("SELECT COUNT(*) AS cnt FROM sales_returns WHERE sales_invoice_id = $sales_invoice_id")->fetch_assoc();
    $seq = $seqRes['cnt'] + 1;
    $return_no = "CN-" . $inv['invoice_no'] . "-" . $seq;

    $stmt = $conn->prepare("
        INSERT INTO sales_returns
        (return_no, sales_invoice_id, client_id, return_date, status, company_id)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $status = ($action === 'final') ? 'final' : 'draft';
    $stmt->bind_param("siissi", $return_no, $sales_invoice_id, $client_id, $return_date, $status, $company_id);
    $stmt->execute();
    $sales_return_id = $stmt->insert_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");

        $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",
            $sales_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("iiid", $si['product_id'], $purchase_item_id, $qty, $sales_return_id);
            $stmtMov->execute();
        }

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

    $stmtUpd = $conn->prepare("UPDATE sales_returns SET total_taxable=?, total_gst=?, total_amount=? WHERE id=?");
    $stmtUpd->bind_param("dddi", $total_taxable, $total_gst, $total_amount, $sales_return_id);
    $stmtUpd->execute();

    $conn->commit();

    // Redirect to the standard sales_return view (same data, no need to duplicate)
    header("Location: ../sales_return/view.php?id=$sales_return_id");
    exit;

} catch (Exception $e) {
    $conn->rollback();
    die("Sales Return Failed: " . $e->getMessage());
}
