<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: auth-basic-signin.php");
    exit();
}

require_once __DIR__ . '/../inc/db.php';
$user_id = $_SESSION['user_id'];

// Fetch user data
$sql = "SELECT name, email, phone, mobile, address, instagram, facebook, profile_image 
        FROM users WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

$cid = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : 0;

// Customer detail
$cust = $conn->query("SELECT name FROM partycustomer WHERE id=$cid")->fetch_assoc();
    
// Items list
$items = [];
$res = $conn->query("SELECT ci.*, p.name AS product_name
                     FROM partycustomeritem ci
                     LEFT JOIN products p ON ci.product_id = p.id
                     WHERE ci.customer_id = $cid
                     ORDER BY ci.id DESC");
while($row = $res->fetch_assoc()) {
    $items[] = $row;
}

$productlist = [];
$result = $conn->query("SELECT * FROM products ORDER BY id ASC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $productlist[] = $row;
    }
}

// Totals for table metrics
$sumTotal = 0.0;
$sumReceived = 0.0;
$sumPending = 0.0;
foreach ($items as $t) {
    $tTotal = (float)($t['total_amount'] ?? 0);
    $tRecv  = (float)($t['amount_payment'] ?? 0);
    $sumTotal    += $tTotal;
    $sumReceived += $tRecv;
    $sumPending  += ($tTotal - $tRecv);
}

// Handle single bill POST request (exclude multi and single invoice AJAX routes)
if (
	$_SERVER['REQUEST_METHOD'] === 'POST'
	&& !isset($_POST['multi_invoice'])
	&& !isset($_POST['single_invoice'])
	&& !isset($_POST['update_customer_item'])
	&& !isset($_POST['delete_customer_item'])
) { 
    $cid        = intval($_POST['customer_id'] ?? 0);
    $owner      = trim($_POST['ownername'] ?? '');
    $address    = trim($_POST['address'] ?? '');
    $billDate   = $_POST['billdate'] ?? '';
    $billNum    = trim($_POST['billnumber'] ?? '');
    $productId  = intval($_POST['product_id'] ?? 0);
    $qty        = intval($_POST['quantity'] ?? 0);
    $productName = $_POST['name'] ?? ''; 
    $hsnCode     = trim($_POST['hsn_code'] ?? ''); 
    
    $fullPay    = ($_POST['fullpaymentreceived'] ?? 'yes') === 'no' ? 'no' : 'yes';
    $amtPay     = $fullPay === 'no' ? floatval($_POST['amount_payment'] ?? 0) : 0;

    if (!$cid || !$productId || $qty <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid data provided.']);
        exit;
    }

    $stmt = $conn->prepare("SELECT sell_price, quantity, name FROM products WHERE id = ?");
    $stmt->bind_param("i", $productId);
    $stmt->execute();
    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    $stmt->close();

    if (!$product) {
        echo json_encode(['status' => 'error', 'message' => 'Product not found.']);
        exit;
    }

    $availableQty = (int)$product['quantity'];
    $price        = (float)$product['sell_price'];
    $productName  = $product['name']; 
    
    
    if ($qty > $availableQty) {
        echo json_encode([
            'status'  => 'error',
            'message' => "Quantity not enough. Available: {$availableQty}"
        ]);
        exit;
    }
    $shopname = $_POST['shopname'] ?? '';  
    
    $totalAmount = $price * $qty;
$fullPay = ($_POST['fullpaymentreceived'] ?? 'yes') === 'no' ? 'no' : 'yes';

// 👉 Agar YES hai to amount_payment = totalAmount set karo
$amtPay = ($fullPay === 'yes')
    ? $totalAmount          // ✅ full payment = price * qty
    : floatval($_POST['amount_payment'] ?? 0);
    // Insert customer item 
     $sql = "INSERT INTO partycustomeritem
        (customer_id, product_id, product_name, hsn_code, shop_name,
         owner_name, address, bill_date, bill_number,
         price, quantity, full_payment_received, amount_payment, total_amount)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            echo json_encode(['status'=>'error','message'=>'Prepare failed: '.$conn->error]);
            exit;
        }
        
        $stmt->bind_param(
            "iisssssssdissd",
            $cid,
            $productId,
            $productName,
            $hsnCode,
            $shopname,
            $owner,
            $address,
            $billDate,
            $billNum,
            $price,
            $qty,
            $fullPay,
            $amtPay,
            $totalAmount
        );

    if ($stmt->execute()) {
        // update stock
        $newQty = $availableQty - $qty;
        $upd = $conn->prepare("UPDATE products SET quantity=? WHERE id=?");
        $upd->bind_param("ii", $newQty, $productId);
        $upd->execute();
        $upd->close();

        echo json_encode(['status' => 'success', 'message' => 'Bill Added']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Execution failed: ' . $stmt->error]);
    }
    $stmt->close();
    exit;
}

// Update existing customer item (Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_customer_item'])) {
	$itemId    = intval($_POST['id'] ?? 0);
	$shopname  = trim($_POST['shop_name'] ?? '');
	$owner     = trim($_POST['owner_name'] ?? '');
	$address   = trim($_POST['address'] ?? '');
	$product   = trim($_POST['product_name'] ?? '');
	$hsnCode   = trim($_POST['hsn_code'] ?? '');
	$billNum   = trim($_POST['bill_number'] ?? '');
	$billDate  = trim($_POST['bill_date'] ?? '');
	$price     = floatval($_POST['price'] ?? 0);
	$qty       = intval($_POST['quantity'] ?? 0);
	$fullPay   = (($_POST['full_payment_received'] ?? 'yes') === 'no') ? 'no' : 'yes';
	$amtPay    = ($fullPay === 'yes') ? ($price * $qty) : floatval($_POST['amount_payment'] ?? 0);
	$total     = $price * $qty;

	if (!$itemId || $qty <= 0 || $price < 0) {
		echo json_encode(['status'=>'error','message'=>'Invalid input data']);
		exit;
	}

	$sql = "UPDATE partycustomeritem SET shop_name=?, owner_name=?, address=?, product_name=?, hsn_code=?, bill_number=?, bill_date=?,
				price=?, quantity=?, full_payment_received=?, amount_payment=?, total_amount=?
			WHERE id=?";
	$stmt = $conn->prepare($sql);
	if (!$stmt) {
		echo json_encode(['status'=>'error','message'=>'Prepare failed: '.$conn->error]);
		exit;
	}
	$stmt->bind_param(
		"sssssssdisdii",
		$shopname,
		$owner,
		$address,
		$product,
		$hsnCode,
		$billNum,
		$billDate,
		$price,
		$qty,
		$fullPay,
		$amtPay,
		$total,
		$itemId
	);
	if ($stmt->execute()) {
		echo json_encode(['status'=>'success','message'=>'Item updated']);
	} else {
		echo json_encode(['status'=>'error','message'=>'Execute failed: '.$stmt->error]);
	}
	$stmt->close();
	exit;
}

// Delete existing customer item
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_customer_item'])) {
	$itemId = intval($_POST['id'] ?? 0);
	if (!$itemId) {
		echo json_encode(['status'=>'error','message'=>'Invalid item id']);
		exit;
	}
	$stmt = $conn->prepare("DELETE FROM partycustomeritem WHERE id=?");
	if (!$stmt) {
		echo json_encode(['status'=>'error','message'=>'Prepare failed: '.$conn->error]);
		exit;
	}
	$stmt->bind_param("i", $itemId);
	if ($stmt->execute()) {
		echo json_encode(['status'=>'success','message'=>'Item deleted']);
	} else {
		echo json_encode(['status'=>'error','message'=>'Execute failed: '.$stmt->error]);
	}
	$stmt->close();
	exit;
}

// Mutli Invoce start
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['multi_invoice'])) {

    $customer_id = intval($_POST['customer_id'] ?? 0);
    $products_json = $_POST['products'] ?? '[]';
    $products = json_decode($products_json, true);
     $invoice_number = trim($_POST['invoice_number'] ?? '');
    $invoice_date   = trim($_POST['invoice_date'] ?? '');

    if (!$customer_id || empty($products)) {
            echo json_encode(['status'=>'error','msg'=>'No products selected.']);
            exit;
        }
        if (!$invoice_number || !$invoice_date) {
            echo json_encode(['status'=>'error','msg'=>'Invoice number or date missing.']);
            exit;
        }

    $products_data = json_encode($products); 
    $stmt = $conn->prepare(
            "INSERT INTO partycustomerinvoice (customer_id, products_data, invoice_number, invoice_date)
             VALUES (?, ?, ?, ?)"
        );
        $stmt->bind_param("isss", $customer_id, $products_data, $invoice_number, $invoice_date);

        if ($stmt->execute()) {
            echo json_encode([
                'status' => 'success',
                'id' => $stmt->insert_id,
                'customer_id' => $customer_id,
                'products_data' => $products_data,
                'invoice_number' => $invoice_number,
                'invoice_date' => $invoice_date
            ]);
        } else {
            echo json_encode(['status'=>'error','msg'=>'Execute failed: '.$stmt->error]);
        }
        $stmt->close();
        exit;
} 
// Mutli Invoce End

// Single Invoce start 

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['single_invoice'])) {

    $customer_id = intval($_POST['customer_id'] ?? 0);

    // Single product sent as JSON string
    $product_json = $_POST['product'] ?? '';
    $product = json_decode($product_json, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['status'=>'error','msg'=>'JSON decode error: '.json_last_error_msg()]);
        exit;
    }

    if (!$customer_id || empty($product)) {
        echo json_encode(['status'=>'error','msg'=>'Invalid data.']);
        exit;
    }

    // Wrap product in array for DB
    $products_data = json_encode([$product]);

    // Use provided invoice details if sent, else auto-generate defaults
    $invoice_number = trim($_POST['invoice_number'] ?? '');
    $invoice_date   = trim($_POST['invoice_date'] ?? '');
    if ($invoice_number === '') { $invoice_number = 'INV-'.time(); }
    if ($invoice_date === '') { $invoice_date = date('Y-m-d'); }

    $stmt = $conn->prepare(
        "INSERT INTO partycustomerinvoice (customer_id, products_data, invoice_number, invoice_date)
         VALUES (?, ?, ?, ?)"
    );

    if (!$stmt) {
        echo json_encode(['status'=>'error','msg'=>'Prepare failed: '.$conn->error]);
        exit;
    }

    $stmt->bind_param("isss", $customer_id, $products_data, $invoice_number, $invoice_date);

    if ($stmt->execute()) {
        echo json_encode([
            'status'=>'success',
            'id'=>$stmt->insert_id,
            'customer_id'=>$customer_id,
            'products_data'=>$products_data,
            'invoice_number'=>$invoice_number,
            'invoice_date'=>$invoice_date
        ]);
    } else {
        echo json_encode(['status'=>'error','message'=>'Execute failed: '.$stmt->error, 'msg'=>'Execute failed: '.$stmt->error]);
    }

    $stmt->close();
    exit;
}
// Single Invoce End
?>

<!doctype html>
<html lang="en">

<head>
	<!-- Required meta tags -->
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--favicon-->
	<link rel="icon" href="assets/images/logo-icon.png" type="image/png" />
	<!--plugins-->
	<link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
	<link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
	<link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
	<link href="assets/plugins/datatable/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
	<!-- loader-->
	<link href="assets/css/pace.min.css" rel="stylesheet" />
	<script src="assets/js/pace.min.js"></script>
	<!-- Bootstrap CSS -->
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/bootstrap-extended.css" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
	<link href="assets/css/app.css" rel="stylesheet">
	<link href="assets/css/icons.css" rel="stylesheet">
	
	<title>Kumawat</title>
	<style>
/* Selected value box */
.select2-container--default .select2-selection--single {
    background-color: #171717 !important;   /* background color */
    color: #ffffff !important;              /* text color */
    border: 1px solid #444;      /* border color */
    height: 40px;
}

/* Placeholder text */
.select2-container--default .select2-selection--single .select2-selection__placeholder {
    color: #bbb !important;  /* placeholder color */
}

/* Dropdown items */
.select2-container--default .select2-results__option {
    background-color: #171717 !important;   /* dropdown background */
    color: #fff !important;                 /* text color */
}

/* Hover/active dropdown item */
.select2-container--default .select2-results__option--highlighted {
    background-color: #171717 !important;      /* hover background */
    color: #fff !important;                 /* hover text color */
}

/* Dropdown arrow icon */
.select2-container--default .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent; /* arrow color */
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
    color: #fff !important;
    line-height: 28px;
}
.select2-dropdown {
    background-color: #171717 !important;
    
}
.select2-container--default .select2-search--dropdown .select2-search__field {
    border: 1px solid #aaa;
    background: #171717 !important;
    color: #FFF !important;
}
.select2-container--default .select2-selection--single .select2-selection__clear { 
    color: #FFF !important;
    
}
 #example2 th, #example2 td { white-space: nowrap; vertical-align: middle; }

</style>  
</head>

<body class="bg-theme bg-theme2">
	<!--wrapper-->
	<div class="wrapper">
		<!--sidebar wrapper -->
		<div class="sidebar-wrapper" data-simplebar="true">
			<div class="sidebar-header">
				<div>
					<img src="assets/images/logo-icon.png" class="logo-icon" alt="logo icon">
				</div>
				<div>
					<h4 class="logo-text">Kumawat</h4>
				</div>
				<div class="toggle-icon ms-auto"><i class='bx bx-arrow-back'></i>
				</div>
			 </div>
			<!--navigation-->
			<ul class="metismenu" id="menu">
				<li>
					<a href="index.php">
						<div class="parent-icon"><i class='bx bx-home-alt'></i>
						</div>
						<div class="menu-title">Home</div>
					</a> 
				</li>  
				<li>
					<a href="table-datatable.php">
						<div class="parent-icon"><i class="bx bx-grid-alt"></i>
						</div>
						<div class="menu-title">Product Tables</div>
					</a> 
				</li>
			  
				<li>
					<a href="ecommerce-products.php">
						<div class="parent-icon"><i class='bx bx-briefcase-alt'></i>
						</div>
						<div class="menu-title">Products</div>
					</a> 
				</li>  
				<li>
					<a href="ecommerce-add-new-products.php">
						<div class="parent-icon"><i class='bx bx-store'></i>
						</div>
						<div class="menu-title">Add New Products</div>
					</a> 
				</li> 
				<li>
					<a href="temprary.php">
						<div class="parent-icon"><i class='bx bx-repeat'></i>
						</div>
						<div class="menu-title">Temporary</div>
					</a> 
				</li> 
				<li>
					<a href="permanent-customer.php">
						<div class="parent-icon"><i class='bx bx-bookmark-heart'></i>
						</div>
						<div class="menu-title">Permanent Customer</div>
					</a> 
				</li>
				<li>
					<a href="party-customer.php">
						<div class="parent-icon"><i class='bx bx-cookie'></i>
						</div>
						<div class="menu-title">Party</div>
					</a> 
				</li>
				<li>
					<a href="ecommerce-orders.php">
						<div class="parent-icon"><i class='bx bx-cart'></i>
						</div>
						<div class="menu-title">History</div>
					</a> 
				</li> 
				<li>
					<a href="user-profile.php">
						<div class="parent-icon"><i class="bx bx-user-circle"></i>
						</div>
						<div class="menu-title">User Profile</div>
					</a>
				</li>  
			</ul>
			<!--end navigation-->
		</div>
		<!--end sidebar wrapper -->
		<!--start header -->
		<header>
			<div class="topbar d-flex align-items-center">
				<nav class="navbar navbar-expand gap-3">
					<div class="mobile-toggle-menu"><i class='bx bx-menu'></i>
					</div>
					<div class="search-bar flex-grow-1">
						<div class="position-relative search-bar-box">
							<input type="text" class="form-control search-control" placeholder="Type to search..."> <span class="position-absolute top-50 search-show translate-middle-y"><i class='bx bx-search'></i></span>
							<span class="position-absolute top-50 search-close translate-middle-y"><i class='bx bx-x'></i></span>
						</div>
					</div>
					<div class="top-menu ms-auto">
						<ul class="navbar-nav align-items-center gap-1">
							<li class="nav-item mobile-search-icon d-flex d-lg-none" data-bs-toggle="modal" data-bs-target="#SearchModal">
								<a class="nav-link" href="avascript:;"><i class='bx bx-search'></i>
								</a>
							</li>  
						</ul>
					</div>
					<div class="user-box dropdown px-3">
						<a class="d-flex align-items-center nav-link dropdown-toggle gap-3 dropdown-toggle-nocaret" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
							<img src="<?= htmlspecialchars($user['profile_image'] ?: 'assets/images/avatars/avatar-2.png') ?>"
                                             alt="Profile" class="user-img">
							<div class="user-info">
								<p class="user-name mb-0"><?= htmlspecialchars($user['name']) ?></p>
								<p class="designattion mb-0"><?= htmlspecialchars($user['email']) ?></p>
							</div>
						</a>
						<ul class="dropdown-menu dropdown-menu-end">
							<li><a class="dropdown-item d-flex align-items-center" href="user-profile.php"><i class="bx bx-user fs-5"></i><span>Profile</span></a>
							</li> 
							<li>
								<div class="dropdown-divider mb-0"></div>
							</li>
							<li><a class="dropdown-item d-flex align-items-center" href="logout.php"><i class="bx bx-log-out-circle"></i><span>Logout</span></a>
							</li>
						</ul>
					</div>
				</nav>
			</div>
		</header>
		<!--end header -->
		<!--start page wrapper -->
		<div class="page-wrapper">
			<div class="page-content">
				<!--breadcrumb-->
				<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
					<div class="breadcrumb-title pe-3">Customer Name</div>
					<div class="ps-3">
						<nav aria-label="breadcrumb">
							<ol class="breadcrumb mb-0 p-0">
								<li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-home-alt"></i></a>
								</li>
								<li class="breadcrumb-item active" aria-current="page"><?= htmlspecialchars($cust['name'] ?? 'Unknown'); ?></li>
							</ol>
						</nav>
					</div> 
					<div class="ms-auto">
					<div class="btn-group ms-2">
						<button type="button" data-bs-toggle="modal" data-bs-target="#addbillModel" class="btn btn-light">Add Bill</button>  
					</div>
					<div class="btn-group">
						<a href="party-invoice-history.php?customer_id=<?= $cid ?>" class="btn btn-light">Invoice History</a>
					</div>
						<div class="btn-group"> 
							<button type="button" id="multiInvoiceOpenBtn" class="btn btn-light">Multiple Inovice Generate</button> 
						</div>
					</div>
				</div>
				<!--end breadcrumb-->
                <div class="row row-cols-1 row-cols-sm-2 row-cols-lg-3 row-cols-xl-4 row-cols-xxl-5">
				     
					<div class="col"> 
						<div class="card product-card"  style="cursor:pointer;"> 
							<div class="card-body">
						<h6 class="card-title cursor-pointer text-center">Total Received Amount: <strong><?= number_format($sumReceived, 2) ?></strong></h6> 
							</div>
						</div> 
					</div>  
                    <div class="col"> 
						<div class="card product-card"  style="cursor:pointer;"> 
							<div class="card-body">
						<h6 class="card-title cursor-pointer text-center">Total Pending Amount: <strong><?= number_format($sumPending, 2) ?></strong></h6> 
							</div>
						</div> 
					</div>   
				</div>
				<h6 class="mb-0 text-uppercase">Product DataTable</h6>
				<hr/>
				<div class="card">
					<div class="card-body">
						<div class="table-responsive">
							<table id="example2" class="table table-striped table-bordered text-center">
								<thead>
									<tr>
									    <th><input type="checkbox" id="selectAll"></th>
										<th>#</th>
										<th>Farm Name</th>
                                        <th>Customer Name</th>
                                        <th>Product Name</th>
                                        <th>HSN Code</th>
                                        <th>Bill No</th>
                                        <th>Bill Date</th> 
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <th>Total Amount</th>
                                        <th>Received Amount</th>
                                        <th>Pending Amount</th>
                                        <th>Action</th>
									</tr>
								</thead>
                                <tbody> 
								 <?php if (count($items) > 0): ?>
                                    <?php foreach ($items as $i => $item): ?>
                                    <?php
                                        $pending = (float)$item['total_amount'] - (float)$item['amount_payment'];
                                        ?>
                                        <tr>
                                            <th>
                                               <input type="checkbox" class="row-check"
                                                       data-id="<?= $item['id'] ?>"
                                                       data-shop="<?= htmlspecialchars($item['shop_name']) ?>"
                                                       data-customer="<?= htmlspecialchars($item['owner_name']) ?>"
                                                       data-product="<?= htmlspecialchars($item['product_name']) ?>"
                                                       data-hsncode="<?= htmlspecialchars($item['hsn_code']) ?>"
                                                       data-bill="<?= htmlspecialchars($item['bill_number']) ?>"
                                                       data-billdate="<?= htmlspecialchars($item['bill_date']) ?>"
                                                       data-quantity="<?= $item['quantity'] ?>"
                                                       data-price="<?= $item['price'] ?>"
                                                       data-total="<?= $item['total_amount'] ?>"
                                                       data-received="<?= $item['amount_payment'] ?>" >
                                            </th>
                                            <td><?= $i + 1 ?></td>
                                            <td><?= htmlspecialchars($item['shop_name']) ?></td>
                                            <td><?= htmlspecialchars($item['owner_name']) ?></td>
                                            <td><?= htmlspecialchars($item['product_name']) ?></td>
                                            <td><?= htmlspecialchars($item['hsn_code']) ?></td>
                                            <td><?= htmlspecialchars($item['bill_number']) ?></td>
                                            <td><?= htmlspecialchars($item['bill_date']) ?></td>
                                            <td><?= htmlspecialchars($item['quantity']) ?></td>
                                            <td><?= htmlspecialchars($item['price']) ?></td>
                                            <td><?= htmlspecialchars($item['total_amount']) ?></td>
                                            <td><?= htmlspecialchars($item['amount_payment']) ?></td>
                                            <td><?= htmlspecialchars(number_format($pending, 2)) ?></td>
                                            <td>
                            <div class="d-flex order-actions"> 
                                <a href="javascript:;" 
								   class="openSingleInvoice" 
								   data-id="<?= $item['id'] ?>"
                                   data-shop="<?= htmlspecialchars($item['shop_name']) ?>"
                                   data-customer="<?= htmlspecialchars($item['owner_name']) ?>"
                                   data-product="<?= htmlspecialchars($item['product_name']) ?>"
                                   data-hsncode="<?= htmlspecialchars($item['hsn_code']) ?>"
                                   data-bill="<?= htmlspecialchars($item['bill_number']) ?>"
                                   data-billdate="<?= htmlspecialchars($item['bill_date']) ?>"
                                   data-quantity="<?= $item['quantity'] ?>"
                                   data-price="<?= $item['price'] ?>"
                                   data-total="<?= $item['total_amount'] ?>"
                                   data-received="<?= $item['amount_payment'] ?>">
								   <i class='bx bxs-printer'></i>
								</a>
								
                                <a href="javascript:;" class="ms-3 openEditItem" data-bs-toggle="modal"
                                   data-bs-target="#editItemModal"
                                   data-id="<?= $item['id'] ?>"
                                   data-shop="<?= htmlspecialchars($item['shop_name']) ?>"
                                   data-customer="<?= htmlspecialchars($item['owner_name']) ?>"
                                   data-address="<?= htmlspecialchars($item['address']) ?>"
                                   data-product="<?= htmlspecialchars($item['product_name']) ?>"
                                   data-hsncode="<?= htmlspecialchars($item['hsn_code']) ?>"
                                   data-bill="<?= htmlspecialchars($item['bill_number']) ?>"
                                   data-billdate="<?= htmlspecialchars($item['bill_date']) ?>"
                                   data-quantity="<?= htmlspecialchars($item['quantity']) ?>"
                                   data-price="<?= htmlspecialchars($item['price']) ?>"
                                   data-total="<?= htmlspecialchars($item['total_amount']) ?>"
                                   data-received="<?= htmlspecialchars($item['amount_payment']) ?>"
                                   data-fullpay="<?= htmlspecialchars($item['full_payment_received']) ?>">
                                   <i class='bx bxs-edit'></i>
                                </a>
                                   
                                <a href="javascript:;" class="ms-3 openDeleteItem" data-bs-toggle="modal"
                                data-bs-target="#deleteItemModal"
                                data-id="<?= $item['id'] ?>"
                                data-name="<?= htmlspecialchars($item['product_name']) ?>"><i class='bx bxs-trash'></i></a>
							</div>  
                        </td> 
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="text-center">No records found</td></tr>
                                <?php endif; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="10" class="text-end">Totals:</th>
                                        <th><?= number_format($sumTotal, 2) ?></th>
                                        <th><?= number_format($sumReceived, 2) ?></th>
                                        <th><?= number_format($sumPending, 2) ?></th>
                                        <th></th>
                                    </tr>
                                </tfoot> 
							</table>
						</div>
					</div>
				</div>
			</div>
		</div> 
		<!--Multi Invoice model Start -->
                     <div class="modal fade" id="invoicemultiModel" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                             <form id="invoicemultiForm" method="post">
                              <div class="modal-header">
                                <h5 class="modal-title" id="modalCenterTitle">Create Invoice</h5>
                                <button
                                  type="button"
                                  class="btn-close"
                                  data-bs-dismiss="modal"
                                  aria-label="Close"
                                ></button>
                              </div>
                              <div class="modal-body">  
                                 
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="invoicemultidate" class="form-label">Invoice Date</label>
                                  <input type="date" name="invoicemultidate" 
                                      class="form-control" 
                                      placeholder="Enter Invoice Date" id="invoicemultidate" required />
                                   
                                  </div>
                                  <div class="col mb-0">
                                    <label for="invoicemultinumber" class="form-label">Invoice Number</label> 
                                    <input type="number" name="invoicemultinumber"  class="form-control"
                                      placeholder="Enter Invoice Number" id="invoicemultinumber"   required /> 
                                  </div>  
                                </div>   
                              </div>
                              <div class="modal-footer">
                                <button type="button"  class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" id="multiSubmitBtn" class="btn btn-primary"><span class="btn-text">Create</span></button> 
                              </div>
                              </form>
                            </div>
                          </div>
                        </div>
                        <!--Multi Invoice model end -->
                        
		  <!--add bill model start -->
                     <div class="modal fade" id="addbillModel" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                             <form id="addbillForm" method="post">
                              <div class="modal-header">
                                <h5 class="modal-title" id="modalCenterTitle">Create Bill</h5>
                                <button
                                  type="button"
                                  class="btn-close"
                                  data-bs-dismiss="modal"
                                  aria-label="Close"
                                ></button>
                              </div>
                              <div class="modal-body">  
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="ownername" class="form-label">Owner Name</label>
                                    <input
                                      type="text"
                                      id="ownername"
                                      class="form-control"
                                      name="ownername"
                                      placeholder="Enter ownername Name"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="address" class="form-label">Address</label>
                                    <input
                                      type="text"
                                      id="address"
                                      name="address"
                                      class="form-control"
                                      placeholder="Enter Address"
                                      required
                                    />
                                  </div> 
                                </div> 
                                
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="billdate" class="form-label">Bill Date</label>
                                  <input type="date" name="billdate" 
                                      class="form-control" 
                                      placeholder="Enter Bill Date" id="billdate" required />
                                   
                                  </div>
                                  <div class="col mb-0">
                                    <label for="billnumber" class="form-label">Bill Number</label>
                                    
                                    <input type="number" name="billnumber"  class="form-control"
                                      placeholder="Enter Bill Number" id="billnumber"   required /> 
                                  </div>  
                                </div>
                                 <div class="row g-2 mb-3">
                                  <div class="col-12">
                                    <label for="productSelect" class="form-label">Select Product</label>
                                    <select id="productSelect" name="product_id" class="form-control" style="width:100%">
                                        <option value="">-- Select Product --</option>
                                        <?php foreach ($productlist as $p): ?>
                                            <option value="<?= $p['id'] ?>"
                                                    data-price="<?= htmlspecialchars($p['sell_price']) ?>" 
                                                    data-name="<?= htmlspecialchars($p['name']) ?>"
                                                    data-hsncode="<?= $p['hsn_code'] ?>" >
                                                
                                                <?= htmlspecialchars($p['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                  </div>
                                </div>
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="productPrice" class="form-label">Price</label> 
                                    <input name="productPrice"  class="form-control"
                                      placeholder="Enter product Price" id="productPrice" readonly />  
                                  </div>
                                  <div class="col mb-0">
                                   <label for="quantity" class="form-label">Quantity</label> 
                                    <input type="number" name="quantity"  class="form-control"
                                      placeholder="Enter Quantity" id="quantity" required /> 
                                  </div>  
                                </div>
                                
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="fullpaymentreceived" class="form-label">Full Payment Received</label> 
                                    <select id="fullpaymentreceived" name="fullpaymentreceived" class="form-control" style="width:100%">
                                        <option value="yes" selected>Yes</option> 
                                         <option value="no">No</option> 
                                    </select>
                                  </div>
                                  <div class="col mb-0" id="amountBox" style="display:none;">
                                   <label for="amount_payment" class="form-label">Received Amount</label> 
                                    <input type="number" name="amount_payment" class="form-control"
                                      placeholder="Enter Recived Amount" id="amount_payment" /> 
                                  </div>  
                                </div>
                                
                               <input name="productid" type="hidden" class="form-control" id="productid" readonly /> 
                               <input type="hidden" id="hsn_code" name="hsn_code">
                               <input type="hidden" name="product_name" id="product_name" />
                                <input type="hidden" name="shopname" id="shopname" value="<?= htmlspecialchars($cust['name'] ?? '') ?>"> 
                                <input type="hidden" name="customer_id" value="<?= $cid ?>">
                              </div>
                              <div class="modal-footer">
                                <button type="button"  class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" id="billSubmitBtn" class="btn btn-primary"><span class="btn-text">Create</span></button> 
                              </div>
                              </form>
                            </div>
                          </div>
                        </div>
                        <!--add bill model end -->
		
		<!-- Edit Item Modal start -->
		<div class="modal fade" id="editItemModal" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-dialog-centered" role="document">
				<div class="modal-content">
					<form id="editItemForm" method="post">
						<div class="modal-header">
							<h5 class="modal-title">Edit Item</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="id" id="edit_item_id" />
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_shop_name">Farm Name</label>
									<input type="text" id="edit_shop_name" name="shop_name" class="form-control" required />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_owner_name">Customer Name</label>
									<input type="text" id="edit_owner_name" name="owner_name" class="form-control" required />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_address">Address</label>
									<input type="text" id="edit_address" name="address" class="form-control" />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_product_name">Product</label>
									<input type="text" id="edit_product_name" name="product_name" class="form-control" required />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_hsn_code">HSN Code</label>
									<input type="text" id="edit_hsn_code" name="hsn_code" class="form-control" />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_bill_number">Bill No</label>
									<input type="text" id="edit_bill_number" name="bill_number" class="form-control" />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_bill_date">Bill Date</label>
									<input type="date" id="edit_bill_date" name="bill_date" class="form-control" />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_quantity">Quantity</label>
									<input type="number" id="edit_quantity" name="quantity" class="form-control" required />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_price">Price</label>
									<input type="number" step="0.01" id="edit_price" name="price" class="form-control" readonly />
								</div>
								<div class="col mb-0">
									<label class="form-label" for="edit_total_amount">Total Amount</label>
									<input type="number" step="0.01" id="edit_total_amount" name="total_amount" class="form-control" readonly />
								</div>
							</div>
							<div class="row g-2 mb-3">
								<div class="col mb-0">
									<label class="form-label" for="edit_fullpaymentreceived">Full Payment Received</label>
									<select id="edit_fullpaymentreceived" name="full_payment_received" class="form-control">
										<option value="yes">Yes</option>
										<option value="no">No</option>
									</select>
								</div>
								<div class="col mb-0" id="edit_amount_box" style="display:none;">
									<label class="form-label" for="edit_amount_payment">Received Amount</label>
									<input type="number" step="0.01" id="edit_amount_payment" name="amount_payment" class="form-control" />
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
							<button type="submit" id="editItemSave" class="btn btn-primary">Save</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		<!-- Edit Item Modal end -->

		<!-- Delete Item Modal start -->
		<div class="modal fade" id="deleteItemModal" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-dialog-centered" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">Delete Item</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
						<p>Are you sure you want to delete <strong id="delete_item_name"></strong>?</p>
						<input type="hidden" id="delete_item_id" />
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">No</button>
						<button type="button" id="confirmDeleteItem" class="btn btn-danger">Yes, Delete</button>
					</div>
				</div>
			</div>
		</div>
		<!-- Delete Item Modal end -->
                         
		<!--end page wrapper -->
		<!--start overlay-->
		<div class="overlay toggle-icon"></div>
		<!--end overlay-->
		<!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
		<!--End Back To Top Button-->
		<footer class="page-footer">
			<p class="mb-0">Copyright @ 2021. All right reserved.</p>
		</footer>
	</div>
	<!--end wrapper-->
	<!--start switcher-->
	<div class="switcher-wrapper">
		<div class="switcher-btn"> <i class='bx bx-cog bx-spin'></i>
		</div>
		<div class="switcher-body">
			<div class="d-flex align-items-center">
				<h5 class="mb-0 text-uppercase">Theme Customizer</h5>
				<button type="button" class="btn-close ms-auto close-switcher" aria-label="Close"></button>
			</div>
			<hr/>
			<p class="mb-0">Gaussian Texture</p>
			  <hr>
			  
			  <ul class="switcher">
				<li id="theme1"></li>
				<li id="theme2"></li>
				<li id="theme3"></li>
				<li id="theme4"></li>
				<li id="theme5"></li>
				<li id="theme6"></li>
			  </ul>
               <hr>
			  <p class="mb-0">Gradient Background</p>
			  <hr>
			  
			  <ul class="switcher">
				<li id="theme7"></li>
				<li id="theme8"></li>
				<li id="theme9"></li>
				<li id="theme10"></li>
				<li id="theme11"></li>
				<li id="theme12"></li>
				<li id="theme13"></li>
				<li id="theme14"></li>
				<li id="theme15"></li>
			  </ul>
		</div>
	</div>
	<!--end switcher-->
	<!-- Bootstrap JS -->
	<script src="assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="assets/js/jquery.min.js"></script>
	<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
	<script src="assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


	<!-- <script>
		$(document).ready(function() {
			$('#example').DataTable(
			  
			  );
			$("div.dataTables_filter input").focus();
		  } );
	</script> -->
	
	
	<script>
	  
	  $(document).ready(function() {
	  $('#example').DataTable()
	});
	  
	</script>
	
	
	<script>
		$(document).ready(function() {
			var table = $('#example2').DataTable( {
				lengthChange: false,
				buttons: [ 'copy', 'excel', 'pdf', 'print']
			} );
		 
			table.buttons().container()
				.appendTo( '#example2_wrapper .col-md-6:eq(0)' );
		} );
	</script>
	<!--app JS-->
	<script src="assets/js/app.js"></script>
 <!--multiple invoice JS Start-->
 <script>
let selectedProducts = [];
 $('#selectAll').on('change', function() {
    $('.row-check').prop('checked', $(this).prop('checked'));
});

$(document).on('change', '.row-check', function() {
    if(!$(this).prop('checked')){
        $('#selectAll').prop('checked', false);
    } else if($('.row-check:checked').length === $('.row-check').length){
        $('#selectAll').prop('checked', true);
    }
});
$('#multiInvoiceOpenBtn').on('click', function() {
    selectedProducts = [];  
    $('.row-check:checked').each(function() {
        selectedProducts.push({
            id: $(this).data('id'),
            shop_name: $(this).data('shop'),
            customer_name: $(this).data('customer'),
            product_name: $(this).data('product'),
            hsn_code: $(this).data('hsncode'),
            bill_number: $(this).data('bill'),
            bill_date: $(this).data('billdate'),
            quantity: parseInt($(this).data('quantity')),
            price: parseFloat($(this).data('price')),
            total_amount: parseFloat($(this).data('total')),
            amount_payment: parseFloat($(this).data('received'))
        });
    });

    if(selectedProducts.length === 0){
       toastr.error('No products selected.');
        return;
    }

    // Open modal
    $('#invoicemultiModel').modal('show');
});
 
$('#invoicemultiForm').on('submit', function(e) {
    e.preventDefault();

    if(selectedProducts.length === 0){
        toastr.error('No products selected.');
        return;
    }

    let invoiceDate = $('#invoicemultidate').val();
    let invoiceNumber = $('#invoicemultinumber').val();

    if(!invoiceDate || !invoiceNumber){
        toastr.error('Please enter invoice date and number.');
        return;
    }

    let btn = $('#multiSubmitBtn');
    btn.prop('disabled', true).text('Processing...');

    $.ajax({
        url: '', 
        type: 'POST',
        dataType: 'json',
        data: {
            multi_invoice: 1,
            customer_id: '<?= $cid ?>', 
            invoice_date: invoiceDate,
            invoice_number: invoiceNumber,
            products: JSON.stringify(selectedProducts)
        },
        success: function(res){
            if(res.status === 'success'){
               toastr.success('Invoice created successfully!');
                $('#invoicemultiModel').modal('hide');
                $('#invoicemultiForm')[0].reset();
                $('.row-check').prop('checked', false);
                $('#selectAll').prop('checked', false);
                window.open('party-customer-invoice.php?id=' + res.id, '_blank');
            }  else {
                toastr.error(res.msg || 'Failed to create invoice.');
            }
        },
        error: function(xhr){
             toastr.error('Server error: ' + (xhr.responseText || 'No response'));
        },
        complete: function(){
            btn.prop('disabled', false).text('Create');
        }
    });
});
</script> 
<!--multiple invoice JS End-->
<script>
$(document).on('click', '.openSingleInvoice', function(e){
    e.preventDefault();

    const product = {
        id:            $(this).data('id'),
        shop_name:     $(this).data('shop'),
        customer_name: $(this).data('customer'),
        product_name:  $(this).data('product'),
        hsn_code:      $(this).data('hsncode'),
        bill_number:   $(this).data('bill'),
        bill_date:     $(this).data('billdate'),
        quantity:      parseInt($(this).data('quantity')) || 0,
        price:         parseFloat($(this).data('price')) || 0,
        total_amount:  parseFloat($(this).data('total')) || 0,
        amount_payment:parseFloat($(this).data('received')) || 0
    };

    const customerId = parseInt('<?= $cid ?? 0 ?>'); // PHP variable

    if(customerId <= 0){
        toastr.error('Invalid customer ID');
        return;
    }

    $.ajax({
        url: '',
        type: 'POST',
        dataType: 'json',
        data: {
            single_invoice: 1,
            customer_id: customerId,
            product: JSON.stringify(product)
        },
        success: function(res){
            if(res.status === 'success'){
                toastr.success('Invoice created successfully!');
                window.open('party-customer-invoice.php?id=' + res.id, '_blank');
            } else {
                toastr.error(res.msg || 'Failed to create invoice.');
            }
        },
        error: function(xhr){
            toastr.error('Server error: ' + (xhr.responseText || 'No response'));
        }
    });
});

</script>

<script>
// Delete modal wiring and action
$(document).on('click', '.openDeleteItem', function(){
	$('#delete_item_id').val($(this).data('id'));
	$('#delete_item_name').text($(this).data('name'));
	$('#deleteItemModal').modal('show');
});

$('#confirmDeleteItem').on('click', function(){
	const id = $('#delete_item_id').val();
	const btn = $(this);
	const orig = btn.text();
	btn.prop('disabled', true).text('Deleting...');
	$.ajax({
		url: '',
		type: 'POST',
		dataType: 'json',
		data: { delete_customer_item: 1, id: id },
		success: function(res){
			if(res.status==='success'){
				toastr.success('Deleted successfully');
				$('#deleteItemModal').modal('hide');
				location.reload();
			}else{
				toastr.error(res.message||res.msg||'Delete failed');
			}
		},
		error: function(xhr){
			toastr.error('Server error: ' + (xhr.responseText || 'No response'));
		},
		complete: function(){
			btn.prop('disabled', false).text(orig);
		}
	});
});
</script>

<script>
// Edit Item JS: populate modal, handle totals and submit
$(document).on('click', '.openEditItem', function(){
	const btn = $(this);
	$('#edit_item_id').val(btn.data('id'));
	$('#edit_shop_name').val(btn.data('shop'));
	$('#edit_owner_name').val(btn.data('customer'));
	$('#edit_address').val(btn.data('address'));
	$('#edit_product_name').val(btn.data('product'));
	$('#edit_hsn_code').val(btn.data('hsncode'));
	$('#edit_bill_number').val(btn.data('bill'));
	$('#edit_bill_date').val(btn.data('billdate'));
	$('#edit_quantity').val(btn.data('quantity'));
	$('#edit_price').val(btn.data('price'));
	$('#edit_total_amount').val(btn.data('total'));
	$('#edit_amount_payment').val(btn.data('received'));
	$('#edit_fullpaymentreceived').val(btn.data('fullpay'));
	if($('#edit_fullpaymentreceived').val()==='no'){
		$('#edit_amount_box').show();
	}else{
		$('#edit_amount_box').hide();
	}
});

function recalcEditTotals(){
	const price = parseFloat($('#edit_price').val()||0);
	const qty = parseFloat($('#edit_quantity').val()||0);
	const total = price * qty;
	$('#edit_total_amount').val(total.toFixed(2));
	if($('#edit_fullpaymentreceived').val()==='yes'){
		$('#edit_amount_payment').val(total.toFixed(2));
	}
}
$(document).on('input', '#edit_price, #edit_quantity', recalcEditTotals);
$(document).on('change', '#edit_fullpaymentreceived', function(){
	if($(this).val()==='yes'){
		$('#edit_amount_box').hide();
		$('#edit_amount_payment').prop('required', false);
		recalcEditTotals();
	}else{
		$('#edit_amount_box').show();
		$('#edit_amount_payment').prop('required', true);
	}
});

$('#editItemForm').on('submit', function(e){
	e.preventDefault();
	const btn = $('#editItemSave');
	const orig = btn.text();
	btn.prop('disabled', true).text('Saving...');
	$.ajax({
		url: '',
		type: 'POST',
		dataType: 'json',
		data: $(this).serialize() + '&update_customer_item=1',
		success: function(res){
			if(res.status==='success'){
				toastr.success(res.message||'Item updated');
				$('#editItemModal').modal('hide');
				location.reload();
			}else{
				toastr.error(res.message||res.msg||'Update failed');
			}
		},
		error: function(xhr){
			toastr.error('Server error: ' + (xhr.responseText || 'No response'));
		},
		complete: function(){
			btn.prop('disabled', false).text(orig);
		}
	});
});
</script>


<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('#productSelect').select2({
        placeholder: 'Search Product',   
        allowClear: true,             
        dropdownParent: $('#addbillModel')  
    });
     $('#productSelect').on('change', function () {
        const price = $(this).find(':selected').data('price') || ''; 
        $('#productPrice').val(price); 
    });
      $('#productSelect').on('change', function () {
        const price = $(this).find(':selected').data('id') || '';
        $('#productid').val(price);
    });
     $('#productSelect').on('change', function () { 
         const name = $(this).find(':selected').data('name') || ''; 
        $('#product_name').val(name);
    });
    $('#productSelect').on('change', function () { 
    const hsncode = $(this).find(':selected').data('hsncode') || ''; 
    $('#hsn_code').val(hsncode);
        console.log('HSN set to:', hsncode); 
    });
});
</script>

<script> 

$(function () {
    // toastr global options (top-right position)
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "4000"
    };
 $('#loadingOverlay').hide();
   
$('#addbillForm').on('submit', function (e) {
        e.preventDefault();

        const btn = $('#billSubmitBtn');
        const orig = btn.text();
        btn.prop('disabled', true).text('Creating...');
        $('#loadingOverlay').show();

       const fd = new FormData(this);
        $.ajax({
            url: '',  
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            dataType: 'json', 
            success: function (res) {
                $('#loadingOverlay').hide();
                btn.prop('disabled', false).text(orig);

                if (res.status === 'success') {
                    toastr.success(res.message);
                    $('#addbillForm')[0].reset();
                    $('#addbillModel').modal('hide');
                    location.reload();
                } else {
                    
                    toastr.error(res.message || 'Error saving bill');
                }
            },
            error: function (xhr) {
                $('#loadingOverlay').hide();
                btn.prop('disabled', false).text(orig);
                let msg = 'Server error';
                try {
                    const j = JSON.parse(xhr.responseText);
                    if (j.message) msg = j.message;
                } catch(e){}
                toastr.error(msg);
            }
        });
    });
});
</script>

<script>
$(document).ready(function () {
    function fillAmountIfYes() {
        const price = parseFloat($('#productPrice').val() || 0);
        const qty   = parseFloat($('#quantity').val() || 0);
        const total = price * qty;

        if ($('#fullpaymentreceived').val() === 'yes') {
            // hide box & auto-fill
            $('#amountBox').hide();
            $('#amount_payment').val(total.toFixed(2));
        } else {
            // show box & clear so user can type
            $('#amountBox').show();
            $('#amount_payment').val('');
        }
    }

    // run whenever user changes these
    $('#fullpaymentreceived').on('change', fillAmountIfYes);
    $('#productPrice, #quantity').on('input', fillAmountIfYes);
});
</script>

 <script>
$(document).ready(function () {
    $('#fullpaymentreceived').on('change', function () {
        if ($(this).val() === 'no') {
            
            $('#amountBox').show();
            $('#amount_payment').prop('required', true);
        } else {
           
            $('#amountBox').hide();
            $('#amount_payment').prop('required', false).val('');
        }
    });
});
</script>

</body>

<script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpsh-oh'},{'server':'p3plzcpnl509132'},{'dcenter':'p3'},{'cp_id':'10399385'},{'cp_cl':'8'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html>