<?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');

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

if ($master_id <= 0) die('Invalid master ID');

// Verify master exists and is final
$master = $conn->query("SELECT * FROM master_invoices WHERE id = $master_id AND status = 'final'")->fetch_assoc();
if (!$master) die('Master invoice not found or not finalized.');

$status = ($action === 'final') ? 'final' : 'draft';

// Group non-zero return qtys by sales_invoice_id
$grouped = []; // [sales_invoice_id => [sales_item_id => qty]]
foreach ($return_qtys as $sales_item_id => $qty) {
    $qty = floatval($qty);
    if ($qty <= 0) continue;
    $inv_id = (int)($item_invoice[$sales_item_id] ?? 0);
    if ($inv_id <= 0) continue;
    $grouped[$inv_id][(int)$sales_item_id] = $qty;
}

if (empty($grouped)) {
    header("Location: ../master_sales/view.php?id=$master_id&msg=no_items");
    exit;
}

$conn->begin_transaction();

try {
    $lastReturnId = null;

    foreach ($grouped as $sales_invoice_id => $items) {
        // Load the company invoice
        $inv = $conn->query("
            SELECT * FROM sales_invoices WHERE id = $sales_invoice_id AND status = 'final'
        ")->fetch_assoc();
        if (!$inv) throw new Exception("Invoice $sales_invoice_id not found or not final.");

        $client_id  = $inv['client_id'];
        $company_id = $inv['company_id'];

        // Generate credit note number
        $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 (?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("siissi", $return_no, $sales_invoice_id, $client_id, $return_date, $status, $company_id);
        $stmt->execute();
        $sales_return_id = $stmt->insert_id;
        $lastReturnId = $sales_return_id;

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

        foreach ($items as $sales_item_id => $qty) {
            $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",
                $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("iidd", $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();

    header("Location: ../master_sales/view.php?id=$master_id");
    exit;

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