<?php
include 'db.php';

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

/* ---------- FINANCIAL YEAR ---------- */
$currentYear  = date('Y');
$currentMonth = date('n');

if ($currentMonth >= 4) {
    $startYear = $currentYear;
    $endYear   = $currentYear + 1;
} else {
    $startYear = $currentYear - 1;
    $endYear   = $currentYear;
}
 
$fyStart = substr($startYear, -2);
$fyEnd   = substr($endYear, -2);

/* ---------- INVOICE NUMBER ---------- */
$usedNumbers = [];

$res = mysqli_query($con,"
SELECT invoice_no FROM invoices 
WHERE invoice_no LIKE 'RP/$fyStart/$fyEnd/%'
");

while ($row = mysqli_fetch_assoc($res)) {
    $parts = explode('/', $row['invoice_no']);
    $usedNumbers[] = (int) end($parts);
}

$nextNumber = 1;
while (in_array($nextNumber, $usedNumbers)) {
    $nextNumber++;
}

$invoice_no = "RP/$fyStart/$fyEnd/" . str_pad($nextNumber, 2, '0', STR_PAD_LEFT);

/* ---------- CLIENT DETAILS ---------- */
$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++){

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

    $makingType = $_POST['making_type'][$i] ?? '';
    $makingRaw  = (float)($_POST['making'][$i] ?? 0);

    $metal  = $net * $rate;
    $making = ($makingType === 'percent') ? ($metal * $makingRaw / 100) : $makingRaw;
    $total  = $metal + $making + $stone + $hm;

    $subtotal += $total;

    $items[] = compact('desc','gross','net','rate','making','stone','hm','makingType','total','hsn');
}
 
/* ---------- OTHER CHARGES ---------- */
if(isset($_POST['other_name'])){
    for($i=0; $i<count($_POST['other_name']); $i++){

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

        if($other_amount > 0){
            mysqli_query($con,"
            INSERT INTO invoice_other_charges
            (invoice_id, charge_name, amount)
            VALUES('$invoice_id', '$other_name', '$other_amount')
            ");
        }
    }
}
$subtotal += $other_amount;

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

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

$subtotal -= $discount_amount;

if($subtotal < 0) $subtotal = 0;

/* ---------- GST ---------- */
$subtotal = round($subtotal, 2);
$cgst = round($subtotal * 0.015, 2);
$sgst = round($subtotal * 0.015, 2);
$final_amount = round($subtotal + $cgst + $sgst, 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', '$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']}')
    ");
}

/* ---------- INSERT OTHER CHARGES ---------- */
if($other_amount > 0){
    mysqli_query($con,"
    INSERT INTO invoice_other_charges(invoice_id, charge_name, amount)
    VALUES('$invoice_id', '$other_name', '$other_amount')
    ");
}

/* ---------- PAYMENTS ---------- */
$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','".mysqli_real_escape_string($con,$type)."','$amt')
            ");
        }
    }
}

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

/* ---------- UPDATE PAYMENT STATUS ---------- */
mysqli_query($con,"
UPDATE invoices SET
paid_amount='$paid_amount',
dues_amount='$dues_amount'
WHERE id='$invoice_id'
");

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