<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'db.php';

$invoice_id = (int)($_POST['invoice_id'] ?? 0);

if(!$invoice_id){
    die("Invalid Invoice ID");
}

/* ✅ CHECK INVOICE EXISTS */
$check = mysqli_query($con,"SELECT * FROM invoices WHERE id='$invoice_id'");
if(mysqli_num_rows($check) == 0){
    die("Invoice not found in DB");
}

/* ================= KEEP OLD INVOICE NO ================= */
$resInv = mysqli_fetch_assoc($check);
$invoice_no = $resInv['invoice_no'];

/* ================= CLIENT ================= */
$client_name = mysqli_real_escape_string($con, $_POST['client_name']);
$phone = mysqli_real_escape_string($con, $_POST['phone']);
$pan_no = mysqli_real_escape_string($con, $_POST['pan_no']);
$gst_no = mysqli_real_escape_string($con, $_POST['gst_no']);
$address = mysqli_real_escape_string($con, $_POST['address']);
$state = mysqli_real_escape_string($con, $_POST['state']);
$city = mysqli_real_escape_string($con, $_POST['city']);
$pincode = mysqli_real_escape_string($con, $_POST['pincode']);

/* ================= START TRANSACTION ================= */
mysqli_begin_transaction($con);

/* ================= RESET ITEMS ================= */
mysqli_query($con, "DELETE FROM invoice_items WHERE invoice_id='$invoice_id'");

$item_subtotal = 0;

for($i=0; $i < count($_POST['desc']); $i++){

    if(!isset($_POST['desc'][$i]) || trim($_POST['desc'][$i]) == '') continue;

    $desc  = mysqli_real_escape_string($con, $_POST['desc'][$i]);
    $gross = (float)($_POST['gross'][$i] ?? 0);
    $net   = (float)($_POST['net'][$i] ?? 0);
    $rate  = (float)($_POST['rate'][$i] ?? 0);
    $stone = (float)($_POST['stone'][$i] ?? 0);
    $hm    = (float)($_POST['hm_value'][$i] ?? 0);
    $hsn   = mysqli_real_escape_string($con, $_POST['hsn'][$i] ?? '');

    $metal = $net * $rate;
    $making = (float)($_POST['making_amount'][$i] ?? 0);

    /* ❌ HM remove from total */
    $total = $metal + $making + $stone;

    $item_subtotal += $total;

    $res = mysqli_query($con,"
        INSERT INTO invoice_items
        (invoice_id, description, gross_weight, net_weight, rate, making, stone_value, hm_type, hm_value, total, hsn)
        VALUES
        ('$invoice_id','$desc','$gross','$net','$rate','$making','$stone','percent','$hm','$total','$hsn')
    ");

    if(!$res){
        mysqli_rollback($con);
        die(mysqli_error($con));
    }
}

/* ================= OTHER ================= */
mysqli_query($con, "DELETE FROM invoice_other_charges WHERE invoice_id='$invoice_id'");

$other_total = 0;

if(isset($_POST['other_name'])){
    for($i=0; $i<count($_POST['other_name']); $i++){

        $name = trim($_POST['other_name'][$i]);
        $amount = trim($_POST['other_amount'][$i]);

        if($name != '' && $amount != ''){
            
            $name = mysqli_real_escape_string($con, $name);
            $amount = (float)$amount;

            // 🔥 ADD THIS LINE (IMPORTANT)
            $other_total += $amount;

            mysqli_query($con,"
            INSERT INTO invoice_other_charges(invoice_id, charge_name, amount)
            VALUES('$invoice_id', '$name', '$amount')
            ");
        }
    }
}
/* ================= DISCOUNT ================= */
$discount_type = $_POST['discount_type'] ?? 'value';
$discount_value = (float)($_POST['discount_value'] ?? 0);

$discount_amount = ($discount_type == 'percent') 
    ? $item_subtotal * $discount_value / 100 
    : $discount_value;

$item_after_discount = max(0, $item_subtotal - $discount_amount);

/* ================= GST ================= */
$cgst = 0;
$sgst = 0;
$igst = 0;

if(strtolower(trim($state)) == 'west bengal'){

    $cgst = round($item_subtotal * 0.015, 2);
$sgst = round($item_subtotal * 0.015, 2);

$final_amount = $item_subtotal + $cgst + $sgst + $other_total - $discount_amount;

}else{

    $igst = round($item_subtotal * 0.03, 2);
 
    $cgst = $igst;   
    $sgst = 0;

    $final_amount = $item_subtotal + $igst + $other_total - $discount_amount;
}

/* ================= PAYMENTS ================= */
mysqli_query($con, "DELETE FROM invoice_payments WHERE invoice_id='$invoice_id'");

$paid_amount = 0;

if(isset($_POST['pay_fixed'])){
    foreach($_POST['pay_fixed'] as $type => $amt){
        $amt = (float)$amt;

        if($amt > 0){
            $paid_amount += $amt;

            mysqli_query($con,"
                INSERT INTO invoice_payments(invoice_id, payment_type, amount)
                VALUES('$invoice_id','$type','$amt')
            ");
        }
    }
}

$dues_amount = max(0, $final_amount - $paid_amount);

/* ================= UPDATE ================= */
mysqli_query($con,"
UPDATE invoices SET
client_name='$client_name',
phone='$phone',
pan_no='$pan_no',
gst_no='$gst_no',
address='$address',
state='$state',
city='$city',
pincode='$pincode',
subtotal='$item_after_discount',
discount_type='$discount_type',
discount_value='$discount_value',
cgst='$cgst',
sgst='$sgst', 
final_amount='$final_amount',
paid_amount='$paid_amount',
dues_amount='$dues_amount'
WHERE id='$invoice_id'
");

/* ================= COMMIT ================= */
mysqli_commit($con);

header("Location: invoice_view.php?id=$invoice_id");
exit;
?>