<?php
// create_bill.php
session_start();
$consignee_name    = trim($_POST['consignee_name'] ?? $_GET['consignee_name'] ?? '');
$consignee_address = trim($_POST['consignee_address'] ?? $_GET['consignee_address'] ?? '');
$consignee_contact = trim($_POST['consignee_contact'] ?? $_GET['consignee_contact'] ?? '');

$buyer_name        = trim($_POST['buyer_name'] ?? $_GET['buyer_name'] ?? '');
$buyer_address     = trim($_POST['buyer_address'] ?? $_GET['buyer_address'] ?? '');
$buyer_contact     = trim($_POST['buyer_contact'] ?? $_GET['buyer_contact'] ?? '');

$consignee_phone = trim($_POST['consignee_phone'] ?? $_GET['consignee_phone'] ?? '');
$buyer_phone     = trim($_POST['buyer_phone'] ?? $_GET['buyer_phone'] ?? '');
require_once '../config.php';

// customer discount
$discount_pct = 0;

// admin max discount
$adminMaxDiscount = 0.00;

$res = $conn->query("SELECT discount_percent FROM discount_settings ORDER BY id DESC LIMIT 1");
if ($res && $row = $res->fetch_assoc()) {
    $adminMaxDiscount = (float)$row['discount_percent'];
}

// apply limit
if ($discount_pct > $adminMaxDiscount) {
    $discount_pct = $adminMaxDiscount;
}

if ($discount_pct < 0) {
    $discount_pct = 0;
}

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }
function money($v){ return number_format((float)$v, 2); }

$messages = [];
$errors = [];
$invoice = null;

/* LOAD PRODUCTS FOR DROPDOWN */
$products = [];

$user_id = (int)($_SESSION['user_id'] ?? 0);

$userCountry = '';

/* GET USER COUNTRY */
$getUser = $conn->query("
    SELECT country
    FROM users
    WHERE id = $user_id
    LIMIT 1
");

$userCountry = '';

if ($getUser && $getUser->num_rows > 0) {

    $userRow = $getUser->fetch_assoc();

    $userCountry = trim($userRow['country'] ?? '');
}

/* COUNTRY NAME TO COUNTRY ID */
$userCountryId = 0;

$getCountryId = $conn->query("
    SELECT id
    FROM countries
    WHERE country_name = '$userCountry'
    LIMIT 1
");

if ($getCountryId && $getCountryId->num_rows > 0) {

    $countryRow = $getCountryId->fetch_assoc();

    $userCountryId = (int)$countryRow['id'];
}


/* LOAD PRODUCTS COUNTRY WISE */
if ($userCountry != '') {

    $safeCountry = $conn->real_escape_string($userCountry);

    $res = $conn->query("
        SELECT
            id,
            product_name,
            brand_name,
            IFNULL(qty, 0) AS qty,
            IFNULL(price_per_packet, 0) AS price,
            IFNULL(gst_percent, 0) AS gst_percent,
            IFNULL(tax_percent, 0) AS tax_percent
        FROM products
        WHERE country_id = $userCountryId
        ORDER BY product_name ASC
    ");

} else {

    $res = false;
}

if ($res) {

    while ($r = $res->fetch_assoc()) {

        $products[] = $r;
    }
}



/* ---------- POST: FINALIZE BILL ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    // No customer info here (separate customer_info.php is used)
   
    $items_json     = $_POST['items_json'] ?? '[]';
    $payment_status = isset($_POST['payment_status']) 
    ? strtolower(trim($_POST['payment_status'])) 
    : 'paid';



$allowed_status = ['paid', 'unpaid', 'advance'];
if (!in_array($payment_status, $allowed_status, true)) {
    $payment_status = 'paid';
}
$advance_amount  = (float)($_POST['advance_amount'] ?? 0);
$due_amount      = 0.00;
$due_date        = trim($_POST['due_date'] ?? '');

$allowed_status = ['paid', 'unpaid', 'advance'];
if (!in_array($payment_status, $allowed_status, true)) {
    $payment_status = 'paid';
}

    $created_by     = (int)($_SESSION['user_id'] ?? 0);

   

    $items = json_decode($items_json, true);
    if (!is_array($items) || count($items) === 0) {
        $errors[] = "No items in bill.";
    }
if (!empty($errors)) {
    echo "<div style='background:#fee2e2;color:#991b1b;padding:10px;border-radius:8px'>";
    foreach ($errors as $e) {
        echo $e . "<br>";
    }
    echo "</div>";
    exit;
}
    if (empty($errors)) {
        $subtotal = 0.0;
        $stmtPrice = $conn->prepare("SELECT IFNULL(price_per_packet,0) AS price FROM products WHERE id=?");

     foreach ($items as $it) {

    $pid = (int)($it['id'] ?? 0);
    $qty = (int)($it['qty'] ?? 0);

    if ($pid <= 0 || $qty <= 0) continue;

    // ✅ STOCK CHECK
    $stmtStock = $conn->prepare("SELECT qty FROM products WHERE id=?");
    $stmtStock->bind_param("i", $pid);
    $stmtStock->execute();
    $stockRow = $stmtStock->get_result()->fetch_assoc();

    if (!$stockRow || $stockRow['qty'] <= 0) {
        throw new Exception("Product out of stock");
    }

    if ($qty > $stockRow['qty']) {
        throw new Exception("Quantity exceeds stock");
    }

    // ✅ PRICE FETCH
    $price = (float)($it['price'] ?? 0);

    if ($stmtPrice) {
        $stmtPrice->bind_param("i", $pid);
        $stmtPrice->execute();
        $row = $stmtPrice->get_result()->fetch_assoc();
        $dbPrice = (float)($row['price'] ?? 0);
        if ($dbPrice > 0) {
            $price = $dbPrice;
        }
    }

    // ✅ SUBTOTAL
    $subtotal += ($qty * $price);
}

        if ($stmtPrice) {
            $stmtPrice->close();
        }

        $discount_amount = ($discount_pct / 100.0) * $subtotal;
        $taxable         = $subtotal - $discount_amount;

  $sgst_amount = 0.0;
$cgst_amount = 0.0;

$stmtGST = $conn->prepare("SELECT price_per_packet, gst_percent, tax_percent FROM products WHERE id=?");

foreach ($items as $it) {
    $pid = (int)($it['id'] ?? 0);
    $qty = (int)($it['qty'] ?? 0);

    if ($pid <= 0 || $qty <= 0) continue;

    $price = (float)($it['price'] ?? 0);
    $gst_percent = 0;

    if ($stmtGST) {
        $stmtGST->bind_param("i", $pid);
        $stmtGST->execute();
        $row = $stmtGST->get_result()->fetch_assoc();

        if ($row) {
            if (!empty($row['price_per_packet'])) {
                $price = (float)$row['price_per_packet'];
            }
$gst_percent = 0;

if (!empty($row['gst_percent']) && $row['gst_percent'] > 0) {
    $gst_percent = (float)$row['gst_percent'];
} elseif (!empty($row['tax_percent']) && $row['tax_percent'] > 0) {
    $gst_percent = (float)$row['tax_percent'];
}        }
    }

    $line_total = $price * $qty;

    // split GST into SGST + CGST
    $sgst_amount += ($line_total * ($gst_percent / 2)) / 100;
    $cgst_amount += ($line_total * ($gst_percent / 2)) / 100;
}

if ($stmtGST) {
    $stmtGST->close();
}

$total = $subtotal;

        $total = $taxable + $sgst_amount + $cgst_amount;
        $rounded_total = round($total, 2);

/* ✅ YAHAN DALNA HAI */
$total_amount = $rounded_total;

if ($payment_status === 'paid') {
    $advance_amount = $total_amount;
    $due_amount = 0.00;
} elseif ($payment_status === 'advance') {
    if ($advance_amount <= 0 || $advance_amount >= $total_amount) {
        $errors[] = "Advance amount must be greater than 0 and less than total amount.";
    } else {
        $due_amount = round($total_amount - $advance_amount, 2);
    }
} else {
    $advance_amount = 0.00;
    $due_amount = $total_amount;
}

        $inserted_bill_id = null;

        $conn->begin_transaction();

        try {
            /*
                Customer fields are intentionally left blank here.
                Keep these columns only if your bills table already has them.
            */
         
         $stmt = $conn->prepare("
INSERT INTO bills 
(consignee_name, consignee_address, consignee_contact, consignee_phone, buyer_name, buyer_address, buyer_contact, buyer_phone, subtotal, taxable_amount, sgst_amount, cgst_amount, total_amount, payment_status, paid_amount, advance_amount, due_amount, due_date, created_by, mr_id, created_at)
VALUES 
(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())
");

            if (!$stmt) {
                throw new Exception("Failed to prepare bill insert.");
            }

           
  $paid_amount = 0;

if ($payment_status === 'paid') {
    $paid_amount = $total_amount;
} elseif ($payment_status === 'advance') {
    $paid_amount = $advance_amount;
} else {
    $paid_amount = 0;
}

$mr_id = $_SESSION['user_id'];

$stmt->bind_param(
    "ssssssssdddddsdddsii",
  $consignee_name,
$consignee_address,
$consignee_contact,
$consignee_phone,
$buyer_name,
$buyer_address,
$buyer_contact,
$buyer_phone,
$subtotal,
$taxable,
$sgst_amount,
$cgst_amount,
$rounded_total,
$payment_status,
$paid_amount,
$advance_amount,
$due_amount,
$due_date,
$created_by,
$mr_id
);

            if (!$stmt->execute()) {
    die("Insert Error: " . $stmt->error);
}
            $inserted_bill_id = $stmt->insert_id;
            $stmt->close();

            if ($inserted_bill_id) {
                $stmt_item = $conn->prepare("
                    INSERT INTO bill_items 
                        (bill_id, product_id, product_name, qty, price, total)
                    VALUES 
                        (?,?,?,?,?,?)
                ");

                if (!$stmt_item) {
                    throw new Exception("Failed to prepare bill items insert.");
                }

                foreach ($items as $it) {
                    $pid   = (int)($it['id'] ?? 0);
                    $pname = $it['name'] ?? '';
                    $qty   = (float)($it['qty'] ?? 0);
                    $price = (float)($it['price'] ?? 0);

                    if ($pid <= 0 || $qty <= 0) {
                        continue;
                    }

                    $line_total = $qty * $price;
     $stmt_item->bind_param("iisddd", $inserted_bill_id, $pid, $pname, $qty, $price, $line_total);

if (!$stmt_item->execute()) {
    throw new Exception("Item Insert Error: " . $stmt_item->error);
}

// ✅ STOCK REDUCE (correct place)
$stmt_update = $conn->prepare("
    UPDATE products 
    SET qty = qty - ? 
    WHERE id = ? AND qty >= ?
");
$stmt_update->bind_param("dii", $qty, $pid, $qty);
$stmt_update->execute();

if ($stmt_update->affected_rows == 0) {
    throw new Exception("Stock update failed");
}
 
                }

                $stmt_item->close();
            }


            $conn->commit();
        } catch (Throwable $ex) {
            $conn->rollback();
            $errors[] = "Bill save failed: " . $ex->getMessage();
            $inserted_bill_id = null;
        }

        if ($inserted_bill_id) {

    $redirect_unpaid = false;

    if ($payment_status === 'unpaid') {
        $redirect_unpaid = true;
    }

    $invoice = [
        'id'              => $inserted_bill_id,
        'discount_percent' => $discount_pct,
        'subtotal'        => $subtotal,
        'discount_amount'  => $discount_amount,
        'taxable'         => $taxable,
        'sgst_amount'     => $sgst_amount,
        'cgst_amount'     => $cgst_amount,
        'total'           => $rounded_total,
        'items'           => $items,
        'payment_status'  => $payment_status,
        'created_by'      => $created_by,
        'created_at'      => date('Y-m-d H:i:s'),
        'redirect_unpaid' => $redirect_unpaid // 🔥 important
    ];

    $_SESSION['last_invoice'] = $invoice;
}
    }
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Create Bill</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
body{font-family:Inter,Arial,Helvetica,sans-serif;background:#eef2f7;margin:0;padding:24px;}
.container{margin-left:260px;
  padding:40px 20px 20px;}
.card{background:#fff;padding:16px;border-radius:14px;box-shadow:0 8px 24 rgba(2,6,23,0.08);margin-bottom:14px;}
.section-title{font-weight:700;font-size:16px;margin-bottom:6px;color:#0f1724;display:flex;align-items:center;gap:6px;}
.form-row{display:flex;gap:12px;align-items:center;margin-bottom:12px;flex-wrap:wrap;}
.form-row .col{flex:1;min-width:220px;}
.input{width:100%;height:38px;padding:0px 10px;border-radius:10px;font-size:13px;border:1px solid #e6eef8;background:#fbfdff;box-sizing:border-box;}
.btn{height:38px;display:inline-flex;align-items:center;gap:6px;padding:0 12px;border-radius:10px;font-size:13px;font-weight:600;border:0;cursor:pointer;}
.btn-primary{background:#1f2937;color:#fff;}
.btn-danger{background:#ef4444;color:#fff;}
.btn-yellow{background:#f59e0b;color:#fff;}
.top-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
.items-table{width:100%;border-collapse:collapse;margin-top:12px;}
.items-table thead th{background:#334155;color:#fff;padding:10px;font-size:13px;text-align:left;}
.items-table td{background:#f8fafc;padding:8px; font-size:13px;border-bottom:1px solid #e6eef8;color:#000;}
.items-table td input{width:60px;padding:4px;border-radius:6px;font-size:12px;border:1px solid #e2e8f0;}
.summary{margin-top:16px;margin-left:auto;width:320px;background:#f8fafc;border-radius:14px;padding:14px;border:1px solid #e2e8f0;}
.summary-row{display:flex;justify-content:space-between;align-items:center;padding:12px 10px;border-radius:10px;margin-bottom:8px;background:#fff;border:1px solid #edf2f7;font-size:14px;font-weight:500;}
.summary-row:last-child{margin-bottom:0;}
.summary-row div:first-child{color:#475569;}
.summary-row div:last-child{font-weight:600;color:#0f172a;}
.summary-row.total{background:#f1f5f9;border:2px solid #e2e8f0;font-size:16px;font-weight:700;}
.small-muted{font-size:12px;color:#64748b;}
.right{text-align:right;}
.print-area{padding:18px;background:#fff;border-radius:10px;}
.notice{color:#064e3b;background:#ecfdf5;padding:10px;border-radius:8px;margin-bottom:12px;}
.bad{color:#7f1d1d;background:#fff1f2;padding:10px;border-radius:8px;margin-bottom:12px;}
@media print {
  body * {
    visibility: hidden !important;
  }

  #printInvoice,
  #printInvoice * {
    visibility: visible !important;
  }

  #printInvoice {
    display: block !important;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background: #fff;
  }
}
/* ================= MOBILE RESPONSIVE BILL PAGE ================= */
@media (max-width: 768px){

    body{
        padding:10px;
    }

    .container{
        margin-left:0 !important;
        padding:10px;
    }

    /* HEADER ACTIONS */
    .top-actions{
        flex-direction:column;
        width:100%;
    }

    .top-actions .btn{
        width:100%;
        justify-content:center;
    }

    /* INPUT + ADD */
    .input{
        font-size:14px;
    }

    #btnAdd{
        width:100%;
        justify-content:center;
    }

    /* ❌ TABLE HEADER HIDE */
    .items-table thead{
        display:none;
    }

    /* ✅ CARD STYLE ROW */
    .items-table tbody tr{
        display:block;
        margin-bottom:12px;
        background:#f8fafc;
        border-radius:12px;
        padding:10px;
        border:1px solid #e2e8f0;
    }

    /* EACH FIELD */
    .items-table td{
        display:flex;
        justify-content:space-between;
        align-items:center;
        padding:6px 0;
        border:none;
        font-size:13px;
    }

    /* LABEL */
    .items-table td::before{
        content:attr(data-label);
        font-weight:600;
        color:#64748b;
    }

    /* INPUT FIX */
    .items-table td input{
        width:80px;
    }

    /* BUTTON FIX */
    .items-table td button{
        padding:6px 10px;
    }

    /* SUMMARY FULL WIDTH */
    .summary{
        width:100%;
        margin-top:14px;
    }

}
</style>
</head>
<body>

<?php include 'salesexecutivesidebar.php'; ?>
<?php include '../header.php'; ?>

<!-- Advance Modal -->
<div id="advanceModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:9999;align-items:center;justify-content:center;">
  <div style="width:380px;background:#fff;color:#000 ;border-radius:10px;padding:16px;">
    <h4>Advance Payment</h4>

    <label>Advance Amount (₹)</label>
    <input type="number" id="advance_input" class="input" placeholder="0.00">

    <label style="margin-top:10px;">Due Date</label>
    <input type="date" id="due_input" class="input">

    <div style="margin-top:12px;display:flex;gap:10px;justify-content:flex-end;">
      <button onclick="hideAdvance()" class="btn">Cancel</button>
      <button onclick="submitAdvance()" class="btn btn-primary">Save</button>
    </div>
  </div>
</div>
<div class="container">

<?php foreach ($messages as $m): ?>
  <div class="notice"><?php echo e($m); ?></div>
<?php endforeach; ?>

<?php foreach ($errors as $err): ?>
  <div class="bad"><?php echo e($err); ?></div>
<?php endforeach; ?>

<input type="hidden" name="consignee_name" value="<?php echo e($consignee_name); ?>">
<input type="hidden" name="consignee_address" value="<?php echo e($consignee_address); ?>">
<input type="hidden" name="consignee_contact" value="<?php echo e($consignee_contact); ?>">

<input type="hidden" name="buyer_name" value="<?php echo e($buyer_name); ?>">
<input type="hidden" name="buyer_address" value="<?php echo e($buyer_address); ?>">
<input type="hidden" name="buyer_contact" value="<?php echo e($buyer_contact); ?>">



<form id="billForm" method="post">
    
    <input type="hidden" name="consignee_phone" value="<?php echo e($consignee_phone); ?>">
<input type="hidden" name="buyer_phone" value="<?php echo e($buyer_phone); ?>">

  <input type="hidden" name="action" value="finalize">
  <input type="hidden" name="items_json" id="items_json" value="[]">
  <input type="hidden" name="payment_status" id="payment_status" value="paid">

  <!-- customer -->



  <!-- advance system -->
  <input type="hidden" name="advance_amount" id="advance_amount" value="0">
  <input type="hidden" name="due_date" id="due_date" value="">

  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;">
      <div>
        <div class="section-title"><i class="fa fa-box"></i>Billing</div>
        <div class="small-muted">Type product name or select from list then click Add</div>
      </div>

      <div class="top-actions">
        <button id="btnClearAll" class="btn btn-danger" type="button"><i class="fa fa-trash"></i> Clear ALL</button>
        <button id="btnFinalizePrint" class="btn btn-primary" type="button"><i class="fa fa-print"></i> Finalize & Print</button>
        <button id="btnUnpaidFinalize" class="btn btn-yellow" type="button"><i class="fa fa-clock"></i> Unpaid & Finalize</button>
        <button id="btnAdvanceFinalize" class="btn btn-yellow" type="button"><i class="fa fa-wallet"></i> Advance & Finalize</button>
      </div>
    </div>

    <div style="margin-top:12px; display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
    <div style="position:relative; flex:1; min-width:240px;">
  <input type="text" id="productInput" class="input" placeholder="Type product name">

  <div id="productDropdown" style="
      position:absolute;
      top:100%;
      left:0;
      width:100%;
      background:#fff;
      border:1px solid #e2e8f0;
      border-radius:10px;
      max-height:200px;
      overflow-y:auto;
      display:none;
      z-index:999;
  "></div>
</div>
      <datalist id="productList">
        <?php foreach($products as $p): ?>
          <option value="<?php echo e($p['product_name']); ?>"><?php echo e($p['brand_name']); ?></option>
        <?php endforeach; ?>
      </datalist>

<input type="hidden" id="discount_percent" value="<?php echo $discount_pct; ?>">
      <button id="btnAdd" class="btn btn-primary" type="button"><i class="fa fa-plus"></i> Add</button>
    </div>

    <div style="margin-top:12px;">
      <table class="items-table" id="itemsTable">
        <thead>
          <tr>
            <th style="width:60px">ID</th>
            <th>Product</th>
            <th>Brand</th>
            <th>Qty</th>
            <th>Price</th>
            <th>Line Total</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody id="itemsBody">
          <tr><td colspan="7" class="small-muted" style="padding:18px;">No items yet.</td></tr>
        </tbody>
      </table>

      <div class="summary">
        <div class="summary-row"><div>SUBTOTAL:</div><div id="subtotal">₹ 0.00</div></div>

        <div class="summary-row total" style="color:#000">
          <strong>TOTAL (With Round Off):</strong>
          <strong id="total_amount">₹ 0.00</strong>

         
        </div>
      </div>
    </div>
  </div>
</form>

<div id="printInvoice" style="display:none;">
  <div class="card print-area" id="invoiceHtml">
    <div style="display:flex;justify-content:space-between">
      <div>
        <h3>Your Company</h3>
        <div class="small-muted">Address line 1</div>
      </div>
      <div class="right">
        <strong>Invoice:</strong> <span id="inv_id"></span><br>
        <small id="inv_date"></small>
      </div>
    </div>

    <hr>

    <div style="display:flex;justify-content:space-between;margin-bottom:12px;">
      <div class="small-muted">
        Payment: <span id="inv_payment"></span>
      </div>
    </div>

    <table style="width:100%;border-collapse:collapse;">
      <thead>
        <tr style="background:#f3f4f6;">
          <th style="padding:8px;border:1px solid #e6eef8;text-align:left">ID</th>
          <th style="padding:8px;border:1px solid #e6eef8;text-align:left">Product</th>
          <th style="padding:8px;border:1px solid #e6eef8;text-align:right">Qty</th>
          <th style="padding:8px;border:1px solid #e6eef8;text-align:right">Price</th>
          <th style="padding:8px;border:1px solid #e6eef8;text-align:right">Total</th>
        </tr>
      </thead>
      <tbody id="inv_items"></tbody>
    </table>

    <div style="margin-top:12px; text-align:right;">
      <div>Subtotal: <span id="inv_sub"></span></div>
      <div>Discount: <span id="inv_disc"></span></div>
      <div>Taxable: <span id="inv_taxable"></span></div>
      <div>SGST: <span id="inv_sgst"></span></div>
      <div>CGST: <span id="inv_cgst"></span></div>
      <h3>Total: <span id="inv_total"></span></h3>
    </div>
  </div>
</div>

</div>

<script>
const PRODUCTS = <?php echo json_encode($products, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>;
let billItems = [];

function e(s){ return String(s || ''); }

function formatMoney(num){
  num = parseFloat(num) || 0;
  return "₹ " + num.toFixed(2);
}

function findProductByName(name){
  name = (name || '').trim().toLowerCase();
  if(!name) return null;

  for(const p of PRODUCTS){
    if((p.product_name || '').toLowerCase() === name) return p;
  }
  for(const p of PRODUCTS){
    if((p.product_name || '').toLowerCase().startsWith(name)) return p;
  }
  for(const p of PRODUCTS){
    if((p.product_name || '').toLowerCase().includes(name)) return p;
  }
  return null;
}

function calculateSummary(){
  let subtotal = 0;
  billItems.forEach(it => {
    const price = parseFloat(it.price) || 0;
    const qty = parseFloat(it.qty) || 0;
    subtotal += price * qty;
  });

 const discPct = <?php echo $discount_pct; ?>;
const discountAmount = (subtotal * discPct) / 100;
const taxable = subtotal - discountAmount;
let sgst = 0;
let cgst = 0;

billItems.forEach(it => {
  const price = parseFloat(it.price) || 0;
  const qty = parseFloat(it.qty) || 0;
  const gst = parseFloat(it.gst_percent || it.tax_percent || 0);

  const lineTotal = price * qty;

  sgst += (lineTotal * (gst / 2)) / 100;
  cgst += (lineTotal * (gst / 2)) / 100;
});

  let total = subtotal;
  total = Math.round(total * 100) / 100;

  document.getElementById('subtotal').textContent = formatMoney(subtotal);

  document.getElementById('total_amount').textContent = formatMoney(total);
}


function renderItems(){
  const tbody = document.getElementById('itemsBody');
  tbody.innerHTML = '';

  if (billItems.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" class="small-muted" style="padding:18px;">No items yet.</td></tr>';
  } else {
    billItems.forEach((it, idx) => {
      const tr = document.createElement('tr');
      tr.innerHTML = `
       <td data-label="ID">${idx + 1}</td>
<td data-label="Product">${e(it.name)}</td>
<td data-label="Brand">${e(it.brand || '')}</td>
<td data-label="Qty">
    <input type="number" value="${it.qty}" oninput="updateQty(${idx}, this.value)">
</td>
<td data-label="Price">${formatMoney(it.price)}</td>
<td data-label="Total">${formatMoney(it.qty * it.price)}</td>
<td data-label="Action">
    <button onclick="deleteItem(${idx})" class="btn btn-danger">
        <i class="fa fa-trash"></i>
    </button>
</td>
      `;
      tbody.appendChild(tr);
    });
  }

  calculateSummary();
}
function deleteItem(idx){
  billItems.splice(idx, 1);
  renderItems();
}

function updateQty(idx, val){
  let maxStock = parseFloat(PRODUCTS.find(p => p.id == billItems[idx].id)?.qty || 0);

  let newQty = parseFloat(val) || 0;

  if (newQty > maxStock) {
    alert("Stock limit exceeded!");
    newQty = maxStock;
  }

  billItems[idx].qty = newQty;

  const row = document.querySelectorAll('#itemsBody tr')[idx];
  if (row) {
    const price = billItems[idx].price || 0;
    const lineTotalEl = row.querySelector('.lineTotal');
    if (lineTotalEl) {
      lineTotalEl.textContent = formatMoney(price * billItems[idx].qty);
    }
  }

  calculateSummary();
}

function finalize(paymentStatus){

  document.getElementById('payment_status').value = paymentStatus; // 1st

  if (billItems.length === 0) {
    alert('Add at least one item');
    return;
  }

  const itemsForServer = billItems.map(it => ({
    id: it.id,
    name: it.name,
    qty: parseFloat(it.qty || 0),
    price: parseFloat(it.price || 0)
  }));

  document.getElementById('items_json').value = JSON.stringify(itemsForServer);

  document.getElementById('payment_status').value = paymentStatus; // 🔥 2nd (FINAL FIX)

  console.log("Sending Status:", paymentStatus);

  document.getElementById('billForm').submit();
}

document.getElementById('btnAdd').addEventListener('click', function(){
  const val = document.getElementById('productInput').value.trim();
  if (!val) {
    alert('Type or select a product');
    return;
  }

 const p = findProductByName(val);
if (!p) {
  alert('Product not found. Please type or select from the list.');
  return;
}

// ✅ STOCK CHECK
if (p.qty <= 0) {
  alert("Out of stock!");
  return;
}

  const existing = billItems.find(it => it.id == p.id);
  if (existing) {
    existing.qty = (parseFloat(existing.qty) || 0) + 1;
  } else {
 billItems.push({
  id: p.id,
  name: p.product_name,
  brand: p.brand_name,
  price: parseFloat(p.price) || 0,
  qty: 1,
  gst_percent: parseFloat(p.gst_percent) || 0,
  tax_percent: parseFloat(p.tax_percent) || 0
});
  }

  document.getElementById('productInput').value = '';
  renderItems();
});

document.getElementById('btnClearAll').addEventListener('click', function(){
  if (!confirm('Clear all items?')) return;
  billItems = [];
  renderItems();
});


document.getElementById('btnFinalizePrint').addEventListener('click', function(){
  finalize('paid');
});

document.getElementById('btnUnpaidFinalize').addEventListener('click', function(){
  finalize('unpaid');
});

document.getElementById('btnAdvanceFinalize').addEventListener('click', showAdvance);
function showAdvance(){
  if (billItems.length === 0) {
    alert('Add items first');
    return;
  }

  document.getElementById('advanceModal').style.display = 'flex';
}

function hideAdvance(){
  document.getElementById('advanceModal').style.display = 'none';
}

function submitAdvance(){
  const adv = parseFloat(document.getElementById('advance_input').value) || 0;
  const due = document.getElementById('due_input').value;

  const totalText = document.getElementById('total_amount').textContent.replace('₹','').trim();
  const total = parseFloat(totalText) || 0;

  if (adv <= 0 || adv >= total) {
    alert("Invalid advance amount");
    return;
  }

  if (!due) {
    alert("Select due date");
    return;
  }

  document.getElementById('advance_amount').value = adv;
  document.getElementById('due_date').value = due;

  hideAdvance();

  finalize('advance');
}
renderItems();


// ✅ PRODUCT DROPDOWN FIX
const input = document.getElementById('productInput');
const dropdown = document.getElementById('productDropdown');

input.addEventListener('input', function () {
  const value = this.value.toLowerCase().trim();
  dropdown.innerHTML = '';

  if (!value) {
    dropdown.style.display = 'none';
    return;
  }

  const filtered = PRODUCTS.filter(p =>
    p.product_name.toLowerCase().includes(value)
  );

  if (filtered.length === 0) {
    dropdown.style.display = 'none';
    return;
  }

  filtered.forEach(p => {
  const item = document.createElement('div');

item.style.padding = '5px 8px';   // 🔥 height chhoti
item.style.cursor = 'pointer';
item.style.borderBottom = '1px solid #eee';
item.style.fontSize = '13px';

item.innerHTML = `
  <strong style="font-size:13px;">${p.product_name}</strong><br>
  <small style="color:#64748b; font-size:11px;">${p.brand_name}</small>
`;

    item.onclick = () => {
      input.value = p.product_name;
      dropdown.style.display = 'none';
    };

    dropdown.appendChild(item);
  });

  dropdown.style.display = 'block';
});

document.addEventListener('click', function (e) {
  if (!input.contains(e.target) && !dropdown.contains(e.target)) {
    dropdown.style.display = 'none';
  }
});
// ✅ CLICK PE FULL LIST SHOW
input.addEventListener('focus', function () {
  dropdown.innerHTML = '';

  PRODUCTS.forEach(p => {
   const item = document.createElement('div');

item.style.padding = '5px 8px';   // 🔥 height chhoti
item.style.cursor = 'pointer';
item.style.borderBottom = '1px solid #eee';
item.style.fontSize = '13px';

item.innerHTML = `
  <strong style="font-size:13px;">${p.product_name}</strong><br>
  <small style="color:#64748b; font-size:11px;">${p.brand_name}</small>
`;

    item.onclick = () => {
      input.value = p.product_name;
      dropdown.style.display = 'none';
    };

    dropdown.appendChild(item);
  });

  dropdown.style.display = 'block';
});
</script>
<?php if (!empty($invoice)): ?>
<script>
(function () {
  const invoice = <?php echo json_encode($invoice); ?>;

  // ✅ IMPORTANT: अगर unpaid है तो print मत खोलो
  if (invoice.payment_status === 'unpaid') {
      window.location.href = "unpaid_sales.php?set_due=1&bill_id=" + invoice.id;
      return; // 🔥 yahin stop
  }

  // ✅ NORMAL PRINT (PAID CASE)
  document.getElementById('inv_id').textContent = invoice.id;
  document.getElementById('inv_date').textContent = invoice.created_at;
  document.getElementById('inv_payment').textContent =
    invoice.payment_status.toUpperCase();

  const inv_items = document.getElementById('inv_items');
  inv_items.innerHTML = '';

  invoice.items.forEach((it, idx) => {
    const qty = parseFloat(it.qty || 0);
    const price = parseFloat(it.price || 0);

    const tr = document.createElement('tr');
    tr.innerHTML =
      '<td>' + (idx + 1) + '</td>' +
      '<td>' + it.name + '</td>' +
      '<td>' + qty.toFixed(0) + '</td>' +
      '<td>' + price.toFixed(2) + '</td>' +
      '<td>' + (qty * price).toFixed(2) + '</td>';

    inv_items.appendChild(tr);
  });

  document.getElementById('inv_total').textContent = parseFloat(invoice.total).toFixed(2);

  document.getElementById('printInvoice').style.display = 'block';

  window.addEventListener('load', function () {
    setTimeout(function () {
      window.print();
    }, 400);
  });

  window.onafterprint = function () {
      window.location.href = window.location.pathname;
  };
})();



function hideAdvance(){
  document.getElementById('advanceModal').style.display = 'none';
}

function submitAdvance(){
  const adv = parseFloat(document.getElementById('advance_input').value) || 0;
  const due = document.getElementById('due_input').value;

  const totalText = document.getElementById('total_amount').textContent.replace('₹','').trim();
  const total = parseFloat(totalText) || 0;

  if (adv <= 0 || adv >= total) {
    alert("Invalid advance amount");
    return;
  }

  if (!due) {
    alert("Select due date");
    return;
  }

  // set hidden fields
  document.getElementById('advance_amount').value = adv;
  document.getElementById('due_date').value = due;

  hideAdvance();

  finalize('advance'); // 🔥 correct flow
}

</script>
<?php endif; ?>
</body>
</html>

