<?php

ob_start();
include("configa.php");

date_default_timezone_set('Asia/Dhaka');
$conn->query("SET time_zone = '+06:00'");



session_start();
if(!isset($_SESSION['username'])){header('location:index.php');}


$username = $_SESSION['username'] ?? '';
$password = $_SESSION['password'] ?? '';
$editor_idNo = $_SESSION['id_no'] ?? '';
$first_name = $_SESSION['first_name'] ?? '';
$last_name =  $_SESSION['last_name'] ?? '';
$shopName = $_SESSION['shopName'] ?? '';
$up = $_SESSION['up'] ?? '';
$upazila =  $_SESSION['upazila'] ?? '';
$district =  $_SESSION['district'] ?? '' ;       
$division = $_SESSION['division'] ?? '';
$address =  $_SESSION['address'] ?? '';
            


// function hasPermission($conn, $editor_idNo, $pageName) {
//     $sql = "SELECT 1 FROM pagepermission 
//             WHERE pageName = '$pageName' 
//             AND editor_idNo = '$editor_idNo' 
//             LIMIT 1";
//     $result = mysqli_query($conn, $sql);
//     return mysqli_num_rows($result) > 0;
// }
// if (hasPermission($conn, $editor_idNo, "product_add.php")) {      
// } else {
//     // ✅ এই পেজে পারমিশন নাই → রিডাইরেক্ট
//     header("Location: index.php");
//     exit;
// }






if (isset($_POST['submitButton'])) {


$hide = 1;


// রিসাইজ ফাংশন (384x256 px)
function resizeImage($source_path, $dest_path, $new_width = 384, $new_height = 256) {
    $image_info = getimagesize($source_path);
    $mime = $image_info['mime'];

    switch ($mime) {
        case 'image/jpeg':
            $src_image = imagecreatefromjpeg($source_path);
            break;
        case 'image/png':
            $src_image = imagecreatefrompng($source_path);
            break;
        case 'image/webp':
            $src_image = imagecreatefromwebp($source_path);
            break;
        default:
            return false; // Unsupported file type
    }

    $resized_image = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($resized_image, $src_image, 0, 0, 0, 0,
        $new_width, $new_height, imagesx($src_image), imagesy($src_image));

    switch ($mime) {
        case 'image/jpeg':
            imagejpeg($resized_image, $dest_path);
            break;
        case 'image/png':
            imagepng($resized_image, $dest_path);
            break;
        case 'image/webp':
            imagewebp($resized_image, $dest_path);
            break;
    }

    imagedestroy($src_image);
    imagedestroy($resized_image);
    return true;
}



if (isset($_FILES['category_picture'])) {
    $path = 'category/';
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }

    $category_pictures = [];

    foreach ($_FILES['category_picture']['name'] as $key => $for_category_picture_name) {
        if (!empty($for_category_picture_name)) {
            $uniq_num = uniqid();
            $new_name = $uniq_num . '_' . basename($for_category_picture_name);

            $tmp_name = $_FILES['category_picture']['tmp_name'][$key];
            $upload_path = $path . $new_name;

            $move = move_uploaded_file($tmp_name, $upload_path);

            if ($move && resizeImage($upload_path, $upload_path)) {
                $category_pictures[$key] = $new_name;
            } else {
                $category_pictures[$key] = null;
            }
            
        } else {
            if (isset($_POST['for_remove_image'][$key])) {
                $category_pictures[$key] = $_POST['for_remove_image'][$key];
            } else {
                $category_pictures[$key] = null;
            }
        }
    }

    // print_r($category_pictures); // Debug করতে চাইলে
}



if (isset($_FILES['small_picture'])) {
    $path = 'category/';
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }

    $small_pictures = [];

    foreach ($_FILES['small_picture']['name'] as $key => $for_small_picture_name) {
        if (!empty($for_small_picture_name)) {
            $uniq_num = uniqid();
            $new_name = $uniq_num . '_' . basename($for_small_picture_name);

            $tmp_name = $_FILES['small_picture']['tmp_name'][$key];
            $upload_path = $path . $new_name;

            $move = move_uploaded_file($tmp_name, $upload_path);

            if ($move && resizeImage($upload_path, $upload_path)) {
                $small_pictures[$key] = $new_name;
            } else {
                $small_pictures[$key] = null;
            }
        } else {
            if (isset($_POST['for_remove_image'][$key])) {
                $small_pictures[$key] = $_POST['for_remove_image'][$key];
            } else {
                $small_pictures[$key] = null;
            }
        }
    }

    // print_r($small_pictures); // Debug করতে চাইলে
}



if (isset($_FILES['small_picture_two'])) {
    $path = 'category/';
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }

    $small_picture_twos = [];

    foreach ($_FILES['small_picture_two']['name'] as $key => $for_small_picture_two_name) {
        if (!empty($for_small_picture_two_name)) {
            $uniq_num = uniqid();
            $new_name = $uniq_num . '_' . basename($for_small_picture_two_name);

            $tmp_name = $_FILES['small_picture_two']['tmp_name'][$key];
            $upload_path = $path . $new_name;

            $move = move_uploaded_file($tmp_name, $upload_path);

            if ($move && resizeImage($upload_path, $upload_path)) {
                $small_picture_twos[$key] = $new_name;
            } else {
                $small_picture_twos[$key] = null;
            }
        } else {
            if (isset($_POST['for_remove_image'][$key])) {
                $small_picture_twos[$key] = $_POST['for_remove_image'][$key];
            } else {
                $small_picture_twos[$key] = null;
            }
        }
    }

    // print_r($small_picture_twos); // Debug করতে চাইলে
}




if (isset($_FILES['small_picture_three'])) {
    $path = 'category/';
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }

    $small_picture_threes = [];

    foreach ($_FILES['small_picture_three']['name'] as $key => $for_small_picture_three_name) {
        if (!empty($for_small_picture_three_name)) {
            $uniq_num = uniqid();
            $new_name = $uniq_num . '_' . basename($for_small_picture_three_name);

            $tmp_name = $_FILES['small_picture_three']['tmp_name'][$key];
            $upload_path = $path . $new_name;

            $move = move_uploaded_file($tmp_name, $upload_path);

            if ($move && resizeImage($upload_path, $upload_path)) {
                $small_picture_threes[$key] = $new_name;
            } else {
                $small_picture_threes[$key] = null;
            }
        } else {
            if (isset($_POST['for_remove_image'][$key])) {
                $small_picture_threes[$key] = $_POST['for_remove_image'][$key];
            } else {
                $small_picture_threes[$key] = null;
            }
        }
    }

    // print_r($small_picture_threes); // Debug করতে চাইলে
}



    foreach ($_POST['category_name'] as $key => $value) {

        $id_no      = mysqli_real_escape_string($conn, $_POST['id_no']);
        $first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
        $last_name  = mysqli_real_escape_string($conn, $_POST['last_name']);
        $mobile     = mysqli_real_escape_string($conn, $_POST['mobile']);
        $division   = mysqli_real_escape_string($conn, $_POST['division']);
        $district   = mysqli_real_escape_string($conn, $_POST['district']);
        $upazila    = mysqli_real_escape_string($conn, $_POST['upazila']);
        $shopName   = mysqli_real_escape_string($conn, $_POST['shopName']);
        $address    = mysqli_real_escape_string($conn, $_POST['address']);

        // ইনপুটগুলো নিরাপদ করা
        $category_name = mysqli_real_escape_string($conn, $_POST['category_name'][$key]);
        $sub_category = mysqli_real_escape_string($conn, $_POST['sub_category'][$key]);
        $item = mysqli_real_escape_string($conn, $_POST['item'][$key]);
        $product_name = mysqli_real_escape_string($conn, $_POST['product_name'][$key]);




$product_banan_array = $_POST['product_banan'] ?? [];
$flattened = [];
foreach ($product_banan_array as $val) {
    if (trim($val) !== "") {
        $flattened[] = mysqli_real_escape_string($conn, $val);
    }
}
$product_banan = implode(',', $flattened);





        $person = mysqli_real_escape_string($conn, $_POST['person'][$key]);
        $gks = mysqli_real_escape_string($conn, $_POST['gks'][$key]);


        $approved = mysqli_real_escape_string($conn, $_POST['approved'][$key]);


          // $paikari_price = mysqli_real_escape_string($conn, $_POST['paikari_price'][$key]);

        $paikari_array = $_POST['paikari_price'] ?? [];
        if (is_array($paikari_array)) {
            $sanitized_paikari_array = array_map(function($val) use ($conn) {
                return mysqli_real_escape_string($conn, $val);
            }, $paikari_array);

            $paikari_price = implode(',', $sanitized_paikari_array);
        } else {
            $paikari_price = '';
        }



        $old_price_array = $_POST['price'] ?? [];
        if (is_array($old_price_array)) {
            $sanitized_old_price_array = array_map(function($val) use ($conn) {
                return mysqli_real_escape_string($conn, $val);
            }, $old_price_array);

            $price = implode(',', $sanitized_old_price_array);
        } else {
            $price = '';
        }




        $percent_array = $_POST['discount'] ?? [];
        if (is_array($percent_array)) {
            $sanitized_percent_array = array_map(function($val) use ($conn) {
                return mysqli_real_escape_string($conn, $val);
            }, $percent_array);

            $discount = implode(',', $sanitized_percent_array);
        } else {
            $discount = '';
        }



        $retail_price_array = $_POST['current_price'] ?? [];
        if (is_array($retail_price_array)) {
            $sanitized_retail_price_array = array_map(function($val) use ($conn) {
                return mysqli_real_escape_string($conn, $val);
            }, $retail_price_array);

            $current_price = implode(',', $sanitized_retail_price_array);
        } else {
            $current_price = '';
        }



        $weight_array = $_POST['weight'] ?? [];
        if (is_array($weight_array)) {
            $sanitized_weight_array = array_map(function($val) use ($conn) {
                return mysqli_real_escape_string($conn, $val);
            }, $weight_array);

            $weight = implode(',', $sanitized_weight_array);
        } else {
            $weight = '';
        }





        // $price = mysqli_real_escape_string($conn, $_POST['price'][$key]);
        // $discount = mysqli_real_escape_string($conn, $_POST['discount'][$key]);
        // $current_price = mysqli_real_escape_string($conn, $_POST['current_price'][$key]);
        $size = mysqli_real_escape_string($conn, $_POST['size'][$key]);

        $color = mysqli_real_escape_string($conn, $_POST['color'][$key]);

        // $weight = mysqli_real_escape_string($conn, $_POST['weight'][$key]);
        $quantity = mysqli_real_escape_string($conn, $_POST['quantity'][$key]);
        $description = mysqli_real_escape_string($conn, $_POST['description'][$key]);
        $specification = mysqli_real_escape_string($conn, $_POST['specification'][$key]);
        $vendor_info = mysqli_real_escape_string($conn, $_POST['vendor_info'][$key]);

        // $editor = mysqli_real_escape_string($conn, $_POST['editor'][$key]);

    $category_picture = isset($category_pictures[$key]) ? $category_pictures[$key] : '';
    $small_picture = isset($small_pictures[$key]) ? $small_pictures[$key] : '';
    $small_picture_two = isset($small_picture_twos[$key]) ? $small_picture_twos[$key] : '';
    $small_picture_three = isset($small_picture_threes[$key]) ? $small_picture_threes[$key] : '';


        // SQL ইনসার্ট
        $sql = "INSERT INTO goods_category (
        seller_idNo, first_name, last_name, mobile, division, district, upazila, shopName, address, category_name, sub_category, item, product_name, product_banan, person, category_picture, small_picture, gks, approved, paikari_price, small_picture_two, small_picture_three, price, discount, current_price, size, color, weight, quantity, refcommi, description, specification, vendor_info, editor, editor_idNo
        ) VALUES (
            '$id_no', '$first_name', '$last_name', '$mobile', '$division', '$district', '$upazila', '$shopName', '$address',
            '$category_name', '$sub_category', '$item', '$product_name', '$product_banan', '$person', '$category_picture', '$small_picture', '$gks', '$approved', '$paikari_price', '$small_picture_two', '$small_picture_three', '$price', '$discount', '$current_price', '$size', '$color', '$weight', '$quantity', '10', '$description', '$specification', '$vendor_info', '$first_name', '$editor_idNo'
        )";

        // কুয়েরি চালানো
        if (!mysqli_query($conn, $sql)) {
            echo "Error inserting row $key: " . mysqli_error($conn);
        }
    }

    echo "<center>প্রডাক্ট এন্ট্রি সফল হয়েছে।</center>";
}
?>


  <meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style type="text/css">

/**{
    background-color: #f0f8ff;
    font-family: SutonnyOMJ, Times New Roman;
}

*/




    /* অন্যান্য গুরুত্বপূর্ণ CSS রুলগুলো এখানে রাখতে পারেন */
    body {
      font-family: 'SutonnyOMJ', Arial, sans-serif;
       /* একটি বেস ফন্ট সাইজ সেট করুন */
       font-size: 14pt;
    }
 
 th{
    font-weight: normal;
    font-size: 16pt;
 }


.container{
  padding: 20pt;
  padding: 20pt;
}


.headLine{
    width: 2in;
    position: absolute;
    left: 50%;
    transform: translate(-50%,0);
    font-family: SutonnyOMJ;
    font-size: 15pt;
    
    background-color: #308DFF;
    padding: 6pt;
    border: solid 1pt;
    border-radius: 10pt;
    box-sizing: border-box;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}


  .product_box{
    width: 100%; 
    /*background-color: red;*/
    padding: 10pt;
  }



.addNew {
  width: 2in;
  background: linear-gradient(135deg, #1625EA, #F80F51);
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  /*padding: 12px;*/
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.addNew:hover {
  background: linear-gradient(135deg, #078301, #6A091B);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.addNew:active {
  transform: translateY(0);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}



.finalSubmitBtn {
  width: 2in;
  background: linear-gradient(135deg, #EF8701, #baf3db);
  color: #333;
  font-size: 16px;
  font-weight: 500;
  /*padding: 12px;*/
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.finalSubmitBtn:hover {
  background: linear-gradient(135deg, #7fd9ff, #92eac7);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.finalSubmitBtn:active {
  transform: translateY(0);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}


 p, input, textarea{
    width: 100%;
    height: 25pt;
    font-size: 13pt;
    padding: 5pt;
    font-family: sutonnyOMJ;
  }


table{
    width: 100%;
    table-layout: fixed;
}


  table, th, td{
    font-size: 11pt;
    border: solid 1pt;
    border-collapse: collapse;
    /*background-color: red;*/
    padding: 5pt;
  }



 th{
    background-color: #A3F9A9;
    color: blue;
  }


 td{
    background-color: #A3F9A9;
  }


input, textarea {
    background-color: transparent;
    transition: background-color 0.3s ease;
}



select, input{
    border: blue 1pt;
    font-size: 13pt;
}

@media screen and (max-width: 1024px) {
  .headLine {
    margin-bottom: 60pt;
    font-size: 12pt;
  }


}

</style>




<div class="container">


<div class="headLine">পণ্য এন্ট্রি</div><br>


<div class="product_box">

<form action="" method="POST" enctype="multipart/form-data">


<?php
$username = $_SESSION['username'] ?? '';
$password = $_SESSION['password'] ?? '';
$id_no = $_SESSION['id_no'] ?? '';
$first_name = $_SESSION['first_name'] ?? '';
$last_name =  $_SESSION['last_name'] ?? '';
$shopName = $_SESSION['shopName'] ?? '';
$up = $_SESSION['up'] ?? '';
$upazila =  $_SESSION['upazila'] ?? '';
$district =  $_SESSION['district'] ?? '' ;       
$division = $_SESSION['division'] ?? '';
$address =  $_SESSION['address'] ?? '';
?>


<div>

    <input hidden="" class="id_no" type="text" name="id_no" placeholder="আইডি নং দিন" 
    value="<?php echo htmlspecialchars($id_no); ?>">

    <input hidden="" class="first_name" type="text" name="first_name" placeholder="First Name"
    value="<?php echo htmlspecialchars($first_name); ?>">

    <input hidden="" class="last_name" type="text" name="last_name" placeholder="Last Name"
    value="<?php echo htmlspecialchars($last_name); ?>">

    <input hidden="" class="mobile" type="text" name="mobile" placeholder="Mobile" value="<?php echo htmlspecialchars($username); ?>">

    <input hidden="" class="division" type="text" name="division" placeholder="Division" value="<?php echo htmlspecialchars($division); ?>">

    <input hidden="" class="district" type="text" name="district" placeholder="District"
    value="<?php echo htmlspecialchars($district); ?>">

    <input hidden="" class="upazila" type="text" name="upazila" placeholder="Upazila"
    value="<?php echo htmlspecialchars($upazila); ?>">

    <input hidden="" class="up" type="text" name="up" placeholder="Union/UP"
    value="<?php echo htmlspecialchars($up); ?>">

    <input hidden="" class="shopName" type="text" name="shopName" placeholder="Shop Name"
    value="<?php echo htmlspecialchars($shopName); ?>">

    <input hidden="" class="address" type="text" name="address" placeholder="Address"
    value="<?php echo htmlspecialchars($address); ?>">


</div> 
<br>

<!-- id_no নং লিখলে ফেচ করে নিচের ইনপুটগুলোর ভ্যালূ অটো বসিয়ে দিবে। -->
<!-- <div> -->
   <!--  <input class="id_no" type="text" name="id_no" placeholder="আইডি নং দিন"> -->

<!-- Include CSS & JS for Select2 -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>



<!-- 
<select class="id_no" name="id_no" style="width:100%" required=""></select>

    <input hidden=""  class="first_name" type="text" name="first_name" placeholder="First Name">
    <input hidden=""  class="last_name" type="text" name="last_name" placeholder="Last Name">
    <input hidden=""  class="mobile" type="text" name="mobile" placeholder="Mobile">
    <input hidden=""  class="division" type="text" name="division" placeholder="Division">
    <input hidden=""  class="district" type="text" name="district" placeholder="District">
    <input hidden=""  class="upazila" type="text" name="upazila" placeholder="Upazila">
    <input hidden=""  class="up" type="text" name="up" placeholder="Union/UP">
    <input hidden=""  class="shopName" type="text" name="shopName" placeholder="Shop Name">
    <input hidden=""  class="address" type="text" name="address" placeholder="Address">
    <p hidden="" class="allData"></p>
</div>



<script type="text/javascript">

    $(document).ready(function() {
    $('.id_no').select2({
        placeholder: "নির্বাচন করুন",
        allowClear: true,
        minimumInputLength: 2, // 2 অক্ষর লিখলে search হবে
        ajax: {
            url: 'search_seller.php',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    search: params.term
                };
            },
            processResults: function(data) {
                // data must be array of {id, text}
                return {
                    results: data
                };
            },
            cache: true
        }
    });

    // যখন seller select করা হবে
    $('.id_no').on('select2:select', function(e) {
        const id_no = e.params.data.id;

        fetch("get_seller.php", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "id_no=" + encodeURIComponent(id_no)
        })
        .then(res => res.json())
        .then(res => {
            if(res.success) {
                document.querySelector(".first_name").value = res.data.first_name;
                document.querySelector(".last_name").value = res.data.last_name;
                document.querySelector(".mobile").value = res.data.mobile;
                document.querySelector(".division").value = res.data.division;
                document.querySelector(".district").value = res.data.district;
                document.querySelector(".upazila").value = res.data.upazila;
                document.querySelector(".up").value = res.data.up;
                document.querySelector(".shopName").value = res.data.shopName;
                document.querySelector(".address").value = res.data.address;

                document.querySelector(".allData").innerHTML = `
                    <p>
                    ID No: ${res.data.id_no}, ব্যবসা প্রতিষ্ঠানের নাম: ${res.data.shopName}, 
                    মালিকের নাম: ${res.data.first_name} ${res.data.last_name},
                    মোবাইল: ${res.data.mobile}, ঠিকানা: ${res.data.address},
                    বিভাগ: ${res.data.division}, জেলা: ${res.data.district},
                    উপজেলা: ${res.data.upazila}, ইউনিয়ন: ${res.data.up}
                    </p>`;
            } else {
                showAlert("⚠️ কোনো ডেটা পাওয়া যায়নি!");
            }
        });
    });
});

</script>


<style type="text/css">
    /* মোবাইল স্ক্রিনে Select2 ফন্ট সাইজ ছোট করা */
@media screen and (max-width: 768px) {
    /* select2 input field */
    .select2-container--default .select2-selection--single {
        font-size: 10pt !important; /* আপনার পছন্দ অনুযায়ী */
        height: 28px; /* লাইন হাইট ঠিক রাখতে */
        line-height: 28px;
    }

    /* selected item text */
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        font-size: 10pt !important;
        line-height: 28px;
    }

    /* arrow */
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 28px;
    }

}

/* মোবাইল স্ক্রীনে allData প্যারাগ্রাফের ফন্ট */
@media screen and (max-width: 768px) {
    .allData p {
        font-size: 12pt;       /* font size বড় করুন */
        line-height: 1.5;      /* লাইন স্পেস বাড়ানো */
        color: #333;           /* readable color */
        margin: 5px 0;         /* উপরের-নিচের স্পেস */
        word-wrap: break-word; /* লাইন টুড়ে যাবে ছোট স্ক্রিনে */
    }
}


</style>



 -->

<table style="margin-left: auto; margin-right: auto; width: 100%;">

<?php if(!isset($hide)){ ?>

<tbody id="myTbody">

<!-- হেডার row (বড় স্ক্রিনে) -->
<tr class="forTh">
    <th class="longTex">ক্যাটাগরী:</th>
    <th style="display: none;" class="longTex">Sub Category:</th>
    <th class="longTex">আইটেম:</th>
    <th class="longTex">পণ্যের নাম:</th>
    <th>পণ্যের বিভিন্ন বানান</th>
    <th class="longTex">ব্যবহারকারী:</th>
    <th class="longTex">ছবি-বড়:</th>
    <th class="longTex">ছবি-ছোট-১:</th>
    <th class="num">ছবি-ছোট-২:</th>
    <th class="num">ছবি-ছোট-৩:</th>
</tr>

<tr>
    <td data-label="ক্যাটাগরী:">
        <select class="category-select" name="category_name[]" style="width:100%" >
            <option value="">নির্বাচন করুন</option>
            <?php
            include('configa.php');
            $sql = "SELECT id, category_list FROM category ORDER BY category_list ASC";
            $result = $conn->query($sql);
            if($result){
                while($row = $result->fetch_assoc()){
                    echo '<option value="'.htmlspecialchars($row['category_list']).'">'.htmlspecialchars($row['category_list']).'</option>';
                }
            }
            ?>
        </select>
    </td>

    <td data-label="Sub Category:" style="display: none;">
        <input type="text" name="sub_category[]" placeholder="Sub Category">
    </td>

    <td data-label="আইটেম:">
        <input type="text" name="item[]" placeholder="আইটেম লিখুন">
    </td>

    <td data-label="পণ্যের নাম:">
        <input type="text" name="product_name[]" placeholder="পণ্যের নাম লিখুন" onblur="genaretGks();" required="">
    </td>

    <td data-label="পণ্যের বিভিন্ন বানান" class="tdProduct_banan">
        <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-1" >
        <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-2" >
        <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-3" >
        <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-4" >
    </td>

    <td data-label="ব্যবহারকারী:">
        <select name="person[]">
            <option value="">ব্যবহারকারী নির্বাচন করুন</option>
            <option value="সকল">সকল</option>
            <option value="পুরুষ">পুরুষ</option>
            <option value="মহিলা">মহিলা</option>
            <option value="শিশু-ছেলে">শিশু-ছেলে</option>
            <option value="শিশু-মেয়ে">শিশু-মেয়ে</option>
        </select>
    </td>

    <td data-label="ছবি-বড়:">
        <input type="file" name="category_picture[]" class="category_picture">
        <br>
        <img class="preview_category_picture" style="max-width: 100px; max-height: 100px; display:none;">
    </td>

    <td data-label="ছবি-ছোট-১:">
        <input type="file" name="small_picture[]" class="small_picture">
        <br>
        <img class="preview_small_picture" style="max-width: 100px; max-height: 100px; display:none;">
    </td>

    <td data-label="ছবি-ছোট-২:">
        <input type="file" name="small_picture_two[]" class="small_picture_two">
        <br>
        <img class="preview_small_picture_two" style="max-width: 100px; max-height: 100px; display:none;">
    </td>

    <td data-label="ছবি-ছোট-৩:">
        <input type="file" name="small_picture_three[]" class="small_picture_three">
        <br>
        <img class="preview_small_picture_three" style="max-width: 100px; max-height: 100px; display:none;">
    </td>
</tr>

<!-- Product details row -->
<tr class="forTh">
    <th class="longTex"> পণ্যের বিবরণ:</th>
    <th class="longTex">পণ্যের বৈশিষ্ট্য:</th>
    <th class="longTex">উৎপাদনকারী:</th>
    <th style="display: none;" class="num">GKS:</th>
    <th hidden="" class="num">Approved:</th>
    <th hidden="" class="num">Price:</th>
    <th hidden="" class="num">Discount (%):</th>
    <th hidden="">Current Price:</th>
    <th style="display: block;" class="size_th">সাইজ:</th>
    <th>পাইকারী মূল্য</th>
    <th>পার্সেন্ট</th>
    <th hidden="">পূর্বের মূল্য</th>
    <th>খুচরা মূল্য</th>
    <th>কালার</th>
    <th class="longTex">ওজন (কেজি):</th>
    <th style="display: none;" class="longTex">Quantity</th>
    <th hidden="">Editor:</th>
</tr>

<tr class="product-row" data-rowid="<?php echo $key; ?>">
    <td data-label="পণ্যের বিবরণ:">
        <textarea name="description[]" rows="3" cols="40" placeholder="পণ্যের বিবরণ লিখুন" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"></textarea>
    </td>
    <td data-label="পণ্যের বৈশিষ্ট্য:">
        <textarea name="specification[]" rows="3" cols="40" placeholder="পণ্যের বৈশিষ্ট্য লিখুন" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"></textarea>
    </td>
    <td data-label="উৎপাদনকারী:">
        <textarea name="vendor_info[]" rows="3" cols="40" placeholder="উৎপাদনকারী" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"></textarea>
    </td>
    <td data-label="GKS:" style="display: none;">
        <input type="text" class="gks" name="gks[]" placeholder="GKS">
    </td>
    <td hidden=""><input type="text" name="approved[]" value=""></td>
    <td style="display: block;" data-label="সাইজ:" class="size">
        <textarea name="size[]" placeholder="সাইজ" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);" onmousemove="auto_hieght(this);" onfocus="showSizeAlert(this);"oninput="auto_height(this);"></textarea>

      
    </td>
    <td data-label="পাইকারী মূল্য" class="tdPaikari"></td>
    <td data-label="পার্সেন্ট" class="tdPercent"></td>
    <td hidden="" class="tdOldPrice"></td>
    <td data-label="খুচরা মূল্য" class="tdRetailPrice"></td>
    <td data-label="কালার">
        <textarea name="color[]" placeholder="কালার" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);" onmousemove="auto_hieght(this);"></textarea>
    </td>
    <td data-label="ওজন (কেজি)" class="tdWeight"></td>
    <td style="display: none;"><input name="quantity[]" value="1" placeholder="Quantity"></td>
</tr>

</tbody>
<?php } ?>

</table>

<!-- CSS -->
<style>
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  padding: 6px;
  border: 1px solid #ddd;
  text-align: left;
}


@media screen and (max-width: 768px) {

    body {
      font-family: 'SutonnyOMJ', Arial, sans-serif;
       /* একটি বেস ফন্ট সাইজ সেট করুন */
       font-size: 14px;
    }

.container{
    width: 100%;
    padding: 5pt;
}

table, thead, tbody, th, td, tr {
    display: block;
}

/* বড় স্ক্রিনের th লুকানো */
.forTh{
    display: none;
}

thead {
    display: none;
}

tr {
    margin-bottom: 15px;
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 8px;
    background: #f9f9f9;
}

/* td flex layout */
td {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 10px;
    border: none;
    border-bottom: 1px solid #eee;
    flex-wrap: wrap; /* ছোট স্ক্রিনে লাইন ব্রেকের জন্য */
}

td:last-child {
    border-bottom: none;
}

/* লেবেল (data-label) স্টাইল */
td:before {
    content: attr(data-label);
    font-weight: 600;
    flex-basis: 40%;
    text-align: left;
    color: #333;
    margin-right: 10px;
}

/* ইনপুট, select, textarea স্টাইল */
input, textarea {
    flex: 1 1 55%; /* লেবেলের পাশে ফিট হবে */
    padding: 6px 8px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    box-sizing: border-box;
}

/* textarea auto height এবং responsive */
textarea {
    min-height: 40px;
    resize: vertical;
}

/* ছবি preview */
td img {
    margin-top: 5px;
    max-width: 100px;
    max-height: 100px;
    border-radius: 4px;
}

/* ছোট স্ক্রিনে select2 select ঠিকমতো দেখানোর জন্য */
/*.select2-container {
    width: 55% !important;
}
*/


}
</style>



<!-- JS: select2 + image preview -->
<script>
$(document).ready(function(){
    $('.category-select').select2({
        placeholder: "নির্বাচন করুন",
        allowClear: true
    });
});
document.addEventListener("DOMContentLoaded", function() {
    function previewImage(input, previewImgSelector) {
        input.addEventListener("change", function() {
            const file = input.files[0];
            const previewImg = input.closest("td").querySelector(previewImgSelector);

            if(file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    previewImg.style.display = "block";
                }
                reader.readAsDataURL(file);
            } else {
                // যদি Cancel করা হয় বা ফাইল না থাকে
                previewImg.src = "";          // src খালি করে দাও
                previewImg.style.display = "none"; // লুকিয়ে দাও
            }
        });
    }

    document.querySelectorAll(".category_picture").forEach(input => previewImage(input, ".preview_category_picture"));
    document.querySelectorAll(".small_picture").forEach(input => previewImage(input, ".preview_small_picture"));
    document.querySelectorAll(".small_picture_two").forEach(input => previewImage(input, ".preview_small_picture_two"));
    document.querySelectorAll(".small_picture_three").forEach(input => previewImage(input, ".preview_small_picture_three"));
});


</script>


<br>
<center>
<input class="finalSubmitBtn"  type="submit" value="Submit" name="submitButton">
</center>


</form>



    </div>



</div>






<!-- <script>
$(document).ready(function(){
    // Initialize Select2 for all category-select
    $('.category-select').select2({
        placeholder: "নির্বাচন করুন",
        allowClear: true,
        width: '100%'
    });

    function toggleSize($select) {
        const val = $select.val() ? $select.val().toLowerCase() : '';

        // শুধু ওই রো এর size input ধরবে
        const $row = $select.closest('tr').next().next(); // category row → next TH row → পরের input row
        const $sizeInput = $row.find('td.size');
        const $sizeInputTh = $row.find('th.size');


        // থ হেডার আলাদাভাবে ধরতে হবে (global থাকে)
        // const $sizeTh = $('th.size');

        if(val === 'পোষাক' || val === 'জুতা'){
            // $sizeTh.css('display', 'table-cell');
            $sizeInput.show();
            $sizeInputTh.show();
        } else {
            $sizeInput.hide();
            $sizeInputTh.hide();
        }
    }

    // Initial check for each select
    $('.category-select').each(function(){
        toggleSize($(this));
    });

    // Bind change event for each select
    $('.category-select').on('change', function(){
        toggleSize($(this));
    });
});

</script>
 -->



<script>
let rowKey = <?php echo json_encode($key); ?>;
</script>


<script>

let rowCounter = 0;

document.addEventListener("DOMContentLoaded", function () {
    const submitBtn = document.querySelector("button[name='submitBtn']");
    const table = document.querySelector("table");
    const tbody = table.querySelector("tbody");

    // Group রঙ পরিবর্তন ফাংশন
    function applyGroupColors() {
        const rows = tbody.querySelectorAll("tr");
        for (let i = 0; i < rows.length; i += 4) {
            const groupRows = [rows[i], rows[i + 1], rows[i + 2], rows[i + 3]];
            const color = Math.floor(i / 4) % 2 === 0 ? "#A3F9A9" : "#F9FBD0";
            groupRows.forEach(row => {
                if (row) {
                    row.querySelectorAll("th, td").forEach(cell => {
                        cell.style.backgroundColor = color;
                    });
                }
            });
        }
    }

    // নতুন গ্রুপ যোগ
    submitBtn.addEventListener("click", function (e) {
        e.preventDefault();

        const groupHTML = `
<tr>
    <th class="longTex">ক্যাটাগরী:</th>
    <th style="display: none;" class="longTex">Sub Category:</th>
    <th class="longTex">আইটেম:</th>
    <th class="longTex">পণ্যের নাম:</th>
    <th>পণ্যের বিভিন্ন বানান</th>
    <th class="longTex">ব্যবহারকারী:</th>
    <th class="longTex">ছবি-বড়:</th>
    <th class="longTex">ছবি-ছোট-১:</th>
    <th class="num">ছবি-ছোট-২:</th>
    <th class="num">ছবি-ছোট-৩:</th>
</tr>


<tr>
<td class="category">

  <select class="category-select" name="category_name[]" style="width:100%">
    <option value="">নির্বাচন করুন</option>
    <?php
    include('configa.php');
    $sql = "SELECT id, category_list FROM category ORDER BY category_list ASC";
    $result = $conn->query($sql);
    if($result){
        while($row = $result->fetch_assoc()){
            echo '<option value="'.htmlspecialchars($row['category_list']).'">'.htmlspecialchars($row['category_list']).'</option>';
        }
    }
    ?>
  </select>


</td>

<td style="display: none;"><input type="text" name="sub_category[]" placeholder="Sub Category"></td>

<td><input type="text" name="item[]" placeholder="আইটেম লিখুন"></td>

<td><input type="text" name="product_name[]" placeholder="পণ্যের নাম লিখুন"></td>

<td class="tdProduct_banan">
    <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-1">
    <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-2">
    <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-3">
    <input type="text" name="product_banan[]" placeholder="পণ্যের বানান-4">
</td>



<td>
  <select name="person[]">
    <option value="">ব্যবহারকারী নির্বাচন করুন</option>
    <option value="সকল">সকল</option>
    <option value="পুরুষ">পুরুষ</option>
    <option value="মহিলা">মহিলা</option>
    <option value="শিশু-ছেলে">শিশু-ছেলে</option>
    <option value="শিশু-মেয়ে">শিশু-মেয়ে</option>
  </select>
</td>

<td><input type="file" name="category_picture[]" placeholder="ছবি-বড় আপলোড করুন"></td>
<td><input type="file" name="small_picture[]" placeholder="ছবি-ছোট-১ আপলোড করুন"></td>
<td><input type="file" name="small_picture_two[]" placeholder="ছবি-ছোট-২ আপলোড করুন"></td>
<td><input type="file" name="small_picture_three[]" placeholder="ছবি-ছোট-৩ আপলোড করুন"></td>
</tr>



<tr>
<th class="longTex"> পণ্যের বিবরণ:</th>
<th class="longTex">পণ্যের বৈশিষ্ট্য:</th>
<th class="longTex">উৎপাদনকারী:</th>
<th hidden="" class="num">GKS:</th>
<th hidden="" class="num">Approved:</th>
<th hidden=""class="num">Price:</th>
<th hidden=""class="num">Discount (%):</th>
<th hidden="">Current Price:</th>
<th style="display: block;" class="size_th">সাইজ:</th>
<th>পাইকারী মূল্য</th>
<th>পার্সেন্ট</th>
<th hidden="">পূর্বের মূল্য</th>
<th>খুচরা মূল্য</th>
<th>কালার</th>
<th class="longTex">ওজন (কেজি):</th>
<th style="display: none;" class="longTex">Quantity</th>
<th hidden="">Editor:</th>
</tr>


<tr class="product-row" data-rowid="${rowCounter}">
<td><textarea name="description[]" rows="3" cols="40" placeholder="পণ্যের বিবরণ লিখুন" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"></textarea></td>
<td><textarea name="specification[]" rows="3" cols="40" placeholder="পণ্যের বৈশিষ্ট্য লিখুন" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"></textarea></td>
<td><textarea name="vendor_info[]" rows="3" cols="40" placeholder="উৎপাদনকারী" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"></textarea></td>
<td hidden=""><input type="text" name="gks[]" placeholder="GKS"></td>
<td hidden=""><input type="text" name="approved[]" value="approved" placeholder="Approved"></td>
<td style="display: block;" class="size">
    <textarea name="size[]" placeholder="সাইজ" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"  onmousemove="auto_hieght(this);"></textarea></td>
 <td class="tdPaikari"></td>
 <td class="tdPercent"></td>
 <td hidden="" class="tdOldPrice"></td>
 <td class="tdRetailPrice"></td>
<td>
    <textarea name="color[]" placeholder="কালার" onkeypress="auto_hieght(this);" onkeyup="auto_hieght(this);"  onmousemove="auto_hieght(this);"></textarea>
</td>

<td class="tdWeight">
<span class="delete"><i class="fas fa-trash"></i></span>
</td>


<td style="display: none;"><input name="quantity[]" value="1" placeholder="Quantity"></td>
<td hidden=""><input type="text" name="editor[]" placeholder="Editor"></td>
</tr>
`;

        tbody.insertAdjacentHTML("beforeend", groupHTML);


// -------------------------------------------

    // এই অংশটি স্ট্যাটিক রো এর জন্যেও একবার লেখা হয়েছে। একই কোড ডায়নামিকের জন্য আবার লেখা হলো।
    // প্রতিটি row এর জন্য ইনপুট বানানোর ফাংশন
        // প্রতিটি row এর জন্য ইনপুট বানানোর ফাংশন
    // function updatePaikariInputs(row) {
    //     const sizeTextarea = row.querySelector('textarea[name="size[]"]');
    //     const tdPaikari = row.querySelector('.tdPaikari');
    //     const tdPercent = row.querySelector('.tdPercent');
    //     const tdOldPrice = row.querySelector('.tdOldPrice');
    //     const tdRetailPrice = row.querySelector('.tdRetailPrice');
    //     const tdWeight = row.querySelector('.tdWeight'); // নতুন tdWeight

    //     if (!sizeTextarea || !tdPaikari || !tdPercent || !tdOldPrice || !tdRetailPrice || !tdWeight) return;

    //     // আগের ইনপুটগুলো মুছে দাও
    //     tdPaikari.innerHTML = "";
    //     tdPercent.innerHTML = "";
    //     tdOldPrice.innerHTML = "";
    //     tdRetailPrice.innerHTML = "";
    //     tdWeight.innerHTML = ""; // tdWeight খালি করো

    //     const sizes = sizeTextarea.value
    //         .split(',')
    //         .map(s => s.trim())
    //         .filter(s => s !== '');

    //     // helper function → old_price + percent দিয়ে retail হিসাব + retail দিয়ে old_price হিসাব
    //     function attachReverseCalc(oldInput, percentInput, retailInput) {
    //         function calculateOldPrice() {
    //             const retailVal = parseFloat(retailInput.value) || 0;
    //             const percentVal = parseFloat(percentInput.value) || 0;
    //             if (percentVal < 100) {
    //                 const oldVal = retailVal * 100 / (100 - percentVal);
    //                 oldInput.value = Math.round(oldVal);
    //             } else {
    //                 oldInput.value = 0;
    //             }
    //         }

    //         retailInput.addEventListener("input", calculateOldPrice);

    //         function calculateRetail() {
    //             const oldVal = parseFloat(oldInput.value) || 0;
    //             const percentVal = parseFloat(percentInput.value) || 0;
    //             const retailVal = oldVal - (oldVal * percentVal / 100);
    //             retailInput.value = Math.round(retailVal);
    //         }

    //         oldInput.addEventListener("input", calculateRetail);
    //         percentInput.addEventListener("input", calculateRetail);
    //     }

    //     if (sizes.length > 0) {
    //         sizes.forEach((size) => {
    //             // পাইকারী মূল্য
    //             const inputPaikari = document.createElement("input");
    //             inputPaikari.type = "number";
    //             inputPaikari.placeholder = "পাইকারী মূল্য (" + size + ")";
    //             inputPaikari.name = "paikari_price[]";
    //             inputPaikari.style.margin = "2px";
    //             inputPaikari.style.width = "100%";
    //             tdPaikari.appendChild(inputPaikari);

    //             // পুরাতন মূল্য
    //             const inputOldPrice = document.createElement("input");
    //             inputOldPrice.type = "number";
    //             inputOldPrice.placeholder = "পুরাতন মূল্য (" + size + ")";
    //             inputOldPrice.name = "price[]";
    //             inputOldPrice.style.margin = "2px";
    //             inputOldPrice.style.width = "100%";
    //             tdOldPrice.appendChild(inputOldPrice);

    //             // পার্সেন্ট
    //             const inputPercent = document.createElement("input");
    //             inputPercent.type = "number";
    //             inputPercent.placeholder = "পার্সেন্ট (" + size + ")";
    //             inputPercent.name = "discount[]";
    //             inputPercent.style.margin = "2px";
    //             inputPercent.style.width = "100%";
    //             tdPercent.appendChild(inputPercent);

    //             // খুচরা মূল্য
    //             const inputRetailPrice = document.createElement("input");
    //             inputRetailPrice.type = "number";
    //             inputRetailPrice.placeholder = "খুচরা মূল্য (" + size + ")";
    //             inputRetailPrice.name = "current_price[]";
    //             inputRetailPrice.style.margin = "2px";
    //             inputRetailPrice.style.width = "100%";
    //             tdRetailPrice.appendChild(inputRetailPrice);

    //             // weight ইনপুট
    //             const inputWeight = document.createElement("input");
    //             inputWeight.type = "text";
    //             inputWeight.placeholder = "ওজন (" + size + ")";
    //             inputWeight.name = "weight[]";
    //             inputWeight.style.margin = "2px";
    //             inputWeight.style.width = "100%";
    //             tdWeight.appendChild(inputWeight);

    //             attachReverseCalc(inputOldPrice, inputPercent, inputRetailPrice);
    //         });
    //     } else {
    //         // default ইনপুট (যদি size[] খালি হয়)
    //         const inputPaikari = document.createElement("input");
    //         inputPaikari.type = "number";
    //         inputPaikari.placeholder = "পাইকারী মূল্য";
    //         inputPaikari.name = "paikari_price[]";
    //         inputPaikari.style.margin = "2px";
    //         inputPaikari.style.width = "100%";
    //         tdPaikari.appendChild(inputPaikari);

    //         const inputOldPrice = document.createElement("input");
    //         inputOldPrice.type = "number";
    //         inputOldPrice.placeholder = "পুরাতন মূল্য";
    //         inputOldPrice.name = "price[]";
    //         inputOldPrice.style.margin = "2px";
    //         inputOldPrice.style.width = "100%";
    //         tdOldPrice.appendChild(inputOldPrice);

    //         const inputPercent = document.createElement("input");
    //         inputPercent.type = "number";
    //         inputPercent.placeholder = "পার্সেন্ট";
    //         inputPercent.name = "discount[]";
    //         inputPercent.style.margin = "2px";
    //         inputPercent.style.width = "100%";
    //         tdPercent.appendChild(inputPercent);

    //         const inputRetailPrice = document.createElement("input");
    //         inputRetailPrice.type = "number";
    //         inputRetailPrice.placeholder = "খুচরা মূল্য";
    //         inputRetailPrice.name = "current_price[]";
    //         inputRetailPrice.style.margin = "2px";
    //         inputRetailPrice.style.width = "100%";
    //         tdRetailPrice.appendChild(inputRetailPrice);

    //         // default weight ইনপুট
    //         const inputWeight = document.createElement("input");
    //         inputWeight.type = "text";
    //         inputWeight.placeholder = "ওজন";
    //         inputWeight.name = "weight[]";
    //         inputWeight.style.margin = "2px";
    //         inputWeight.style.width = "100%";
    //         tdWeight.appendChild(inputWeight);

    //         attachReverseCalc(inputOldPrice, inputPercent, inputRetailPrice);
    //     }
    // }


    // // page load এ সব row initialize করো
    // document.querySelectorAll('.product-row').forEach(function (row) {
    //     updatePaikariInputs(row);
    // });

    // // size textarea পরিবর্তন হলে update করো
    // document.addEventListener('input', function (e) {
    //     if (e.target.matches('textarea[name="size[]"]')) {
    //         const row = e.target.closest('tr');
    //         updatePaikariInputs(row);
    //     }
    // });


// -------------------------------------------

        // নতুন সিলেক্টে Select2 চালানো
        $(tbody).find(".category-select").select2({
            placeholder: "নির্বাচন করুন",
            allowClear: true
        });

        applyGroupColors();

        
    });


// -----------------------------

  $(document).ready(function(){
      $('#category-select').select2({
          placeholder: "নির্বাচন করুন",
          allowClear: true
      });
  });

// -----------------------------

    // ডিলিট বাটন
    table.addEventListener("click", function (e) {
        if (e.target.closest(".delete")) {
            const deleteRow = e.target.closest("tr");
            if (!deleteRow) return;
            const row3 = deleteRow.previousElementSibling;
            const row2 = row3?.previousElementSibling;
            const row1 = row2?.previousElementSibling;
            [row1, row2, row3, deleteRow].forEach(row => {
                if (row && row.parentNode) {
                    row.parentNode.removeChild(row);
                }
            });
            applyGroupColors();
        }
    });
});




document.addEventListener("DOMContentLoaded", () => {
    // শুরুতেই ইনপুট/টেক্সটএরিয়ার ব্যাকগ্রাউন্ড ট্রান্সপারেন্ট এবং ডিফল্ট বোর্ডার কালার সেট করা
    document.querySelectorAll("input, textarea").forEach(input => {
        input.style.backgroundColor = "transparent";
        input.style.borderColor = ""; // ডিফল্ট রঙ (বা আপনি চাইলে স্পেসিফিক দিতে পারেন)
    });

    // ডাইনামিক ইনপুটের জন্য ইভেন্ট ডেলিগেশন
    document.body.addEventListener("input", e => {
        if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") {
            e.target.style.backgroundColor = "white";
            e.target.style.borderColor = "red"; // লেখা শুরু হলে বোর্ডার ব্লু হবে
        }
    });

    document.body.addEventListener("focusout", e => {
        if ((e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") && e.target.value.trim() === "") {
            e.target.style.backgroundColor = "transparent";
            e.target.style.borderColor = ""; // ফাঁকা হলে বোর্ডার রঙ রিসেট হবে
        }
    });
});




 function auto_hieght(element) {
      element.style.height = "5px";
      element.style.height = (element.scrollHeight)+"px";
    }





function validateWeight(input) {
    const value = input.value;
    const pattern = /^\d{0,2}(\.\d*)?$/;

    if (!pattern.test(value)) {
        input.setCustomValidity("এখানে কেজি হবে, গ্রাম নয়।");
        input.reportValidity();
    } else {
        input.setCustomValidity(""); // valid হলে মেসেজ মুছে ফেলি
    }
}

</script>


<!-- 
<script>
document.addEventListener("DOMContentLoaded", function () {

// এই অংশটি স্ট্যাটিক রো এর জন্যেও একবার লেখা হয়েছে। একই কোড ডায়নামিকের জন্য আবার লেখা হলো।
    // প্রতিটি row এর জন্য ইনপুট বানানোর ফাংশন
    function updatePaikariInputs(row) {
        const sizeTextarea = row.querySelector('textarea[name="size[]"]');
        const tdPaikari = row.querySelector('.tdPaikari');
        const tdPercent = row.querySelector('.tdPercent');
        const tdOldPrice = row.querySelector('.tdOldPrice');
        const tdRetailPrice = row.querySelector('.tdRetailPrice');

        if (!sizeTextarea || !tdPaikari || !tdPercent || !tdOldPrice || !tdRetailPrice) return;

        // আগের ইনপুটগুলো মুছে দাও
        tdPaikari.innerHTML = "";
        tdPercent.innerHTML = "";
        tdOldPrice.innerHTML = "";
        tdRetailPrice.innerHTML = "";

        const sizes = sizeTextarea.value
            .split(',')
            .map(s => s.trim())
            .filter(s => s !== '');

        // helper function → old_price + percent দিয়ে retail হিসাব + retail দিয়ে old_price হিসাব
        function attachReverseCalc(oldInput, percentInput, retailInput) {
            // retail পরিবর্তন হলে old_price হিসাব করো, percent অপরিবর্তিত
            function calculateOldPrice() {
                const retailVal = parseFloat(retailInput.value) || 0;
                const percentVal = parseFloat(percentInput.value) || 0;
                if (percentVal < 100) {
                    const oldVal = retailVal * 100 / (100 - percentVal);
                    oldInput.value = Math.round(oldVal);
                } else {
                    oldInput.value = 0;
                }
            }

            retailInput.addEventListener("input", calculateOldPrice);

            // old_price বা percent পরিবর্তন হলে retail হিসাব করো
            function calculateRetail() {
                const oldVal = parseFloat(oldInput.value) || 0;
                const percentVal = parseFloat(percentInput.value) || 0;
                const retailVal = oldVal - (oldVal * percentVal / 100);
                retailInput.value = Math.round(retailVal);
            }

            oldInput.addEventListener("input", calculateRetail);
            percentInput.addEventListener("input", calculateRetail);
        }

        if (sizes.length > 0) {
            sizes.forEach((size) => {
                // পাইকারী মূল্য
                const inputPaikari = document.createElement("input");
                inputPaikari.type = "number";
                inputPaikari.placeholder = "পাইকারী মূল্য (" + size + ")";
                inputPaikari.name = "paikari_price[]";
                inputPaikari.style.margin = "2px";
                inputPaikari.style.width = "100%";
                tdPaikari.appendChild(inputPaikari);

                // পুরাতন মূল্য
                const inputOldPrice = document.createElement("input");
                inputOldPrice.type = "number";
                inputOldPrice.placeholder = "পুরাতন মূল্য (" + size + ")";
                inputOldPrice.name = "price[]";
                inputOldPrice.style.margin = "2px";
                inputOldPrice.style.width = "100%";
                tdOldPrice.appendChild(inputOldPrice);

                // পার্সেন্ট
                const inputPercent = document.createElement("input");
                inputPercent.type = "number";
                inputPercent.placeholder = "পার্সেন্ট (" + size + ")";
                inputPercent.name = "discount[]";
                inputPercent.style.margin = "2px";
                inputPercent.style.width = "100%";
                tdPercent.appendChild(inputPercent);

                // খুচরা মূল্য
                const inputRetailPrice = document.createElement("input");
                inputRetailPrice.type = "number";
                inputRetailPrice.placeholder = "খুচরা মূল্য (" + size + ")";
                inputRetailPrice.name = "current_price[]";
                inputRetailPrice.style.margin = "2px";
                inputRetailPrice.style.width = "100%";
                tdRetailPrice.appendChild(inputRetailPrice);

                attachReverseCalc(inputOldPrice, inputPercent, inputRetailPrice);
            });
        } else {
            // default ইনপুট (যদি size[] খালি হয়)
            const inputPaikari = document.createElement("input");
            inputPaikari.type = "number";
            inputPaikari.placeholder = "পাইকারী মূল্য";
            inputPaikari.name = "paikari_price[]";
            inputPaikari.style.margin = "2px";
            inputPaikari.style.width = "100%";
            tdPaikari.appendChild(inputPaikari);

            const inputOldPrice = document.createElement("input");
            inputOldPrice.type = "number";
            inputOldPrice.placeholder = "পুরাতন মূল্য";
            inputOldPrice.name = "price[]";
            inputOldPrice.style.margin = "2px";
            inputOldPrice.style.width = "100%";
            tdOldPrice.appendChild(inputOldPrice);

            const inputPercent = document.createElement("input");
            inputPercent.type = "number";
            inputPercent.placeholder = "পার্সেন্ট";
            inputPercent.name = "discount[]";
            inputPercent.style.margin = "2px";
            inputPercent.style.width = "100%";
            tdPercent.appendChild(inputPercent);

            const inputRetailPrice = document.createElement("input");
            inputRetailPrice.type = "number";
            inputRetailPrice.placeholder = "খুচরা মূল্য";
            inputRetailPrice.name = "current_price[]";
            inputRetailPrice.style.margin = "2px";
            inputRetailPrice.style.width = "100%";
            tdRetailPrice.appendChild(inputRetailPrice);

            attachReverseCalc(inputOldPrice, inputPercent, inputRetailPrice);
        }
    }

    // page load এ সব row initialize করো
    document.querySelectorAll('.product-row').forEach(function (row) {
        updatePaikariInputs(row);
    });

    // size textarea পরিবর্তন হলে update করো
    document.addEventListener('input', function (e) {
        if (e.target.matches('textarea[name="size[]"]')) {
            const row = e.target.closest('tr');
            updatePaikariInputs(row);
        }
    });

});
</script>
 -->


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

    // প্রতিটি row এর জন্য ইনপুট বানানোর ফাংশন
    function updatePaikariInputs(row) {
        const sizeTextarea = row.querySelector('textarea[name="size[]"]');
        const tdPaikari = row.querySelector('.tdPaikari');
        const tdPercent = row.querySelector('.tdPercent');
        const tdOldPrice = row.querySelector('.tdOldPrice');
        const tdRetailPrice = row.querySelector('.tdRetailPrice');
        const tdWeight = row.querySelector('.tdWeight'); // নতুন tdWeight

        if (!sizeTextarea || !tdPaikari || !tdPercent || !tdOldPrice || !tdRetailPrice || !tdWeight) return;

        // আগের ইনপুটগুলো মুছে দাও
        tdPaikari.innerHTML = "";
        tdPercent.innerHTML = "";
        tdOldPrice.innerHTML = "";
        tdRetailPrice.innerHTML = "";
        tdWeight.innerHTML = ""; // tdWeight খালি করো

        const sizes = sizeTextarea.value
            .split(',')
            .map(s => s.trim())
            .filter(s => s !== '');

        // helper function → old_price + percent দিয়ে retail হিসাব + retail দিয়ে old_price হিসাব
        function attachReverseCalc(oldInput, percentInput, retailInput) {
            function calculateOldPrice() {
                const retailVal = parseFloat(retailInput.value) || 0;
                const percentVal = parseFloat(percentInput.value) || 0;
                if (percentVal < 100) {
                    const oldVal = retailVal * 100 / (100 - percentVal);
                    oldInput.value = Math.round(oldVal);
                } else {
                    oldInput.value = 0;
                }
            }

            retailInput.addEventListener("input", calculateOldPrice);

            function calculateRetail() {
                const oldVal = parseFloat(oldInput.value) || 0;
                const percentVal = parseFloat(percentInput.value) || 0;
                const retailVal = oldVal - (oldVal * percentVal / 100);
                retailInput.value = Math.round(retailVal);
            }

            oldInput.addEventListener("input", calculateRetail);
            percentInput.addEventListener("input", calculateRetail);
        }

        if (sizes.length > 0) {
            sizes.forEach((size) => {
                // পাইকারী মূল্য
                const inputPaikari = document.createElement("input");
                inputPaikari.type = "number";
                inputPaikari.placeholder = "পাইকারী মূল্য (" + size + ")";
                inputPaikari.name = "paikari_price[]";
                inputPaikari.style.margin = "2px";
                inputPaikari.style.width = "100%";
                tdPaikari.appendChild(inputPaikari);

                // পুরাতন মূল্য
                const inputOldPrice = document.createElement("input");
                inputOldPrice.type = "number";
                inputOldPrice.placeholder = "পুরাতন মূল্য (" + size + ")";
                inputOldPrice.name = "price[]";
                inputOldPrice.style.margin = "2px";
                inputOldPrice.style.width = "100%";
                tdOldPrice.appendChild(inputOldPrice);

                // পার্সেন্ট
                const inputPercent = document.createElement("input");
                inputPercent.type = "number";
                inputPercent.placeholder = "পার্সেন্ট (" + size + ")";
                inputPercent.name = "discount[]";
                inputPercent.style.margin = "2px";
                inputPercent.style.width = "100%";
                tdPercent.appendChild(inputPercent);

                // খুচরা মূল্য
                const inputRetailPrice = document.createElement("input");
                inputRetailPrice.type = "number";
                inputRetailPrice.placeholder = "খুচরা মূল্য (" + size + ")";
                inputRetailPrice.name = "current_price[]";
                inputRetailPrice.style.margin = "2px";
                inputRetailPrice.style.width = "100%";
                tdRetailPrice.appendChild(inputRetailPrice);

                // weight ইনপুট
                // const inputWeight = document.createElement("input");
                // inputWeight.type = "text";
                // inputWeight.placeholder = "ওজন (" + size + ")";
                // inputWeight.name = "weight[]";
                // inputWeight.style.margin = "2px";
                // inputWeight.style.width = "100%";
                // tdWeight.appendChild(inputWeight);


                // default weight ইনপুট
                const inputWeight = document.createElement("input");
                inputWeight.type = "text";
                inputWeight.placeholder = "ওজন";
                inputWeight.name = "weight[]";
                inputWeight.style.margin = "2px";
                inputWeight.style.width = "100%";
                tdWeight.appendChild(inputWeight);

                // ইংরেজি সংখ্যা এবং দশমিক ছাড়া অন্য অক্ষর হলে এলার্ট
                inputWeight.addEventListener("input", function() {
                    const value = inputWeight.value;

                    // Regex: শুধুমাত্র 0-9 এবং একটি মাত্র দশমিক
                    if(/[^0-9.]/.test(value)) {
                        showAlert("দয়া করে শুধুমাত্র ইংরেজি সংখ্যা লিখুন।");
                        // invalid character মুছে ফেলা
                        inputWeight.value = value.replace(/[^0-9.]/g, '');
                    }

                    // দশমিক একাধিক হলে শুধু প্রথমট রাখো
                    const parts = inputWeight.value.split('.');
                    if(parts.length > 2) {
                        inputWeight.value = parts[0] + '.' + parts.slice(1).join('');
                    }
                });






                attachReverseCalc(inputOldPrice, inputPercent, inputRetailPrice);
            });
        } else {
            // default ইনপুট (যদি size[] খালি হয়)
            const inputPaikari = document.createElement("input");
            inputPaikari.type = "number";
            inputPaikari.placeholder = "পাইকারী মূল্য";
            inputPaikari.name = "paikari_price[]";
            inputPaikari.style.margin = "2px";
            inputPaikari.style.width = "100%";
            tdPaikari.appendChild(inputPaikari);

            const inputOldPrice = document.createElement("input");
            inputOldPrice.type = "number";
            inputOldPrice.placeholder = "পুরাতন মূল্য";
            inputOldPrice.name = "price[]";
            inputOldPrice.style.margin = "2px";
            inputOldPrice.style.width = "100%";
            tdOldPrice.appendChild(inputOldPrice);

            const inputPercent = document.createElement("input");
            inputPercent.type = "number";
            inputPercent.placeholder = "পার্সেন্ট";
            inputPercent.name = "discount[]";
            inputPercent.style.margin = "2px";
            inputPercent.style.width = "100%";
            tdPercent.appendChild(inputPercent);

            const inputRetailPrice = document.createElement("input");
            inputRetailPrice.type = "number";
            inputRetailPrice.placeholder = "খুচরা মূল্য";
            inputRetailPrice.name = "current_price[]";
            inputRetailPrice.style.margin = "2px";
            inputRetailPrice.style.width = "100%";
            tdRetailPrice.appendChild(inputRetailPrice);

            // default weight ইনপুট
            // const inputWeight = document.createElement("input");
            // inputWeight.type = "text";
            // inputWeight.placeholder = "ওজন";
            // inputWeight.name = "weight[]";
            // inputWeight.style.margin = "2px";
            // inputWeight.style.width = "100%";
            // tdWeight.appendChild(inputWeight);


            // default weight ইনপুট
                const inputWeight = document.createElement("input");
                inputWeight.type = "text";
                inputWeight.placeholder = "ওজন";
                inputWeight.name = "weight[]";
                inputWeight.style.margin = "2px";
                inputWeight.style.width = "100%";
                tdWeight.appendChild(inputWeight);

                // ইংরেজি সংখ্যা এবং দশমিক ছাড়া অন্য অক্ষর হলে এলার্ট
                inputWeight.addEventListener("input", function() {
                    const value = inputWeight.value;

                    // Regex: শুধুমাত্র 0-9 এবং একটি মাত্র দশমিক
                    if(/[^0-9.]/.test(value)) {
                        showAlert("দয়া করে শুধুমাত্র ইংরেজি সংখ্যা লিখুন।");
                        // invalid character মুছে ফেলা
                        inputWeight.value = value.replace(/[^0-9.]/g, '');
                    }

                    // দশমিক একাধিক হলে শুধু প্রথমট রাখো
                    const parts = inputWeight.value.split('.');
                    if(parts.length > 2) {
                        inputWeight.value = parts[0] + '.' + parts.slice(1).join('');
                    }
                });




            attachReverseCalc(inputOldPrice, inputPercent, inputRetailPrice);
        }
    }

    // page load এ সব row initialize করো
    document.querySelectorAll('.product-row').forEach(function (row) {
        updatePaikariInputs(row);
    });

    // size textarea পরিবর্তন হলে update করো
    document.addEventListener('input', function (e) {
        if (e.target.matches('textarea[name="size[]"]')) {
            const row = e.target.closest('tr');
            updatePaikariInputs(row);
        }
    });

});
</script>





<!-- -----------------কা্স্টমাইজ এলার্ট--------------------- -->

<div id="customAlert" class="custom-alert">
  <div class="custom-alert-content">
    <p id="customAlertMessage"></p>
    <button id="customAlertClose">OK</button>
  </div>
</div>

<style type="text/css">
  .custom-alert {
  display: none; 
  position: fixed;
  z-index: 9999;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background-color: rgba(0,0,0,0.4);
  align-items: center;
  justify-content: center;

}


.custom-alert-content {
  background: #fff;
  padding: 20px;
  width: 300px;
  max-width: 90%;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0,0,0,0.3);
  text-align: center;
  animation: fadeIn 0.3s ease-in-out;
  position: relative;
  top: 0%;
  transform: translate(0, -100%);

}

.custom-alert-content p {
  margin-bottom: 15px;
  font-size: 14pt;
  font-weight: bold;
  color: #333;
}

.custom-alert-content button {
  background: #ff5722;
  color: white;
  border: none;
  padding: 8px 15px;
  font-size: 12pt;
  border-radius: 5px;
  cursor: pointer;
}

.custom-alert-content button:hover {
  background: #e64a19;
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.9); }
  to { opacity: 1; transform: scale(1); }
}

</style>


<script type="text/javascript">
  function showAlert(message) {
  const modal = document.getElementById("customAlert");
  const msgBox = document.getElementById("customAlertMessage");
  const closeBtn = document.getElementById("customAlertClose");

  msgBox.textContent = message;
  modal.style.display = "flex";

  closeBtn.onclick = function() {
    modal.style.display = "none";
  };

  // ESC চাপলে বন্ধ হবে
  document.addEventListener("keydown", function escHandler(e) {
    if (e.key === "Escape") {
      modal.style.display = "none";
      document.removeEventListener("keydown", escHandler);
    }
  });
}

</script>



<script type="text/javascript">
     function auto_hieght(element) {      
      element.style.height = "5px";
      element.style.height = (element.scrollHeight)+"px";
    }
</script>





<script>
function genaretGks(){
   const gksInput = document.querySelector(".gks");        
        let randomNum = Math.floor(1000000 + Math.random() * 9000000);
        gksInput.value ='p-'+randomNum;
    } 
</script>


<!-- ------------------নোটিফিকেশন------------ -->

<script type="text/javascript">
// auto_height function
function auto_height(el){
    el.style.height = 'auto';
    el.style.height = (el.scrollHeight) + 'px';
}

// Size alert function
function showSizeAlert(textarea) {
    // Check sessionStorage যদি Don’t show again চাপা থাকে
    if(sessionStorage.getItem('sizeAlertShown') === 'true') return;

    const message = "একাধিক সাইজ হলে কমা দিয়ে লিখুন।";

    // Custom dialog
    createCustomDialog(message, function(dontShowAgain) {
        if(dontShowAgain) {
            sessionStorage.setItem('sizeAlertShown', 'true');
        }
    });
}

// Custom dialog function
function createCustomDialog(message, callback) {
    // Overlay
    const overlay = document.createElement('div');
    overlay.className = 'custom-alert';

    // Dialog box
    const box = document.createElement('div');
    box.className = 'custom-alert-content';

    // Message
    const msg = document.createElement('p');
    msg.textContent = message;
    box.appendChild(msg);

    // Buttons container
    const btnContainer = document.createElement('div');
    btnContainer.className = 'btn-container';

    // OK button
    const okBtn = document.createElement('button');
    okBtn.textContent = 'OK';
    okBtn.className = 'ok-btn';
    okBtn.onclick = function() {
        document.body.removeChild(overlay);
        callback(false);
    };

    // Don't show again button
    const dontBtn = document.createElement('button');
    dontBtn.textContent = "পুনরায় দেখা বন্ধ করুন";
    dontBtn.style.backgroundColor = '#2683FF';
    dontBtn.style.marginLeft = '10pt';
    dontBtn.className = 'dont-btn';
    dontBtn.onclick = function() {
        document.body.removeChild(overlay);
        callback(true);
    };

    // Append buttons to container
    btnContainer.appendChild(okBtn);
    btnContainer.appendChild(dontBtn);

    // Append container to box
    box.appendChild(btnContainer);

    // Append box to overlay
    overlay.appendChild(box);

    // Append overlay to body
    document.body.appendChild(overlay);

    // Show overlay
    overlay.style.display = 'flex';
}

</script>




<?php
// End capturing the output and store it in a variable
$product_add_display_content = ob_get_clean();

// Now include frameForAll.php, which will use $catagory_display_content
include("frameForAll.php");

// mysqli_close($conn); // You might want to close the connection after all database operations
ob_end_flush();
?>




<!DOCTYPE html>
<html>
<head>

  <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<meta name="theme-color" content="#FF0000">
    
<title>অনলাইন শপ</title>
    

  
</head>
<body>


<style type="text/css">




</style>

<!----------------------------->
<script>
  flatpickr("#start_date", {
    dateFormat: "d/m/Y", // DD/MM/YYYY format
    position: "below"     // Force show calendar below
  });

  flatpickr("#end_date", {
    dateFormat: "d/m/Y",
    position: "below"
  });
</script>

<!-- ------------------------- -->
  

</body>
</html>