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

header('Content-Type: application/json');

$id              = (int)($_POST['id'] ?? 0);
$received_amount = (float)($_POST['received_amount'] ?? 0);
$payment_mode    = trim($_POST['payment_mode'] ?? 'Cash');
$new_disc_type   = trim($_POST['overall_discount_type'] ?? '');
$new_disc_val    = (float)($_POST['overall_discount_value'] ?? 0);

if ($id <= 0) { echo json_encode(['status'=>'error','msg'=>'Invalid invoice.']); exit; }

$isAdminLike = in_array($_SESSION['user_role'] ?? '', ['admin', 'master_staff']);
$cidFilter   = $isAdminLike ? '' : "AND company_id=$cid";

$inv = $conn->query("
    SELECT gross_total, round_off, total_taxable, total_gst,
           overall_discount_type, overall_discount_value,
           status, master_invoice_id
    FROM sales_invoices WHERE id=$id $cidFilter LIMIT 1
")->fetch_assoc();
if (!$inv) { echo json_encode(['status'=>'error','msg'=>'Invoice not found.']); exit; }

$gross     = (float)$inv['gross_total'];
$round_off = (float)$inv['round_off'];

// Reverse current discount to get undiscounted taxable/gst
$old_type = $inv['overall_discount_type'];
$old_val  = (float)$inv['overall_discount_value'];
$old_net  = $gross;
if ($old_type === 'percent') $old_net -= $gross * $old_val / 100;
elseif ($old_type === 'amount') $old_net -= $old_val;
$old_net   = max(0, $old_net);
$old_ratio = ($gross > 0 && $old_net > 0) ? ($old_net / $gross) : 1;

$orig_taxable = $old_ratio > 0 ? ((float)$inv['total_taxable'] / $old_ratio) : (float)$inv['total_taxable'];
$orig_gst     = $old_ratio > 0 ? ((float)$inv['total_gst']     / $old_ratio) : (float)$inv['total_gst'];

// Apply new discount
$new_net = $gross;
if ($new_disc_type === 'percent') $new_net -= $gross * $new_disc_val / 100;
elseif ($new_disc_type === 'amount') $new_net -= $new_disc_val;
$new_net = max(0, $new_net);

$new_ratio   = ($gross > 0) ? ($new_net / $gross) : 1;
$new_taxable = round($orig_taxable * $new_ratio, 2);
$new_gst     = round($orig_gst     * $new_ratio, 2);
$new_net     = round($new_net + $round_off, 2);
$balance     = round(max(0, $new_net - $received_amount), 2);

$was_draft    = ($inv['status'] === 'draft');
$cidUpdate    = $isAdminLike ? '' : "AND company_id=$cid";

$stmt = $conn->prepare("
    UPDATE sales_invoices
    SET overall_discount_type=?, overall_discount_value=?,
        total_taxable=?, total_gst=?, net_total=?,
        received_amount=?, balance_amount=?, payment_mode=?, status='final'
    WHERE id=? $cidUpdate
");
$stmt->bind_param("sddddddsi",
    $new_disc_type, $new_disc_val,
    $new_taxable, $new_gst, $new_net,
    $received_amount, $balance, $payment_mode,
    $id
);
$stmt->execute();

// Finalize master invoice if this sub-invoice belongs to one
$master_finalized = false;
$master_id = (int)($inv['master_invoice_id'] ?? 0);
if ($master_id > 0) {
    $conn->query("UPDATE master_invoices SET status='final' WHERE id=$master_id");
    $master_finalized = true;
}

echo json_encode([
    'status'           => 'ok',
    'net_total'        => $new_net,
    'total_gst'        => $new_gst,
    'discount_type'    => $new_disc_type,
    'discount_value'   => $new_disc_val,
    'received_amount'  => $received_amount,
    'balance_amount'   => $balance,
    'was_draft'        => $was_draft,
    'master_finalized' => $master_finalized,
    'master_id'        => $master_id,
]);
