<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
 
if (!isset($_SESSION['user_id'])) {
    header("Location: auth-login-basic.php");
    exit();
}

require_once __DIR__ . '/../inc/db.php'; // $conn

$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();

// ==== Delete product (Ajax) ====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_product') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM products WHERE id=?");
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => $stmt->error]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid ID']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'products') {
    $id = intval($_POST['id']);
    $name = $_POST['name'] ?? '';
    $price = floatval($_POST['price'] ?? 0);
    $sell_price = floatval($_POST['sell_price'] ?? 0);
    $distributor = $_POST['distributor'] ?? '';
    $quantity = intval($_POST['quantity'] ?? 0);
    $hsn_code = $_POST['hsn_code'] ?? ''; 
    $details = $_POST['details'] ?? '';
    $existing = json_decode($_POST['existing_images'] ?? '[]', true);

    // Handle new images upload
    $newImages = [];
    if (!empty($_FILES['images']['name'][0])) {
        $uploadDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        foreach ($_FILES['images']['name'] as $k => $nameFile) {
            $tmp = $_FILES['images']['tmp_name'][$k];
            $ext = pathinfo($nameFile, PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $ext;
            if (move_uploaded_file($tmp, $uploadDir . $filename)) {
                $newImages[] = $filename;
            }
        }
    }

    $allImages = array_merge($existing, $newImages);
    $imagesJson = json_encode($allImages, JSON_UNESCAPED_UNICODE);

    // Correct bind_param types: s = string, d = double, i = int
    $stmt = $conn->prepare("UPDATE products SET name=?, price=?, sell_price=?, distributor=?, quantity=?, hsn_code=?, details=?, images=? WHERE id=?");
    $stmt->bind_param('sddsisssi', $name, $price, $sell_price, $distributor, $quantity, $hsn_code, $details, $imagesJson, $id);

    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => $stmt->error]);
    }
    exit;
}

$products = [];
$result = $conn->query("SELECT * FROM products ORDER BY id ASC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $row['images'] = json_decode($row['images'], true); // <-- JSON decode
        $products[] = $row;
    }
} 

// ==== PHP Save Logic (same page) ====
// if ($_SERVER['REQUEST_METHOD'] === 'POST'
//     && isset($_POST['action'])
//     && $_POST['action'] === 'multi_invoices') {

//     header('Content-Type: application/json');

//     $partyName    = trim($_POST['partyname']    ?? '');
//     $businessName = trim($_POST['businessname'] ?? '');
//     $partyAddress = trim($_POST['partyaddress'] ?? '');
//     $gstNumber    = trim($_POST['gstnumber']    ?? '');
//     $productsJSON = $_POST['selectedProducts']  ?? '[]';
//     $products     = json_decode($productsJSON, true);

//     if (!is_array($products) || empty($products)) {
//         echo json_encode(['status' => 'error', 'msg' => 'No products selected']);
//         exit;
//     }

//     $stmt = $conn->prepare(
//         "INSERT INTO invoices
//          (product_id, name, price, sell_price, distributor, quantity,
//           party_name, business_name, party_address, gst_number, details)
//          VALUES (?,?,?,?,?,?,?,?,?,?,?)"
//     );

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

//     foreach ($products as $p) {
//         $id          = (int)($p['id'] ?? 0);
//         $name        = $p['name'] ?? '';
//         $price       = (float)($p['price'] ?? 0);
//         $sell_price  = (float)($p['sell_price'] ?? 0);
//         $distributor = $p['distributor'] ?? '';
//         $quantity    = (int)($p['quantity'] ?? 1);
//         $details     = $p['details'] ?? '';

//         $stmt->bind_param(
//             "isddsisisss",
//             $id,
//             $name,
//             $price,
//             $sell_price,
//             $distributor,
//             $quantity,
//             $partyName,
//             $businessName,
//             $partyAddress,
//             $gstNumber,
//             $details
//         );
//         $stmt->execute();
//     }

//     echo json_encode(['status' => 'success']);
//     exit;
// }
 
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'multi_invoices') {
    header('Content-Type: application/json');

    $partyName    = trim($_POST['partyname']    ?? '');
    $businessName = trim($_POST['businessname'] ?? '');
    $partyAddress = trim($_POST['partyaddress'] ?? '');
    $gstNumber    = trim($_POST['gstnumber']    ?? '');
    $invoiceDate  = trim($_POST['invoicedate']  ?? '');
    $invoiceId    = trim($_POST['invoiceid']    ?? '');
    $productsJson = $_POST['selectedProducts']  ?? '[]'; 

    // अब केवल एक row insert करेंगे
   $stmt = $conn->prepare(
        "INSERT INTO invoices
         (party_name, business_name, party_address, gst_number, invoice_date, invoice_id, products_json)
         VALUES (?,?,?,?,?,?,?)"
    );

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

    $stmt->bind_param(
        'sssssss',
        $partyName,
        $businessName,
        $partyAddress,
        $gstNumber,
        $invoiceDate,
        $invoiceId,
        $productsJson   // पूरा JSON string
    );
      if ($stmt->execute()) {
        echo json_encode([
            'status' => 'success',
            'id'     => $conn->insert_id
        ]);
    } else {
        echo json_encode(['status'=>'error','msg'=>'Execute failed: '.$stmt->error]);
    }
    exit;
}
?>

<!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>
</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">Tables</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">Data Table</li>
							</ol>
						</nav>
					</div> 
					<div class="ms-auto">
						<div class="btn-group">
							<button type="button" id="generateInvoiceBtn" data-bs-toggle="modal" data-bs-target="#multiInvoiceModel" class="btn btn-light">Multiple Inovice Generate</button> 
						</div>
					</div>
				</div>
				<!--end breadcrumb-->
				 
				<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>Name</th>
                                        <th>Price</th>
                                        <th>Sell Price</th>
                                        <th>Distributer Name</th>
                                        <th>Product Quantity</th>
                                        <th>HSN Code</th>
                                        <th>Image</th>  
                                        <th>Action</th> 
									</tr>
								</thead>
								<tbody>
									 <?php foreach ($products as $p): ?>
                                <tr> 
                            <th>
                               <input type="checkbox" class="row-check"
                                       data-id="<?= $p['id'] ?>"
                                       data-name="<?= htmlspecialchars($p['name']) ?>"
                                       data-price="<?= $p['price'] ?>"
                                       data-sell="<?= $p['sell_price'] ?>"
                                       data-distributor="<?= htmlspecialchars($p['distributor']) ?>"
                                       data-quantity="<?= $p['quantity'] ?>"
                                       data-details="<?= htmlspecialchars($p['details'] ?? '') ?>">
                          </th>
                        <th scope="row"><?= $p['id']; ?></td>
                        <td><?= htmlspecialchars($p['name']); ?></td>
                        <td>₹<?= number_format($p['price'],2); ?></td>
                        <td>₹<?= number_format($p['sell_price'],2); ?></td>
                        <td><?= htmlspecialchars($p['distributor']); ?></td>
                        <td><?= intval($p['quantity']); ?></td>
                        <td><?= nl2br(htmlspecialchars($p['hsn_code'])); ?></td>
                        <td> 
                        <?php if (!empty($p['images'])): ?>
                            <?php $limitedImgs = array_slice($p['images'], 0, 3); ?>
                            <ul class="list-unstyled users-list m-0 avatar-group d-flex align-items-center">
                                <?php foreach ($limitedImgs as $img): ?>
                                    <li class="avatar avatar-xs pull-up" title="<?= htmlspecialchars($p['name']) ?>">
                                        <a href="uploads/<?= htmlspecialchars($img) ?>" target="_blank">
                                            <img src="uploads/<?= htmlspecialchars($img) ?>" style="height:30px; width:30px;" class="rounded-circle" alt="img">
                                        </a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            N/A
                        <?php endif; ?>
                          </td> 
                        <td>
                            <div class="d-flex order-actions"> 
                                <a href="javascript:;" 
								   class="openSingleInvoice"
								   data-bs-toggle="modal"
								   data-bs-target="#singleInvoiceModel"
								   data-id="<?= $p['id'] ?>"
								   data-name="<?= htmlspecialchars($p['name']) ?>"
								   data-price="<?= $p['price'] ?>"
								   data-sell="<?= $p['sell_price'] ?>"
								   data-distributor="<?= htmlspecialchars($p['distributor']) ?>"
								   data-quantity="<?= $p['quantity'] ?>"
								   data-hsncode="<?= htmlspecialchars($p['hsn_code']) ?>"
								   data-details="<?= htmlspecialchars($p['details'] ?? '') ?>">
								   <i class='bx bxs-printer'></i>
								</a>
								
								<a href="javascript:;" class="ms-3" data-bs-toggle="modal"
                                   data-bs-target="#editProduct"
                                   data-id="<?= $p['id'] ?>"
                                   data-name="<?= htmlspecialchars($p['name']) ?>"
                                   data-price="<?= htmlspecialchars($p['price']) ?>"
                                   data-sell="<?= htmlspecialchars($p['sell_price']) ?>"
                                   data-distributor="<?= htmlspecialchars($p['distributor']) ?>"
                                   data-quantity="<?= htmlspecialchars($p['quantity']) ?>"
                                   data-hsncode="<?= htmlspecialchars($p['hsn_code']) ?>"
                                   data-details="<?= htmlspecialchars($p['details']) ?>"
                                   data-images='<?= json_encode($p["images"] ?? []) ?>'><i class='bx bxs-edit'></i></a>
                                   
								<a href="javascript:;" class="ms-3" data-bs-toggle="modal"
                                data-bs-target="#deleteModal"
                                data-id="<?= $p['id'] ?>"
                                data-name="<?= htmlspecialchars($p['name']) ?>"><i class='bx bxs-trash'></i></a>
							</div>  
                        </td> 
                      </tr> 
                     
                       <?php endforeach; ?>  
								</tbody> 
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- Edit Modal Start -->
		<div class="modal fade" id="editProduct" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                 <form id="productForm" enctype="multipart/form-data">
                                     <input type="hidden" name="id" />
                              <div class="modal-header">
                                <h5 class="modal-title" id="modalCenterTitle">Product Edit</h5>
                                <button
                                  type="button"
                                  class="btn-close"
                                  data-bs-dismiss="modal"
                                  aria-label="Close"
                                ></button>
                              </div>
                              <div class="modal-body">
                                <div class="row">
                                  <div class="col mb-3">
                                    <label for="nameWithTitle" class="form-label">Name</label>
                                    <input
                                      type="text"
                                      id="nameWithTitle"
                                      name="name"
                                      class="form-control"
                                      placeholder="Enter Name"
                                      required
                                    />
                                  </div>
                                </div>
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="priceWithTitle" class="form-label">Price</label>
                                    <input
                                      type="number"
                                      id="priceWithTitle"
                                      name="price"
                                      class="form-control"
                                      placeholder="Enter Price"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="sellpriceWithTitle" class="form-label">Sell Price</label>
                                    <input
                                      type="number"
                                      id="sellpriceWithTitle"
                                      name="sell_price"
                                      class="form-control"
                                      placeholder="Enter Sell Price"
                                      required
                                    />
                                  </div> 
                                </div>
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="distributernameWithTitle" class="form-label">Distributer Name</label>
                                    <input
                                      type="text"
                                      id="distributernameWithTitle"
                                      class="form-control"
                                      name="distributor"
                                      placeholder="Enter Distributer Name"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="quantityWithTitle" class="form-label">Product Quantity</label>
                                    <input
                                      type="number"
                                      id="quantityWithTitle"
                                      name="quantity"
                                      class="form-control"
                                      placeholder="Enter Product Quantity"
                                      required
                                    />
                                  </div> 
                                </div>
                                 <div class="row">
                                  <div class="col mb-3">
                                    <label for="hsnCode" class="form-label">HSN Code</label>
                                    <input
                                      type="text"
                                      id="hsnCode"
                                      name="hsn_code"
                                      class="form-control"
                                      placeholder="Enter HSN Code"
                                      required
                                    />
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col mb-3">
                                    <label for="details" class="form-label">Details</label>
                                    <textarea
                                      type="text"
                                      id="details"
                                      class="form-control"
                                      name="details"
                                      placeholder="Hi, please Fill Details?"
                                      aria-label="Hi, please Fill Details?"
                                      aria-describedby="basic-icon-default-message2"
                                    ></textarea>
                                  </div>
                                </div> 
                                 <div class="mb-3">
                                    <label for="formFileMultiple" class="form-label">Multiple files input example</label>
                                    <input class="form-control" type="file" id="formFileMultiple" name="images[]" multiple accept=".png,.jpg,.jpeg"/>
                                  </div>
                                  <div id="previewBox" class="d-none border p-2 rounded" 
                                       style="display:flex; gap:10px; overflow-x:auto;">
                                  </div>
                              </div>
                              <div class="modal-footer">
                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" class="btn btn-primary">Save changes</button>
                                  <span class="spinner-border spinner-border-sm d-none" role="status" id="loadingSpinner"></span>

                              </div>
                              </form>
                            </div>
                          </div>
                        </div>
                         <!-- Edit Modal End -->
                        <!-- Small Modal 2 -->
                      <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
                          <div class="modal-content">
                            <div class="modal-header">
                              <h5 class="modal-title" id="exampleModalLabel2">Delete <strong id="deleteName"></strong></h5>
                              <button
                                type="button"
                                class="btn-close"
                                data-bs-dismiss="modal"
                                aria-label="Close"
                              ></button>
                            </div>
                            <div class="modal-body">
                              Are You Sure Want to Delete?
                            </div>
                            <div class="modal-footer">
                              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                No
                              </button>
                              <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Yes</button>
                              <span class="spinner-border spinner-border-sm d-none" id="deleteSpinner" role="status"></span>
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- Small Modal 2 End-->
                      
                      <!--Single invoice model start -->
                     <div class="modal fade" id="singleInvoiceModel" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                             <form id="singleInvoiceForm">
                              <div class="modal-header">
                                <h5 class="modal-title" id="modalCenterTitle">Generate 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="partyname" class="form-label">Party Name</label>
                                    <input
                                      type="text"
                                      id="partyname"
                                      class="form-control"
                                      name="partyname"
                                      placeholder="Enter Party Name"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="businessname" class="form-label">Business Name</label>
                                    <input
                                      type="text"
                                      id="businessname"
                                      name="businessname"
                                      class="form-control"
                                      placeholder="Enter Business Name"
                                      required
                                    />
                                  </div> 
                                </div>
                                
                                
                                
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="partyaddress" class="form-label">Party Address</label>
                                    <input
                                      type="text"
                                      id="partyaddress"
                                      class="form-control"
                                      name="partyaddress"
                                      placeholder="Enter Party Address"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="gstnumber" class="form-label">GST Number</label>
                                    <input
                                      type="text"
                                      id="gstnumber"
                                      name="gstnumber"
                                      class="form-control" 
                                      placeholder="Enter GST Number e.g. 22AAAAA0000A1Z5"
                                      pattern="^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$"
                                      required
                                    />
                                  </div>  
                                </div> 
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="invoicedate" class="form-label">Invoice Date</label>
                                  <input type="date" name="invoicedate" 
                                      class="form-control" 
                                      placeholder="Enter Invoice Date" id="invoicedate" required />
                                   
                                  </div>
                                  <div class="col mb-0">
                                    <label for="invoiceid" class="form-label">Invoice Id</label>
                                    
                                    <input type="number" name="invoiceid"  class="form-control"
                                      placeholder="Enter Invoice Id" id="invoiceid"   required /> 
                                  </div> 
                                  <input type="hidden" name="selectedProducts" id="selectedSingleProductsInput">
                                </div>
                                 
                              </div>
                              <div class="modal-footer">
                                <button type="button"  class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" id="singleSubmitBtn" class="btn btn-primary"><span class="btn-text">Generate</span></button> 
                              </div>
                              </form>
                            </div>
                          </div>
                        </div>
                        <!--Single invoice model end -->
                        
                        <!--multiInvoiceModel model start -->
                     <div class="modal fade" id="multiInvoiceModel" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                             <form id="multiInvoiceForm">
                              <div class="modal-header">
                                <h5 class="modal-title" id="modalCenterTitle">Generate 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="partyname" class="form-label">Party Name</label>
                                    <input
                                      type="text"
                                      id="partyname"
                                      class="form-control"
                                      name="partyname"
                                      placeholder="Enter Party Name"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="businessname" class="form-label">Business Name</label>
                                    <input
                                      type="text"
                                      id="businessname"
                                      name="businessname"
                                      class="form-control"
                                      placeholder="Enter Business Name"
                                      required
                                    />
                                  </div> 
                                </div>
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="partyaddress" class="form-label">Party Address</label>
                                    <input
                                      type="text"
                                      id="partyaddress"
                                      class="form-control"
                                      name="partyaddress"
                                      placeholder="Enter Party Address"
                                      required
                                    />
                                  </div>
                                  <div class="col mb-0">
                                    <label for="gstnumber" class="form-label">GST Number</label>
                                    <input
                                      type="text"
                                      id="gstnumber"
                                      name="gstnumber"
                                      class="form-control"
                                      placeholder="Enter GST Number e.g. 22AAAAA0000A1Z5"
                                      pattern="^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$"
                                      required
                                    />
                                  </div> 
                                       
                                </div> 
                                
                                <div class="row g-2 mb-3">
                                  <div class="col mb-0">
                                    <label for="invoicedate" class="form-label">Invoice Date</label>
                                  <input type="date" name="invoicedate" 
                                      class="form-control" 
                                      placeholder="Enter Invoice Date" id="invoicedate" required />
                                   
                                  </div>
                                  <div class="col mb-0">
                                    <label for="invoiceid" class="form-label">Invoice Id</label>
                                    
                                    <input type="number" name="invoiceid"  class="form-control"
                                      placeholder="Enter Invoice Id" id="invoiceid"   required /> 
                                  </div> 
                                  <input type="hidden" name="selectedProducts" id="selectedProductsInput">
                                </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">Generate</span></button> 
                              </div>
                              </form>
                            </div>
                          </div>
                        </div>
                        <!--multiInvoiceModel model 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>
	
	
<script>
$(function(){
    let existingImages = [], newImages = [];

    function renderPreview() {
        const box = $('#previewBox').empty();
        [...existingImages, ...newImages].forEach(src=>{
            let imgSrc = src instanceof File ? URL.createObjectURL(src) : 'uploads/'+src;
            let wrapper = $('<div style="position:relative;"></div>');
            wrapper.append(`<img src="${imgSrc}" style="height:80px;border-radius:4px;">`);
            let rm = $('<span style="position:absolute;top:0;right:0;background:rgba(0,0,0,0.5);color:white;padding:2px 5px;cursor:pointer;">&times;</span>');
            rm.click(()=>{ 
                if(src instanceof File) newImages.splice(newImages.indexOf(src),1);
                else existingImages.splice(existingImages.indexOf(src),1);
                renderPreview();
            });
            wrapper.append(rm);
            box.append(wrapper);
        });
        box.toggleClass('d-none', existingImages.length+newImages.length===0);
    }

    $('#editProduct').on('show.bs.modal', function(e){
        const btn = $(e.relatedTarget);
        const form = $('#productForm')[0];
        form.id.value = btn.data('id');
        form.name.value = btn.data('name');
        form.price.value = btn.data('price');
        form.sell_price.value = btn.data('sell');
        form.distributor.value = btn.data('distributor');
        form.quantity.value = btn.data('quantity');
        form.hsn_code.value = btn.data('hsncode');
        form.details.value = btn.data('details');

        existingImages = btn.data('images') || [];
        newImages = [];
        $('#formFileMultiple').val('');
        renderPreview();
    });

    $('#formFileMultiple').on('change', function(){
        newImages.push(...this.files);
        renderPreview();
    });

    $('#productForm').on('submit', function(e){
        e.preventDefault();
        const btn = $(this).find('button[type="submit"]');
        const origText = btn.text();
        btn.prop('disabled', true).text('Saving...');

        const fd = new FormData(this);
        newImages.forEach(f => fd.append('images[]', f));
        fd.set('existing_images', JSON.stringify(existingImages));
        fd.set('action', 'products');

        $.ajax({
            url: '',
            type: 'POST',
            data: fd,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(res){
                if(res.success){
                    $('#editProduct').modal('hide');
                    location.reload();
                } else {
                    alert('Error: ' + (res.error||'Unknown'));
                    btn.prop('disabled', false).text(origText);
                }
            },
            error: function(xhr, status, error){
                console.log(xhr.responseText);
                alert('AJAX error: ' + error);
                btn.prop('disabled', false).text(origText);
            }
        });
    });
});
</script>
<script>
$(function(){
    let deleteId = null;

     
    $('#deleteModal').on('show.bs.modal', function (e) {
        const btn = $(e.relatedTarget);
        deleteId = btn.data('id');
        $('#deleteName').text(btn.data('name'));
        $('#deleteSpinner').addClass('d-none');
        $('#confirmDeleteBtn').prop('disabled', false);
    });

    
    $('#confirmDeleteBtn').on('click', function () {
    if (!deleteId) return;

 
    $('#confirmDeleteBtn').addClass('d-none');
    $('#deleteSpinner').removeClass('d-none');

    $.ajax({
        url: '', // same page
        type: 'POST',
        dataType: 'json',
        data: {action: 'delete_product', id: deleteId},
        success: function (res) {
            if (res.success) {
                $('#deleteModal').modal('hide');
                location.reload();
            } else {
                alert('Delete failed: ' + (res.error || 'Unknown error'));
                 
                $('#confirmDeleteBtn').removeClass('d-none');
                $('#deleteSpinner').addClass('d-none');
            }
        },
        error: function (xhr, status, error) {
            alert('AJAX error: ' + error);
            $('#confirmDeleteBtn').removeClass('d-none');
            $('#deleteSpinner').addClass('d-none');
        }
    });
});
});
</script>
 

<script>
document.addEventListener('DOMContentLoaded', function () {

    // ✅ Master checkbox: सभी rows select/unselect
    const selectAll = document.getElementById('selectAll');
    selectAll.addEventListener('change', function () {
        document.querySelectorAll('.row-check').forEach(cb => {
            cb.checked = selectAll.checked;
        });
    });

    // ✅ Generate Invoice बटन क्लिक
    document.getElementById('generateInvoiceBtn').addEventListener('click', function () {
        const selectedData = [];
        document.querySelectorAll('.row-check:checked').forEach(cb => {
            selectedData.push({
                id: cb.dataset.id,
                name: cb.dataset.name,
                price: cb.dataset.price,
                sell_price: cb.dataset.sell,
                distributor: cb.dataset.distributor,
                quantity: cb.dataset.quantity,
                hsn_code:   p.hsncode,
                details: cb.dataset.details || ''   // 🟢 NEW: details add kiya
            });
        });

        if (selectedData.length === 0) {
            alert("कम से कम एक प्रोडक्ट select करें!");
            // मॉडल को ओपन होने से रोकने के लिए
            const modal = bootstrap.Modal.getInstance(document.getElementById('multiInvoiceModel'));
            if(modal) modal.hide();
            return;
        }

        // 🚩 अब selectedData को इनवॉइस मॉडल में डालें
        const nameInput        = document.querySelector('#multiInvoiceModel input[name="name"]');
        const priceInput       = document.querySelector('#multiInvoiceModel input[name="price"]');
        const sellInput        = document.querySelector('#multiInvoiceModel input[name="sell_price"]');
        const distributorInput = document.querySelector('#multiInvoiceModel input[name="distributor"]');
        const quantityInput    = document.querySelector('#multiInvoiceModel input[name="quantity"]');
        const detailsInput     = document.querySelector('#multiInvoiceModel textarea[name="details"]'); // 🟢 hidden textarea

        // Multiple rows ke liye combined values
        nameInput.value        = selectedData.map(p => p.name).join(', ');
        priceInput.value       = selectedData.reduce((sum, p) => sum + parseFloat(p.price), 0);
        sellInput.value        = selectedData.reduce((sum, p) => sum + parseFloat(p.sell_price), 0);
        distributorInput.value = selectedData.map(p => p.distributor).join(', ');
        quantityInput.value    = selectedData.reduce((sum, p) => sum + parseInt(p.quantity), 0);
        detailsInput.value     = selectedData.map(p => p.details).join('\n');  // 🟢 all details joined

        // 🔹 backend par poora array JSON me bhejna hai
        let hidden = document.getElementById('selectedProductsInput');
        if (!hidden) {
            hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'selectedProducts';
            hidden.id   = 'selectedProductsInput';
            document.querySelector('#multiInvoiceModel form').appendChild(hidden);
        }
        hidden.value = JSON.stringify(selectedData);
    });

});
</script>

<script>
$(function () {

    // सभी चुने हुए products collect करना
    function collectSelectedProducts() {
        const list = [];
        $('.row-check:checked').each(function () {
            list.push({
                id:         $(this).data('id'),
                name:       $(this).data('name'),
                price:      $(this).data('price'),
                sell_price: $(this).data('sell'),
                distributor:$(this).data('distributor'),
                quantity:   $(this).data('quantity'),
                details:    $(this).data('details') || ''
            });
        });
        return list;
    }

    // toastr डिफॉल्ट ऑप्शन (आप चाहें तो कस्टमाइज़ करें)
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: 'toast-top-right',
        timeOut: 3000
    };

    $('#multiInvoiceForm').on('submit', function (e) {
        e.preventDefault();

        const products = collectSelectedProducts();
        if (products.length === 0) {
            toastr.error('कृपया कम से कम एक product चुनें।');
            return;
        }

        $('#selectedProductsInput').val(JSON.stringify(products));
        const formData = $(this).serialize() + '&action=multi_invoices';

       const $btn = $('#multiSubmitBtn');

         
        $btn.prop('disabled', true)
            .find('.btn-text').text('Generating…'); 

        $.ajax({
            url: '',
            type: 'POST',
            dataType: 'json',
            data: formData,
            success: function (res) {
                 if (res.status === 'success') {
                    toastr.success('Invoice generated successfully!');
                     $('#multiInvoiceModal').modal('hide');
                    window.location.href = 'app-invoice.php?id=' + res.id;
                } else {
                    toastr.error('Error: ' + (res.msg || 'Failed'));
                } 
            },
            error: function () {
                toastr.error('Server error!');
            },
            complete: function () {
                $btn.prop('disabled', false)
                    .find('.btn-text').text('Generate');
            }
        });
    });
});
</script>

<script>
$(function () {
    $('#example2').DataTable();
 console.log('Click working 1');

    // ---- Single Invoice open handler ----
    $(document).on('click', '.openSingleInvoice', function () {
        const p = $(this).data();
console.log('Click working 2');
        // पहले फॉर्म को reset करें
        $('#singleInvoiceForm')[0].reset();

        // फिर hidden input में JSON डालें
        $('#selectedSingleProductsInput').val(JSON.stringify([{
            id:         p.id,
            name:       p.name,
            price:      p.price,
            sell_price: p.sell,
            distributor:p.distributor,
            quantity:   p.quantity,
            hsn_code:   p.hsncode,
            details:    p.details || ''
        }]));

        console.log('Hidden input value:',
            $('#selectedSingleProductsInput').val());
    });

    // ---- Form submit ----
    $('#singleInvoiceForm').on('submit', function (e) {
        e.preventDefault();

        const fd = new FormData(this);
        fd.append('action', 'multi_invoices'); // या single_invoice जैसा चाहें

        const $btn = $('#singleSubmitBtn');
        $btn.prop('disabled', true).find('.btn-text').text('Generating…');

        $.ajax({
            url: '', // <-- अपनी PHP फ़ाइल का path दें
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function (res) {
                if (res.status === 'success') {
                    toastr.success('Invoice generated successfully!');
                    $('#singleInvoiceModel').modal('hide');
                    window.location.href = 'app-invoice.php?id=' + res.id;
                } else {
                    toastr.error('Error: ' + (res.msg || 'Failed'));
                }
            },
            error: function () {
                toastr.error('Server error!');
            },
            complete: function () {
                $btn.prop('disabled', false).find('.btn-text').text('Generate');
            }
        });
    });
});
</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>