<?php
error_reporting(E_ERROR | E_PARSE); // temporarily hide warnings
session_start(); // Start session at the very top

// अगर user login नहीं है, redirect कर दो login page पर
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();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json'); 

    try {
        $uploadDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $imageNames = [];
        if (!empty($_FILES['images']['name'][0])) {
            foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
                if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                    $ext  = pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);
                    $file = uniqid('img_', true) . '.' . $ext;
                    move_uploaded_file($tmp, $uploadDir . $file);
                    $imageNames[] = $file;
                }
            }
        }

        // Prepare MySQLi statement
        // $stmt = $conn->prepare(
        //     "INSERT INTO products (name, price, sell_price, distributor, quantity, details, images)
        //      VALUES (?, ?, ?, ?, ?, ?, ?)"
        // );
        $stmt = $conn->prepare(
                "INSERT INTO products (name, price, sell_price, distributor, hsn_code, quantity, details, images)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
            );

        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }

        $images_json = json_encode($imageNames);

        $stmt->bind_param(
                "sddsssss", 
                $_POST['name'],
                $_POST['price'],
                $_POST['sell_price'],
                $_POST['distributor'],
                $_POST['hsn_code'],  
                $_POST['quantity'],
                $_POST['details'],
                $images_json
            );
        // $stmt->bind_param(
        //     "sddssss", 
        //     $_POST['name'],
        //     $_POST['price'],
        //     $_POST['sell_price'],
        //     $_POST['distributor'],
        //     $_POST['quantity'],
        //     $_POST['details'],
        //     $images_json
        // );

        if ($stmt->execute()) {
            echo json_encode(['status' => 1, 'message' => 'Product saved successfully']);
        } else {
            throw new Exception("Execute failed: " . $stmt->error);
        }

        $stmt->close();
        exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['status' => 0, 'message' => $e->getMessage()]);
        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/Drag-And-Drop/dist/imageuploadify.min.css" rel="stylesheet" />
	<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" />
	<!-- 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>Dashtrans - Bootstrap5 Admin Template</title>
  
</head>

<body class="bg-theme bg-theme2">
 <div id="loadingOverlay"
     style="
        display:none;                 /* डिफ़ॉल्ट रूप से छुपा */
        position:fixed;
        top:0; left:0;
        width:100%; height:100%;
        background:rgba(0,0,0,0.5);
        z-index:9999;
        display:flex;
        justify-content:center;
        align-items:center;">
   <button class="btn btn-primary" type="button" disabled>
      <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
      Loading...
   </button>
</div>
	<!--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">Dashtrans</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">eCommerce</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">Add New Product</li>
							</ol>
						</nav>
					</div> 
				</div>
				<!--end breadcrumb-->

              <div class="card">
				  <div class="card-body p-4">
					  <h5 class="card-title">Add New Product</h5>
					  <hr/>
                       <div class="form-body mt-4">
                            <form id="productForm" enctype="multipart/form-data">
					    <div class="row">
						   <div class="col-lg-8">
                           <div class="border border-3 p-4 rounded">
							<div class="mb-3">
								<label for="nameWithTitle" class="form-label">Product Title</label>
								<input type="text" class="form-control"
                                      id="nameWithTitle"
                                      name="name" 
                                      placeholder="Enter product title"
                                      required >
							  </div>
							  <div class="mb-3">
								<label for="details" class="form-label">Description</label>
								<textarea class="form-control" type="text" id="details" placeholder="Hi, please Fill Details?" name="details" rows="3"></textarea>
							  </div>
							  <div class="mb-3">
								<label for="formFileMultiple" class="form-label">Product Images</label>
								<input id="image-uploadify" type="file" id="formFileMultiple" name="images[]" accept=".png,.jpg,.jpeg,image/*" multiple>
							  </div>
                            </div>
						   </div>
						   <div class="col-lg-4">
							<div class="border border-3 p-4 rounded">
                              <div class="row g-3">
								<div class="col-12">
									<label for="priceWithTitle" class="form-label">Price</label>
									<input type="number" class="form-control" 
                                      id="priceWithTitle"
                                      name="price" 
                                      placeholder="Enter Price"
                                      required >
								  </div>
								  <div class="col-12">
									<label for="inputCompareatprice" class="form-label">Sell Price</label>
									<input type="number" class="form-control"id="sellpriceWithTitle"
                                      name="sell_price" 
                                      placeholder="Enter Sell Price"
                                      required >
								  </div>
								  <div class="col-12">
									<label for="distributernameWithTitle" class="form-label">Vendor Name</label>
									<input type="text" class="form-control"
									  id="distributernameWithTitle" 
                                      name="distributor"
                                      placeholder="Enter Distributer Name"
                                      required>
								  </div>
								  <div class="col-12">
									<label for="hsnCode" class="form-label">HSN Code</label>
									<input type="text" class="form-control"
									  id="hsnCode" 
                                      name="hsn_code"
                                      placeholder="Enter HSN Code"
                                      required>
								  </div>
								  <div class="col-12">
									<label for="inputStarPoints" class="form-label">Product Quantity</label>
									<input type="number" class="form-control" 
                                      id="quantityWithTitle"
                                      name="quantity" 
                                      placeholder="Enter Product Quantity"
                                      required>
								  </div>
								 <!-- <div class="col-12">-->
									<!--<label for="inputProductType" class="form-label">Product Type</label>-->
									<!--<select class="form-select" id="inputProductType">-->
									<!--	<option></option>-->
									<!--	<option value="1">One</option>-->
									<!--	<option value="2">Two</option>-->
									<!--	<option value="3">Three</option>-->
									<!--  </select>-->
								 <!-- </div>--> 
								  <div class="col-12">
									  <div class="d-grid">
                                         <button type="submit" class="btn btn-light">Save Product</button>
									  </div>
								  </div>
							  </div> 
						  </div>
						  </div>
					   </div><!--end row-->
					   </form>
					</div>
				  </div>
			  </div>

			</div>
		</div>
		<!--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/Drag-And-Drop/dist/imageuploadify.min.js"></script>
	<script>
		$(document).ready(function () {
			$('#image-uploadify').imageuploadify();
		})
	</script>
	<!--app JS-->
	<script src="assets/js/app.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> 
// $(function() {
//     let newImages = [];
 
//   // Submit form 
//   $('#productForm').on('submit', function(e){
//     e.preventDefault();
//     const fd = new FormData(this);
//     $.ajax({
//         url: '', // same page
//         type: 'POST',
//         data: fd,
//         processData: false,
//         contentType: false,
//         success: function(res){
//             toastr.success(res.message);
//             // Close modal
//             bootstrap.Modal.getInstance(document.getElementById('modalCenter')).hide();
//             // Reset form & preview
//             $('#productForm')[0].reset();
//             $('#previewBox').empty().hide();
//         },
//         error: function(xhr){
//              console.log("XHR response:", xhr.responseText);  
//             let msg = 'Error saving product';
//             try { msg = JSON.parse(xhr.responseText).message; } catch(e){}
//             toastr.error(msg);
//         }
//     });
// });
// });
$(function () {
    // toastr global options (top-right position)
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "4000"
    };
 $('#loadingOverlay').hide();
    $('#productForm').on('submit', function (e) {
        e.preventDefault();

        // 1️⃣ Loader दिखाओ
        $('#loadingOverlay').show();

        const fd = new FormData(this);
        $.ajax({
            url: '',  // अपने PHP save फाइल का path दें
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                // 2️⃣ Loader हटाओ
                $('#loadingOverlay').hide();

                // 3️⃣ Success toast
                const msg = (res && res.message) ? res.message : 'Product added successfully';
                toastr.success(msg);

                // 4️⃣ Form reset
                $('#productForm')[0].reset();

                // 5️⃣ Redirect
                setTimeout(function () {
                    window.location.href = 'ecommerce-products.php';
                }, 1500);
            },
            error: function (xhr) {
                // Loader हटाओ
                $('#loadingOverlay').hide();

                // Error message
                let msg = 'Error saving product';
                try {
                    const json = JSON.parse(xhr.responseText);
                    if (json.message) msg = json.message;
                } catch (e) {}
                toastr.error(msg);
            }
        });
    });
});

</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>