<?php
include 'db.php';

/* ---------- COMPANY ---------- */
$company_name = "R.P. JEWELLERS & SONS";

/* ---------- INVOICE NUMBER ---------- */
$res = mysqli_query($con, "
    SELECT invoice_no 
    FROM invoices 
    ORDER BY id DESC 
    LIMIT 1
");

$row = mysqli_fetch_assoc($res);

$lastNumber = 0;

if($row && isset($row['invoice_no'])){
    $parts = explode('/', $row['invoice_no']);
    $lastNumber = (int) end($parts);
}

$nextNumber = $lastNumber + 1;

$invoice_no = "RP/".date('y')."/".date('y', strtotime('+1 year'))."/".str_pad($nextNumber, 2, '0', STR_PAD_LEFT);

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

/* ---------- ITEMS ---------- */
$subtotal = 0;
$items = [];

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);
    $makingType = 'percent';

    $total  = $metal + $making + $stone;

    $subtotal += $total;

    $items[] = [
        'desc' => $desc,
        'gross' => $gross,
        'net' => $net,
        'rate' => $rate,
        'making' => $making,
        'stone' => $stone,
        'hm' => $hm,
        'makingType' => $makingType,
        'total' => $total,
        'hsn' => $hsn
    ];
}

/* ---------- DISCOUNT ---------- */
$discount_type = $_POST['discount_type'] ?? 'value';
$discount_value = (float)($_POST['discount_value'] ?? 0);

$discount_amount = 0;

if($discount_type == 'percent'){
    $discount_amount = $subtotal * $discount_value / 100;
}else{
    $discount_amount = $discount_value;
}

$subtotal_after_discount = $subtotal - $discount_amount;
if($subtotal_after_discount < 0) $subtotal_after_discount = 0;

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

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

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

$final_amount = round($subtotal + $cgst + $sgst - $discount_amount, 2);

}else{
 
    $igst = round($subtotal_after_discount * 0.03, 2);
 
    $cgst = $igst;    
    $sgst = 0;

    $final_amount = round($subtotal_after_discount + $igst, 2);
}

/* ---------- INSERT INVOICE ---------- */
mysqli_query($con, "
INSERT INTO invoices 
(invoice_no, invoice_date, company_name, client_name, phone, pan_no, gst_no, address, state, city, pincode, subtotal, discount_type, discount_value, cgst, sgst, final_amount)
VALUES
('$invoice_no', CURDATE(), '$company_name', '$client_name', '$phone', '$pan_no', '$gst_no', '$address', '$state', '$city', '$pincode', '$subtotal_after_discount', '$discount_type', '$discount_value', '$cgst', '$sgst', '$final_amount')
");

$invoice_id = mysqli_insert_id($con);

/* ---------- INSERT ITEMS ---------- */
foreach($items as $it){
    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','{$it['desc']}','{$it['gross']}','{$it['net']}','{$it['rate']}','{$it['making']}','{$it['stone']}','{$it['makingType']}','{$it['hm']}','{$it['total']}','{$it['hsn']}')
    ");
}

/* ---------- OTHER CHARGES ---------- */
if(isset($_POST['other_name'])){
    for($i=0; $i<count($_POST['other_name']); $i++){

        $name = mysqli_real_escape_string($con, $_POST['other_name'][$i]);
        $amount = (float)$_POST['other_amount'][$i];

        if(isset($amount) && $amount != ''){
            mysqli_query($con,"
            INSERT INTO invoice_other_charges(invoice_id, charge_name, amount)
            VALUES('$invoice_id', '$name', '$amount')
            ");
        }
    }
}
/* ---------- PAYMENT SAVE ---------- */
$paid_total = 0;

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

        $amount = (float)$amount;

        if($amount > 0){

            $paid_total += $amount;

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

/* UPDATE INVOICE */
$dues = $final_amount - $paid_total;

mysqli_query($con,"
UPDATE invoices 
SET paid_amount='$paid_total', dues_amount='$dues'
WHERE id='$invoice_id'
");
header("Location: invoice_view.php?id=$invoice_id");
exit;
?>