<!DOCTYPE html>
<html>
   <head>
  <!-- TABLES CSS CODE -->
  <?php include"comman/code_css.php"; ?>
  
  <!-- </copy> -->  
  </head>
   <body class="hold-transition skin-blue  sidebar-mini">
      <!-- **********************MODALS***************** -->
       <?php include"modals/modal_brand.php"; ?>
       <?php include"modals/modal_category.php"; ?>
       <?php include"modals/modal_unit.php"; ?>
       <?php include"modals/modal_tax.php"; ?>
       <!-- **********************MODALS END***************** -->
       
      <div class="wrapper">
      <?php include"sidebar.php"; ?>
      <?php
         if(!isset($item_name)){
         $item_name=$sku=$hsn=$opening_stock=$brand_id=$category_id=$gst_percentage=$tax_type=
         $sales_price=$purchase_price=$profit_margin=$unit_id=$price=$alert_qty=$store_id="";
         $stock = 0;
         $seller_points =0;
         $custom_barcode ='';
         $description ='';
         $mrp ='';
         $child_bit ='';
         $tax_id ='';
         $minimum_stock_level = 0;
         $reorder_level = 0;
         
         // Wholesale and Retail Pricing
         $wholesale_price = '';
         $retail_price = '';
         $wholesale_margin_type = 'percentage';
         $wholesale_margin_value = '10';
         $retail_margin_type = 'percentage';
         $retail_margin_value = '20';
         $auto_calculate_prices = 1;
         
         //$variants_selected='';
         $item_group='Single';

         $discount='';
          $discount_type='Percentage';

          
          $opening_stock_readonly='';


         $item_code = get_init_code('item');

         }
         else{
            $opening_stock_readonly = 'readonly';
         }
         //For new or update
         $opening_stock ='0';

         
         
         
         ?>
      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
        <!-- **********************MODALS***************** -->
      <?php include"modals/modal_variant.php"; ?>
      <!-- **********************MODALS END***************** -->

         <!-- Content Header (Page header) -->
         <section class="content-header">
            <h1>
               <?= $page_title;?>
               <small>Add/Update Items</small>
            </h1>
            <ol class="breadcrumb">
               <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i>Home</a></li>
               <li><a href="<?php echo $base_url; ?>items"><?= $this->lang->line('items_list'); ?></a></li>
               <li class="active"><?= $page_title;?></li>
            </ol>
         </section>
         <!-- Main content -->
         <section class="content">
            <div class="row">
               <!-- ********** ALERT MESSAGE START******* -->
               <?php include"comman/code_flashdata.php"; ?>
               <!-- ********** ALERT MESSAGE END******* -->
               <!-- right column -->
               <div class="col-md-12">
                  <!-- Horizontal Form -->
                  <div class="box box-primary ">
                     
                      <?= form_open('#', array('class' => 'form', 'id' => 'items-form', 'enctype'=>'multipart/form-data', 'method'=>'POST'));?>
                        <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                        <div class="box-body">

                          <div class="row">
                             <!-- Store Code -->
                              <?php /*if(store_module() && is_admin()) {$this->load->view('store/store_code',array('show_store_select_box_1'=>true,'store_id'=>$store_id)); }else{*/
                                echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
                              /*}*/ ?>
                              <!-- Preserve margin settings on edit: hidden fields so they are submitted and saved -->
                              <input type="hidden" name="wholesale_margin_type" id="wholesale_margin_type" value="<?php print isset($wholesale_margin_type) ? htmlspecialchars($wholesale_margin_type) : 'percentage'; ?>">
                              <input type="hidden" name="wholesale_margin_value" id="wholesale_margin_value" value="<?php print isset($wholesale_margin_value) ? htmlspecialchars($wholesale_margin_value) : '0.00'; ?>">
                              <input type="hidden" name="retail_margin_type" id="retail_margin_type" value="<?php print isset($retail_margin_type) ? htmlspecialchars($retail_margin_type) : 'percentage'; ?>">
                              <input type="hidden" name="retail_margin_value" id="retail_margin_value" value="<?php print isset($retail_margin_value) ? htmlspecialchars($retail_margin_value) : '0.00'; ?>">
                              <input type="hidden" name="auto_calculate_prices" id="auto_calculate_prices" value="<?php print isset($auto_calculate_prices) ? htmlspecialchars($auto_calculate_prices) : '1'; ?>">
                              <!-- Store Code end -->
                          </div>

                           <div class="row">
                              <div class="form-group col-md-4">
                                 <label for="item_code"><?= $this->lang->line('item_code'); ?><span class="text-danger">*</span></label>
                                 <input type="text" class="form-control" id="item_code" name="item_code" placeholder="" value="<?php print $item_code; ?>" >
                                 <span id="item_code_msg" style="display:none" class="text-danger"></span>
                              </div>
                           </div>
                           <div class="row">
                              <div class="form-group col-md-4">
                                 <label for="item_name"><?= $this->lang->line('item_name'); ?><span class="text-danger">*</span></label>
                                 <input type="text" autofocus="" class="form-control" id="item_name" name="item_name" placeholder="" value="<?php print $item_name; ?>" >
                                 <span id="item_name_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="brand_id"><?= $this->lang->line('brand'); ?></label>
                                 <div class="input-group">
                                 <select class="form-control select2" id="brand_id" name="brand_id"  style="width: 100%;"  >
                                    <option value="">-Select-</option>
                                    <?= get_brands_select_list($brand_id);  ?>
                                 </select>
                                 <span class="input-group-addon pointer" data-toggle="modal" data-target="#brand_modal" title="Add Customer"><i class="fa fa-plus-square-o text-primary fa-lg"></i></span>
                                    </div>
                                 <span id="brand_id_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="category_id"><?= $this->lang->line('category'); ?><span class="text-danger">*</span></label>
                                 <div class="input-group">
                                 <select class="form-control select2" id="category_id" name="category_id"  style="width: 100%;"  >
                                    <option value="">-Select-</option>
                                    <?= get_categories_select_list($category_id);  ?>
                                 </select>
                                 <span class="input-group-addon pointer" data-toggle="modal" data-target="#category_modal" title="Add Customer"><i class="fa fa-plus-square-o text-primary fa-lg"></i></span>
                                    </div>
                                 <span id="category_id_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="item_group"><?= $this->lang->line('item_group'); ?><span class="text-danger">*</span></label>
                                 <select class="form-control select2" id="item_group" name="item_group"  style="width: 100%;" >
                                  
                                    <option  value="Single">Single</option>
                                    <option  value="Variants">Variants</option>
                                 </select>
                                 <span id="item_group_msg" style="display:none" class="text-danger"></span>
                                 
                              </div>
                              <div class="form-group col-md-3">
                                 <label for="unit_id"><?= $this->lang->line('unit'); ?> (Main Unit)<span class="text-danger">*</span></label>
                                 <div class="input-group">
                                 <select class="form-control select2" id="unit_id" name="unit_id"  style="width: 100%;" onchange="updateUnitConversion()" >
                                    <?= get_units_select_list($unit_id);  ?>
                                 </select>
                                 <span class="input-group-addon pointer" data-toggle="modal" data-target="#unit_modal" title="Add Unit"><i class="fa fa-plus-square-o text-primary fa-lg"></i></span>
                                    </div>
                                 <small class="text-muted">Primary unit (e.g., Box)</small>
                                 <span id="unit_id_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-3">
                                 <label for="alternate_unit_id">Alternate Unit <small class="text-muted">(Optional)</small></label>
                                 <div class="input-group">
                                    <select class="form-control select2" id="alternate_unit_id" name="alternate_unit_id" style="width: 100%;" onchange="updateUnitConversion()">
                                       <option value="">--Select Alternate Unit--</option>
                                       <?= get_units_select_list(isset($alternate_unit_id) ? $alternate_unit_id : ''); ?>
                                    </select>
                                    <span class="input-group-addon pointer" data-toggle="modal" data-target="#unit_modal" title="Add Unit"><i class="fa fa-plus-square-o text-primary fa-lg"></i></span>
                                 </div>
                                 <small class="text-muted">Secondary unit (e.g., PCs)</small>
                                 <span id="alternate_unit_id_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-3" id="conversion_factor_group" style="display: none;">
                                 <label for="conversion_factor">Conversion Factor</label>
                                 <input type="text" class="form-control only_currency" id="conversion_factor" name="conversion_factor" placeholder="e.g., 12" value="<?php print isset($conversion_factor) ? $conversion_factor : '1.0000'; ?>" onkeyup="updateConversionDisplay(); updateAllUnitPrices();" onblur="updateUnitConversion(); updateAllUnitPrices();" oninput="updateConversionDisplay()">
                                 <div class="alert alert-info" style="padding: 5px; margin-top: 5px; margin-bottom: 0; font-size: 12px;">
                                    <strong id="conversion_display">1 <span id="main_unit_display">Main</span> = <span id="conversion_value">?</span> <span id="alternate_unit_display">Alt</span></strong>
                                 </div>
                                 <span id="conversion_factor_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-2" id="auto_calc_group" style="display: none;">
                                 <label for="auto_calculate_unit_prices">Auto Calculate</label>
                                 <select class="form-control" id="auto_calculate_unit_prices" name="auto_calculate_unit_prices" onchange="updateUnitConversion(); updateAllUnitPrices();">
                                    <option value="1" <?php echo (!isset($auto_calculate_unit_prices) || $auto_calculate_unit_prices == 1) ? 'selected' : ''; ?>>Yes (Default)</option>
                                    <option value="0" <?php echo (isset($auto_calculate_unit_prices) && $auto_calculate_unit_prices == 0) ? 'selected' : ''; ?>>No (Manual)</option>
                                 </select>
                                 <small class="text-muted">Auto-calculate prices</small>
                                 <span id="auto_calculate_unit_prices_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-2" id="clear_multi_unit_group" style="display: none;">
                                 <label>&nbsp;</label><br>
                                 <button type="button" class="btn btn-default btn-sm" onclick="clearMultiUnit()" style="width: 100%;">
                                    <i class="fa fa-times"></i> Clear
                                 </button>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="sku"><?= $this->lang->line('sku'); ?></label>
                                 <input type="text" class="form-control" id="sku" name="sku" placeholder="" value="<?php print $sku; ?>" >
                                 <span id="sku_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="hsn"><?= $this->lang->line('hsn'); ?></label>
                                 <input type="text" class="form-control" id="hsn" name="hsn" placeholder="" value="<?php print $hsn; ?>" >
                                 <span id="hsn_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="alert_qty" ><?= $this->lang->line('alert_qty'); ?></label>
                                 <input type="number" class="form-control no_special_char" id="alert_qty" name="alert_qty" placeholder="" min="0"  value="<?php print $alert_qty; ?>" >
                                 <span id="alert_qty_msg" style="display:none" class="text-danger"></span>
                              </div>
                           </div>
                           <hr>

                           <!-- Expiry Tracking Section -->
                           <div class="row">
                              <div class="col-md-12">
                                 <h4><i class="fa fa-calendar"></i> Expiry & Batch Tracking Settings</h4>
                                 <hr>
                              </div>
                           </div>
                           <div class="row">
                              <div class="form-group col-md-3">
                                 <label for="tracking_type">Tracking Type</label>
                                 <select class="form-control" id="tracking_type" name="item_tracking_type">
                                    <option value="none" <?php echo (isset($tracking_type) && $tracking_type == 'none') ? 'selected' : ''; ?>>None</option>
                                    <option value="expiry_only" <?php echo (isset($tracking_type) && $tracking_type == 'expiry_only') ? 'selected' : ''; ?>>Expiry Only</option>
                                    <option value="mfg_only" <?php echo (isset($tracking_type) && $tracking_type == 'mfg_only') ? 'selected' : ''; ?>>Manufacturing Only</option>
                                    <option value="both" <?php echo (isset($tracking_type) && $tracking_type == 'both') ? 'selected' : ''; ?>>Both Expiry & Manufacturing</option>
                                 </select>
                                 <span id="tracking_type_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-3">
                                 <label for="expiry_enabled">Enable Expiry Tracking</label>
                                 <select class="form-control" id="expiry_enabled" name="expiry_enabled">
                                    <option value="0" <?php echo (isset($expiry_enabled) && $expiry_enabled == 0) ? 'selected' : ''; ?>>No</option>
                                    <option value="1" <?php echo (isset($expiry_enabled) && $expiry_enabled == 1) ? 'selected' : ''; ?>>Yes</option>
                                 </select>
                                 <span id="expiry_enabled_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-3">
                                 <label for="batch_tracking_enabled">Enable Batch Tracking</label>
                                 <select class="form-control" id="batch_tracking_enabled" name="batch_tracking_enabled">
                                    <option value="0" <?php echo (isset($batch_tracking_enabled) && $batch_tracking_enabled == 0) ? 'selected' : ''; ?>>No</option>
                                    <option value="1" <?php echo (isset($batch_tracking_enabled) && $batch_tracking_enabled == 1) ? 'selected' : ''; ?>>Yes</option>
                                 </select>
                                 <span id="batch_tracking_enabled_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-3">
                                 <label for="expiry_notification_days">Notification Days</label>
                                 <input type="number" class="form-control" id="expiry_notification_days" name="expiry_notification_days" placeholder="Days before expiry" min="1" max="365" value="<?php print isset($expiry_notification_days) ? $expiry_notification_days : 30; ?>" >
                                 <small class="text-muted">Days before expiry to send notifications</small>
                                 <span id="expiry_notification_days_msg" style="display:none" class="text-danger"></span>
                              </div>
                           </div>
                           <div class="row">
                              <div class="form-group col-md-4">
                                 <label for="minimum_stock_level" >Minimum Stock Level</label>
                                 <input type="number" class="form-control no_special_char" id="minimum_stock_level" name="minimum_stock_level" placeholder="Minimum stock before alert" min="0"  value="<?php print isset($minimum_stock_level) ? $minimum_stock_level : ''; ?>" >
                                 <span id="minimum_stock_level_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="reorder_level" >Reorder Level</label>
                                 <input type="number" class="form-control no_special_char" id="reorder_level" name="reorder_level" placeholder="Stock level to trigger reorder" min="0"  value="<?php print isset($reorder_level) ? $reorder_level : ''; ?>" >
                                 <span id="reorder_level_msg" style="display:none" class="text-danger"></span>
                              </div>
                              
                              <div class="form-group col-md-4">
                                 <label for="seller_points" ><?= $this->lang->line('seller_points'); ?></label>
                                 <input type="text" class="form-control only_currency" id="seller_points" name="seller_points" placeholder=""  value="<?php print $seller_points; ?>" >
                                 <span id="seller_points_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="custom_barcode" ><?= $this->lang->line('barcode'); ?></label>
                                 <input type="text" class="form-control " id="custom_barcode" name="custom_barcode" placeholder=""  value="<?php print $custom_barcode; ?>" >
                                 <span id="custom_barcode_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="custom_barcode" ><?= $this->lang->line('description'); ?></label>
                                 <textarea type="text" class="form-control" id="description" name="description" placeholder=""><?php print $description; ?></textarea>
                                 <span id="description_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="item_image"><?= $this->lang->line('select_image'); ?></label>
                                 <input type="file" name="item_image" id="item_image">
                                 <span id="item_image_msg" style="display:block;" class="text-danger">Max Width/Height: 1000px * 1000px & Size: 1MB </span>
                              </div>
                              
                              
                           </div>
                           <hr>
                           <div class="row">
                              <div class="form-group col-md-4">
                                 <label for="discount_type"><?= $this->lang->line('discount_type'); ?></label>
                                 <select class="form-control" id="discount_type" name="discount_type"  style="width: 100%;" >
                                 <option value='Percentage'>Percentage(%)</option>
                                 <option value='Fixed'>Fixed(<?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?>)</option>
                                 </select>
                                 <span id="discount_type_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="discount"><?= $this->lang->line('discount'); ?></label>
                                 <input type="text" class="form-control only_currency" id="discount" name="discount" value="<?php print $discount; ?>" >
                                 <span id="discount_msg" style="display:none" class="text-danger"></span>
                              </div>
                              
                           </div>
                           <hr>
                           <!-- PRICING SECTION -->
                           <div class="box box-info">
                              <div class="box-header with-border">
                                 <h3 class="box-title"><i class="fa fa-calculator"></i> Item Pricing</h3>
                              </div>
                              <div class="box-body">
                                 
                                 <!-- Purchase Cost Section -->
                                 <div class="panel panel-primary" style="margin-bottom: 20px;">
                                    <div class="panel-heading">
                                       <h4 class="panel-title" style="margin: 0;"><i class="fa fa-shopping-cart"></i> Purchase Cost <small class="text-white">(What you paid to supplier)</small></h4>
                                    </div>
                                    <div class="panel-body">
                                       <!-- Price Before Tax Row -->
                                       <div class="row">
                                          <div class="form-group col-md-6 col-sm-6">
                                             <label for="price">Price Before Tax (Main Unit)<span class="text-danger">*</span></label>
                                             <input type="text" class="form-control only_currency" id="price" name="price" placeholder="Enter price before tax" value="<?php print $price; ?>" onkeyup="calculateAllPrices(); updateUnitPrices('purchase', 'main');" onblur="calculateAllPrices(); updateUnitPrices('purchase', 'main');">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Price per <span id="main_unit_price_label">main unit</span></small>
                                             <span id="price_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-6 col-sm-6" id="purchase_price_alternate_group" style="display: <?php echo (isset($alternate_unit_id) && !empty($alternate_unit_id)) ? 'block' : 'none'; ?>;">
                                             <label for="purchase_price_alternate">Price Before Tax (Alternate Unit)</label>
                                             <input type="text" class="form-control only_currency" id="purchase_price_alternate" name="purchase_price_alternate" placeholder="Auto-calculated or enter manually" value="<?php print isset($purchase_price_alternate) ? $purchase_price_alternate : ''; ?>" onkeyup="updateUnitPrices('purchase', 'alternate')" onblur="updateUnitPrices('purchase', 'alternate')">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Price per <span id="alternate_unit_price_label">alternate unit</span> <span id="auto_calc_status_purchase" class="text-info"></span></small>
                                             <span id="purchase_price_alternate_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                       
                                       <!-- Tax Configuration Row -->
                                       <div class="row">
                                          <div class="form-group col-md-4 col-sm-6">
                                             <label for="tax_id">Tax Rate<span class="text-danger">*</span></label>
                                             <div class="input-group">
                                                <select class="form-control select2" id="tax_id" name="tax_id" style="width: 100%;" onchange="calculateAllPrices()">
                                                   <?= get_tax_select_list($tax_id); ?>
                                                </select>
                                                <span class="input-group-addon pointer" data-toggle="modal" data-target="#tax_modal" title="Add Tax"><i class="fa fa-plus-square-o text-primary fa-lg"></i></span>
                                             </div>
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Tax percentage</small>
                                             <span id="tax_id_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-4 col-sm-6">
                                             <label for="tax_type">Tax Type<span class="text-danger">*</span></label>
                                             <select class="form-control select2" id="tax_type" name="tax_type" style="width: 100%;" onchange="calculateAllPrices(true)">
                                                <?php 
                                                   $inclusive_selected=$exclusive_selected='';
                                                   if($tax_type =='Inclusive') { $inclusive_selected='selected'; }
                                                   if($tax_type =='Exclusive') { $exclusive_selected='selected'; }
                                                ?>
                                                <option <?= $inclusive_selected ?> value="Inclusive">Inclusive (Tax included)</option>
                                                <option <?= $exclusive_selected ?> value="Exclusive">Exclusive (Tax added)</option>
                                             </select>
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Tax calculation method</small>
                                             <span id="tax_type_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-4 col-sm-6">
                                             <label for="profit_margin">Profit Margin (%)</label>
                                             <input type="text" class="form-control only_currency" id="profit_margin" name="profit_margin" placeholder="Enter margin percentage" value="<?php print (isset($profit_margin) && $profit_margin !== '' && $profit_margin !== null) ? $profit_margin : ''; ?>" onkeyup="calculateFromProfitMargin()" onblur="calculateFromProfitMargin()">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Desired profit percentage (Purchase cost card)</small>
                                             <span id="profit_margin_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                       
                                       <!-- Total Purchase Cost Row -->
                                       <div class="row">
                                          <div class="form-group col-md-6 col-sm-6">
                                             <label for="purchase_price">Total Purchase Cost (Main Unit)<span class="text-danger">*</span></label>
                                             <input type="text" class="form-control only_currency" id="purchase_price" name="purchase_price" placeholder="Auto-calculated" value="<?php print $purchase_price; ?>" readonly style="background-color: #f5f5f5; font-weight: bold;">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Final amount per <span id="main_unit_purchase_label">main unit</span> (Price + Tax)</small>
                                             <span id="purchase_price_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-6 col-sm-6" id="purchase_price_main_group" style="display: <?php echo (isset($alternate_unit_id) && !empty($alternate_unit_id)) ? 'block' : 'none'; ?>;">
                                             <label for="purchase_price_main">Total Purchase Cost (Alternate Unit)</label>
                                             <input type="text" class="form-control only_currency" id="purchase_price_main" name="purchase_price_main" placeholder="Auto-calculated" value="<?php print isset($purchase_price_main) ? $purchase_price_main : ''; ?>" readonly style="background-color: #f5f5f5; font-weight: bold;">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Final amount per <span id="alternate_unit_purchase_label">alternate unit</span></small>
                                             <span id="purchase_price_main_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 
                                 <!-- Selling Prices Section -->
                                 <div class="panel panel-success" id="selling_prices_section">
                                    <div class="panel-heading">
                                       <h4 class="panel-title" style="margin: 0;"><i class="fa fa-dollar"></i> Selling Prices <small class="text-white">(What you charge customers)</small></h4>
                                    </div>
                                    <div class="panel-body">
                                       <!-- Wholesale and Retail Prices Row -->
                                       <div class="row">
                                          <div class="form-group col-md-6 col-sm-6">
                                             <label for="wholesale_price">Wholesale Price (Main Unit)<span class="text-danger">*</span></label>
                                             <input type="text" class="form-control only_currency" id="wholesale_price" name="wholesale_price" placeholder="Enter wholesale price" value="<?php print (!empty($wholesale_price) && $wholesale_price != '0.0000') ? $wholesale_price : ''; ?>" required onkeyup="updateSalesPrice(); updateUnitPrices('wholesale', 'main');" onblur="updateSalesPrice(); updateUnitPrices('wholesale', 'main');">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Per <span id="main_unit_wholesale_label">main unit</span> (bulk customers)</small>
                                             <span id="wholesale_price_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-6 col-sm-6" id="wholesale_price_alternate_group" style="display: <?php echo (isset($alternate_unit_id) && !empty($alternate_unit_id)) ? 'block' : 'none'; ?>;">
                                             <label for="wholesale_price_alternate">Wholesale Price (Alternate Unit)</label>
                                             <input type="text" class="form-control only_currency" id="wholesale_price_alternate" name="wholesale_price_alternate" placeholder="Auto-calculated or enter manually" value="<?php print isset($wholesale_price_alternate) ? $wholesale_price_alternate : ''; ?>" onkeyup="updateUnitPrices('wholesale', 'alternate')" onblur="updateUnitPrices('wholesale', 'alternate')">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Per <span id="alternate_unit_wholesale_label">alternate unit</span> <span id="auto_calc_status_wholesale" class="text-info"></span></small>
                                             <span id="wholesale_price_alternate_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                       
                                       <div class="row">
                                          <div class="form-group col-md-6 col-sm-6">
                                             <label for="retail_price">Retail Price (Main Unit)<span class="text-danger">*</span></label>
                                             <input type="text" class="form-control only_currency" id="retail_price" name="retail_price" placeholder="Enter retail price" value="<?php print (!empty($retail_price) && $retail_price != '0.0000') ? $retail_price : $sales_price; ?>" required onkeyup="updateSalesPrice(); updateUnitPrices('retail', 'main');" onblur="updateSalesPrice(); updateUnitPrices('retail', 'main');">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Per <span id="main_unit_retail_label">main unit</span> (individual customers)</small>
                                             <span id="retail_price_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-6 col-sm-6" id="retail_price_alternate_group" style="display: <?php echo (isset($alternate_unit_id) && !empty($alternate_unit_id)) ? 'block' : 'none'; ?>;">
                                             <label for="retail_price_alternate">Retail Price (Alternate Unit)</label>
                                             <input type="text" class="form-control only_currency" id="retail_price_alternate" name="retail_price_alternate" placeholder="Auto-calculated or enter manually" value="<?php print isset($retail_price_alternate) ? $retail_price_alternate : ''; ?>" onkeyup="updateUnitPrices('retail', 'alternate')" onblur="updateUnitPrices('retail', 'alternate')">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Per <span id="alternate_unit_retail_label">alternate unit</span> <span id="auto_calc_status_retail" class="text-info"></span></small>
                                             <span id="retail_price_alternate_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                       
                                       <!-- Margin and Sales Price Row -->
                                       <div class="row">
                                          <div class="form-group col-md-4 col-sm-6">
                                             <label for="margin_percentage">Margin %</label>
                                             <input type="text" class="form-control only_currency" id="margin_percentage" name="margin_percentage" placeholder="Enter margin percentage" value="<?php print (!empty($margin_percentage) && $margin_percentage != '0.0000') ? $margin_percentage : ''; ?>" onkeyup="calculateFromMarginPercentage()" onblur="calculateFromMarginPercentage()">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Applies to both wholesale & retail</small>
                                          </div>
                                          <div class="form-group col-md-4 col-sm-6">
                                             <label for="sales_price">Sales Price (Legacy)<span class="text-danger">*</span></label>
                                             <input type="text" class="form-control only_currency" id="sales_price" name="sales_price" placeholder="Auto-set to retail price" value="<?php print $sales_price; ?>" readonly style="background-color: #f5f5f5; font-weight: bold;">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Auto-set to retail price</small>
                                             <span id="sales_price_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                          <div class="form-group col-md-4 col-sm-6" id="sales_price_main_group" style="display: <?php echo (isset($alternate_unit_id) && !empty($alternate_unit_id)) ? 'block' : 'none'; ?>;">
                                             <label for="sales_price_main">Sales Price - Main Unit</label>
                                             <input type="text" class="form-control only_currency" id="sales_price_main" name="sales_price_main" placeholder="Auto-set from retail price" value="<?php print isset($sales_price_main) ? $sales_price_main : ''; ?>" readonly style="background-color: #f5f5f5; font-weight: bold;" onkeyup="updateUnitPrices('sales', 'main')" onblur="updateUnitPrices('sales', 'main')">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Auto-set from retail price (main unit)</small>
                                             <span id="sales_price_main_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                       
                                       <div class="row" id="sales_price_alternate_row" style="display: <?php echo (isset($alternate_unit_id) && !empty($alternate_unit_id)) ? 'block' : 'none'; ?>;">
                                          <div class="form-group col-md-4 col-sm-6">
                                             <label for="sales_price_alternate">Sales Price - Alternate Unit</label>
                                             <input type="text" class="form-control only_currency" id="sales_price_alternate" name="sales_price_alternate" placeholder="Auto-set from retail price" value="<?php print isset($sales_price_alternate) ? $sales_price_alternate : ''; ?>" readonly style="background-color: #f5f5f5; font-weight: bold;" onkeyup="updateUnitPrices('sales', 'alternate')" onblur="updateUnitPrices('sales', 'alternate')">
                                             <small class="text-muted"><i class="fa fa-info-circle"></i> Auto-set from retail price (alternate unit)</small>
                                             <span id="sales_price_alternate_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 
                              </div>
                           </div>
                           <hr>
                           
                           <div class="row">
                              <div class="form-group col-md-4">
                                 <label for="mrp"><?= $this->lang->line('msp'); ?><i class="hover-q " data-container="body" data-toggle="popover" data-placement="top" data-content="<?= $this->lang->line('mrp_definition'); ?>" data-html="true" data-trigger="hover" data-original-title="">
                                  <i class="fa fa-info-circle text-maroon text-black hover-q"></i>
                                </i></label>
                                 <input type="text" class="form-control only_currency" id="mrp" name="mrp" placeholder="Minimum Sale Price"  value="<?php print $mrp; ?>" >
                                 <span id="mrp_msg" style="display:none" class="text-danger"></span>
                              </div>
                           </div>
                           <hr>
                           <div class="row">
                              <div class="form-group col-md-4">
                                 <label for="warehouse_id"><?= $this->lang->line('warehouse'); ?></label>
                                 <select class="form-control" id="warehouse_id" name="warehouse_id"  style="width: 100%;" >
                                 <?= get_warehouse_select_list();?>
                                 </select>
                                 <span id="warehouse_id_msg" style="display:none" class="text-danger"></span>
                              </div>
                              <div class="form-group col-md-4">
                                 <label for="adjustment_qty"><?= $this->lang->line('opening_stock'); ?></label>
                                 <input type="text" class="form-control only_currency" id="adjustment_qty" name="adjustment_qty" value="<?php print $opening_stock; ?>" >
                                 <span id="adjustment_qty_msg" style="display:none" class="text-danger"></span>
                              </div>
                           </div>
                           
                           <!-- Batch Details Section (Hidden by default) -->
                           <div class="row" id="batch-details-section" style="display:none;">
                              <div class="col-md-12">
                                 <div class="box box-info">
                                    <div class="box-header with-border">
                                       <h3 class="box-title"><i class="fa fa-cubes"></i> Batch Details for Opening Stock</h3>
                                    </div>
                                    <div class="box-body">
                                       <table class="table table-bordered" id="batch-details-table">
                                          <thead>
                                             <tr class="bg-primary">
                                                <th style="width:5%">#</th>
                                                <th style="width:20%">Batch Number</th>
                                                <th style="width:15%">Manufacturing Date</th>
                                                <th style="width:15%">Expiry Date</th>
                                                <th style="width:15%">Quantity</th>
                                                <th style="width:30%">Remarks</th>
                                                <th style="width:10%">Action</th>
                                             </tr>
                                          </thead>
                                          <tbody id="batch-details-tbody">
                                             <!-- Batch rows will be added here -->
                                          </tbody>
                                       </table>
                                       <button type="button" class="btn btn-primary btn-sm" id="add-batch-row-btn">
                                          <i class="fa fa-plus"></i> Add Batch
                                       </button>
                                    </div>
                                 </div>
                              </div>
                           </div>

                           <div class="row variant_div">
                             <div class="col-md-12">
                                  <div class="box box-info ">
                                    <div class="">
                                      <div class="box-header">
                                        <div class="col-md-6 col-md-offset-3 d-flex justify-content" >
                                          <div class="input-group">
                                                <span class="input-group-addon" title="Select Items"><i class="fa fa-search"></i></span>
                                                 <input type="text" class="form-control " placeholder="Search Variant" id="variant_search">
                                                 <span class="input-group-addon pointer text-green" data-toggle="modal" data-target="#variant-modal" title="Click to Add New Variant"><i class="fa fa-plus"></i></span>
                                              </div>
                                        </div>
                                      </div>
                                      <div class="box-body">
                                        <div class="table-responsive" style="width: 100%">
                                        <input type="hidden" value='1' id="hidden_rowcount" name="hidden_rowcount">
                                        <table class="table table-hover table-bordered" style="width:100%" id="variant_table">
                                             <thead class="custom_thead">
                                                <tr class="bg-primary" >
                                                   <th rowspan='2' style="width:15%"><?= $this->lang->line('variant_name'); ?></th>
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('sku'); ?></th> 
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('hsn'); ?></th> 
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('barcode'); ?></th> 
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('purchase_price'); ?>(<span id="purchase_price_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('profit_margin'); ?></th>
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('sales_price'); ?>(<span id="sales_price_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                   <th rowspan='2' style="width:10%">Wholesale Price(<span id="wholesale_price_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                   <th rowspan='2' style="width:10%">Retail Price(<span id="retail_price_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                   <th rowspan='2' style="width:10%">Margin %</th>
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('mrp'); ?>(<span id="mrp_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('opening_stock'); ?></th>
                                                   <th rowspan='2' style="width:5%"><?= $this->lang->line('action'); ?></th>
                                                </tr>
                                             </thead>
                                             <tbody>
                                               <?php if($item_group!='Single'){ 
                                                  echo $this->items_model->get_variants_list_in_row($q_id);
                                                } ?>
                                             </tbody>
                                          </table>
                                      </div>
                                      </div>
                                    </div>
                                  </div>
                              </div>
                              
                           </div>
                           <!-- /row -->
                           <!-- /.box-body -->
                           <div class="box-footer">
                              <div class="col-sm-8 col-sm-offset-2 text-center">
                                 <!-- <div class="col-sm-4"></div> -->
                                 <?php
                                    if($item_name!=""){
                                         $btn_name="Update";
                                         $btn_id="update";
                                         ?>
                                 <input type="hidden" name="q_id" id="q_id" value="<?php echo $q_id;?>"/>
                                 <?php
                                    }
                                              else{
                                                  $btn_name="Save";
                                                  $btn_id="save";
                                              }
                                    
                                              ?>
                                 <div class="col-md-3 col-md-offset-3">
                                    <button type="button" id="<?php echo $btn_id;?>" class=" btn btn-block btn-success" title="Save Data"><?php echo $btn_name;?></button>
                                 </div>
                                 <div class="col-sm-3">
                                    <a href="<?=base_url('dashboard');?>">
                                    <button type="button" class="col-sm-3 btn btn-block btn-warning close_btn" title="Go Dashboard">Close</button>
                                    </a>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                     <?= form_close(); ?>
                     </div>
                     <!-- /.box -->
                  </div>
                  <!--/.col (right) -->
               </div>
              
               <!-- /.row -->
         </section>
         <!-- /.content -->
         </div>
         <!-- /.content-wrapper -->
         <?php include"footer.php"; ?>
         <!-- Add the sidebar's background. This div must be placed
            immediately after the control sidebar -->
         <div class="control-sidebar-bg"></div>
      </div>
      <!-- ./wrapper -->
      <!-- SOUND CODE -->
      <?php include"comman/code_js_sound.php"; ?>
      <!-- TABLES CODE -->
      <?php include"comman/code_js.php"; ?>
      <script src="<?php echo $theme_link; ?>js/items.js"></script>
      <script src="<?php echo $theme_link; ?>js/modals.js"></script>
      <script type="text/javascript">
         $("#discount_type").val('<?=$discount_type; ?>');
        <?php if(isset($q_id)){ ?>
          $("#store_id").attr('readonly',true);
        <?php }?>
        $("#item_group").val("<?=$item_group;?>").select2().trigger("change");

        // Handle item group change to show/hide selling prices section
        $("#item_group").on('change', function(){
            var itemGroup = $(this).val();
            if (itemGroup === 'Variants') {
                // Hide selling prices section for variants
                $("#selling_prices_section").hide();
            } else {
                // Show selling prices section for single items
                $("#selling_prices_section").show();
            }
        });

        // Initialize visibility based on current selection
        var currentItemGroup = $("#item_group").val();
        if (currentItemGroup === 'Variants') {
            $("#selling_prices_section").hide();
        } else {
            $("#selling_prices_section").show();
        }

        <?php if(!empty($item_name)){ ?>
          $("#hidden_rowcount").val($("#variant_table  tr").length)+1;
            calculate_purchase_price_of_all_row();
            calculate_sales_price_of_all_row();
        <?php } ?>

        <?php if($child_bit==1 || !empty($item_name)){ ?>
          $("#item_group").parent().addClass('hide');
        <?php } ?>

        // Auto-populate wholesale and retail prices when sales price changes
        $("#sales_price").on('keyup blur', function(){
            updateLegacyPrice();
        });

        // Auto-populate when wholesale price changes (if retail is empty)
        $("#wholesale_price").on('keyup blur', function(){
            calculateRetailPrice();
        });

        // Auto-populate when retail price changes (if wholesale is empty)
        $("#retail_price").on('keyup blur', function(){
            calculateWholesalePrice();
        });

        // Simple and clear pricing calculations
        // Track if user has manually set retail/wholesale prices
        var userSetRetailPrice = false;
        var userSetWholesalePrice = false;

        $("#retail_price").on('focus', function() { userSetRetailPrice = true; });
        $("#wholesale_price").on('focus', function() { userSetWholesalePrice = true; });

        function calculateAllPrices(forceUpdate) {
            var basePrice = parseFloat($("#price").val()) || 0;
            var taxId = $("#tax_id").val();
            var taxType = $("#tax_type").val();

            if (basePrice > 0 && taxId) {
                var taxRate = parseFloat($("#tax_id option:selected").attr('data-tax')) || 0;
                var purchasePrice = 0;

                if (taxType === 'Inclusive') {
                    // Inclusive: base price already includes tax, so purchase cost = base price
                    purchasePrice = basePrice;
                } else {
                    // Exclusive: tax is added on top, so purchase cost = base price + tax
                    purchasePrice = basePrice + (basePrice * taxRate / 100);
                }

                $("#purchase_price").val(purchasePrice.toFixed(2));

                // On edit (initial load): keep server-loaded selling prices from margins – do not overwrite with purchase price
                var isInitialLoad = (typeof window.initialLoadComplete === 'undefined' || window.initialLoadComplete === false);
                var currentRetailPrice = parseFloat($("#retail_price").val()) || 0;
                var currentWholesalePrice = parseFloat($("#wholesale_price").val()) || 0;

                if (isInitialLoad) {
                    // Edit mode: leave retail/wholesale as loaded from DB (they were set using margins). Only fix if invalid.
                    if (currentRetailPrice > 0 && currentRetailPrice >= purchasePrice) {
                        userSetRetailPrice = true; // Treat server value as valid so we don't overwrite later
                    } else if (currentRetailPrice <= 0 || currentRetailPrice < purchasePrice) {
                        $("#retail_price").val(purchasePrice.toFixed(2));
                    }
                    if (currentWholesalePrice > 0 && currentWholesalePrice >= purchasePrice) {
                        userSetWholesalePrice = true;
                    } else if (currentWholesalePrice <= 0 || currentWholesalePrice < purchasePrice) {
                        $("#wholesale_price").val(purchasePrice.toFixed(2));
                    }
                } else {
                    // New item or user changed something: auto-set if empty, zero, or less than purchase price
                    if (forceUpdate || !userSetRetailPrice || currentRetailPrice <= 0 || currentRetailPrice < purchasePrice) {
                        $("#retail_price").val(purchasePrice.toFixed(2));
                        userSetRetailPrice = false;
                    }
                    if (forceUpdate || !userSetWholesalePrice || currentWholesalePrice <= 0 || currentWholesalePrice < purchasePrice) {
                        $("#wholesale_price").val(purchasePrice.toFixed(2));
                        userSetWholesalePrice = false;
                    }
                }

                updateSalesPrice();
            }

            // Auto-calculate alternate unit prices if enabled (after all calculations)
            if (typeof updateUnitPrices === 'function') {
                setTimeout(function() {
                    updateUnitPrices('purchase', 'main');
                }, 100);
            }
        }

        function updateSalesPrice(skipProfitMarginUpdate) {
            var retailPrice = parseFloat($("#retail_price").val()) || 0;
            var wholesalePrice = parseFloat($("#wholesale_price").val()) || 0;
            
            // Set sales price to retail price
            $("#sales_price").val(retailPrice.toFixed(2));
            
            // Profit Margin (%) lives in the PURCHASE card and must never be overwritten by sell-side logic on initial load.
            // Only recalculate it from retail price when the user is actively changing prices (not on edit page load).
            if (!skipProfitMarginUpdate) {
                var purchasePrice = parseFloat($("#purchase_price").val()) || 0;
                var currentProfitMarginVal = $("#profit_margin").val();
                var currentProfitMargin = parseFloat(currentProfitMarginVal) || 0;
                var isInitialLoad = (typeof window.initialLoadComplete === 'undefined' || window.initialLoadComplete === false);
                
                if (isInitialLoad) {
                    // On edit: keep the value from the server (Purchase cost card). Do not overwrite with sell-side calculation.
                    // Do nothing – leave profit_margin as rendered by the server
                } else if (purchasePrice > 0 && retailPrice > 0) {
                    // After initial load: only update if field is empty so we can back-fill from prices
                    if (currentProfitMarginVal === '' || currentProfitMarginVal === null) {
                        var profitMargin = ((retailPrice - purchasePrice) / purchasePrice) * 100;
                        $("#profit_margin").val(profitMargin.toFixed(2));
                    }
                }
            }
            
            // Only update wholesale price if it's empty and we have a retail price
            if (wholesalePrice == 0 && retailPrice > 0) {
                $("#wholesale_price").val(retailPrice.toFixed(2));
            }
            
            // Update sales_price_main and sales_price_alternate from retail prices (not purchase)
            if ($("#alternate_unit_id").val()) {
                var retailPriceMain = parseFloat($("#retail_price").val()) || 0;
                if (retailPriceMain > 0) {
                    $("#sales_price_main").val(retailPriceMain.toFixed(2));
                }
                
                var retailPriceAlternate = parseFloat($("#retail_price_alternate").val()) || 0;
                if (retailPriceAlternate > 0) {
                    $("#sales_price_alternate").val(retailPriceAlternate.toFixed(2));
                } else {
                    // If alternate retail price is not set, calculate it from main retail price
                    var conversionFactor = parseFloat($("#conversion_factor").val()) || 0;
                    if (retailPriceMain > 0 && conversionFactor > 0) {
                        var calculatedAltRetail = retailPriceMain / conversionFactor;
                        $("#retail_price_alternate").val(calculatedAltRetail.toFixed(2));
                        $("#sales_price_alternate").val(calculatedAltRetail.toFixed(2));
                    }
                }
            }
            
            // Auto-calculate alternate unit prices if enabled (after all calculations)
            if (typeof updateUnitPrices === 'function') {
                setTimeout(function() {
                    updateUnitPrices('wholesale', 'main');
                    updateUnitPrices('retail', 'main');
                }, 100);
            }
        }

        function calculateFromProfitMargin() {
            var purchasePrice = parseFloat($("#purchase_price").val()) || 0;
            var profitMargin = parseFloat($("#profit_margin").val()) || 0;
            
            if (purchasePrice > 0 && profitMargin > 0) {
                var retailPrice = purchasePrice + (purchasePrice * profitMargin / 100);
                $("#retail_price").val(retailPrice.toFixed(2));
                $("#sales_price").val(retailPrice.toFixed(2));
                
                // Also update wholesale price with a smaller margin (10% less than retail)
                var wholesaleMargin = Math.max(0, profitMargin - 10);
                var wholesalePrice = purchasePrice + (purchasePrice * wholesaleMargin / 100);
                $("#wholesale_price").val(wholesalePrice.toFixed(2));
                
                // Update sales price function to handle multi-unit prices (skip profit margin update to avoid overwriting)
                updateSalesPrice(true);
                
                // Auto-calculate alternate unit prices if enabled (after all calculations)
                if (typeof updateUnitPrices === 'function') {
                    setTimeout(function() {
                        updateUnitPrices('wholesale', 'main');
                        updateUnitPrices('retail', 'main');
                    }, 100);
                }
            }
        }

        function calculateFromMarginPercentage() {
            var purchasePrice = parseFloat($("#purchase_price").val()) || 0;
            var marginPercentage = parseFloat($("#margin_percentage").val()) || 0;
            
            if (purchasePrice > 0 && marginPercentage > 0) {
                // Calculate base sales price with margin
                var salesPrice = purchasePrice + (purchasePrice * marginPercentage / 100);
                
                // Set retail price to sales price
                $("#retail_price").val(salesPrice.toFixed(2));
                $("#sales_price").val(salesPrice.toFixed(2));
                
                // Only set wholesale price if it's empty
                var currentWholesalePrice = parseFloat($("#wholesale_price").val()) || 0;
                if (currentWholesalePrice == 0) {
                    $("#wholesale_price").val(salesPrice.toFixed(2));
                }
            }
        }


        // Initialize on page load
        $(document).ready(function() {
            // Leave initialLoadComplete undefined so first run preserves Profit Margin (%) from Purchase card (edit).
            // Do NOT set to false here – that was causing profit_margin to be overwritten by sell-side calculation.
            calculateAllPrices();
            
            // Mark initial load as complete after first run so future user changes can recalc
            setTimeout(function() {
                window.initialLoadComplete = true;
            }, 500);

            // Add event listeners for real-time updates
            $("#price, #tax_id").on('keyup change', function() {
                calculateAllPrices();
            });

            // When tax type changes, force recalculate all prices to avoid negative margins
            $("#tax_type").on('change', function() {
                calculateAllPrices(true);
            });

            $("#wholesale_price, #retail_price").on('keyup change', function() {
                updateSalesPrice();
            });

            $("#profit_margin").on('keyup change', function() {
                calculateFromProfitMargin();
            });
        });
        
        // ===== BATCH DETAILS AUTO-DISPLAY =====
        var batchRowCounter = 0;
        
        function addBatchRow() {
            batchRowCounter++;
            var row = '<tr id="batch-row-' + batchRowCounter + '">' +
                '<td>' + batchRowCounter + '</td>' +
                '<td><input type="text" class="form-control" name="batch_number[]" placeholder="E.g. BATCH001" required></td>' +
                '<td><input type="text" class="form-control date-input" name="manufacturing_date[]" placeholder="YYYY-MM-DD" readonly></td>' +
                '<td><input type="text" class="form-control date-input" name="expiry_date[]" placeholder="YYYY-MM-DD" readonly></td>' +
                '<td><input type="number" class="form-control batch-qty-input" name="batch_qty[]" min="0" step="0.01" placeholder="0" required></td>' +
                '<td><input type="text" class="form-control" name="batch_remarks[]" placeholder="Remarks"></td>' +
                '<td><button type="button" class="btn btn-danger btn-sm remove-batch-row"><i class="fa fa-trash"></i></button></td>' +
                '</tr>';
            $('#batch-details-tbody').append(row);
            
            // Initialize date pickers for new row
            $('#batch-row-' + batchRowCounter + ' .date-input').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayHighlight: true,
                clearBtn: true
            });
            
            updateBatchQuantityValidation();
        }
        
        function updateBatchQuantityValidation() {
            var openingStock = parseFloat($('#adjustment_qty').val()) || 0;
            var totalBatchQty = 0;
            
            $('.batch-qty-input').each(function() {
                totalBatchQty += parseFloat($(this).val()) || 0;
            });
            
            var diff = Math.abs(totalBatchQty - openingStock).toFixed(2);
            
            if (totalBatchQty > 0 && totalBatchQty !== openingStock) {
                $('#batch-qty-validation').html('<span class="text-danger"><i class="fa fa-exclamation-triangle"></i> Total batch quantity (' + totalBatchQty + ') does not match opening stock (' + openingStock + '). Difference: ' + diff + '</span>');
            } else if (totalBatchQty > 0 && totalBatchQty === openingStock) {
                $('#batch-qty-validation').html('<span class="text-success"><i class="fa fa-check"></i> Total matches opening stock</span>');
            } else {
                $('#batch-qty-validation').html('');
            }
        }
        
            function toggleBatchDetails() {
                var isBatch = $('#batch_tracking_enabled').val() == '1';
                var stock = parseFloat($('#adjustment_qty').val()) || 0;
                
                if (isBatch && stock > 0) {
                    $('#batch-details-section').show();
                    if ($('#batch-details-tbody tr').length === 0) {
                        addBatchRow();
                    }
                    // Add validation message inside box-body
                    if (!$('#batch-qty-validation').length) {
                        $('#batch-details-section .box-body').prepend('<div id="batch-qty-validation" class="alert alert-info" style="margin-bottom: 15px; padding: 10px;"><i class="fa fa-info-circle"></i> Batch quantities must total to the opening stock amount.</div>');
                    }
                } else {
                    $('#batch-details-section').hide();
                    $('#batch-qty-validation').remove();
                }
            }
        
        $(document).ready(function() {
            toggleBatchDetails();
            $('#batch_tracking_enabled, #adjustment_qty').on('change input keyup', toggleBatchDetails);
            
            // Update batch quantity validation on any change
            $(document).on('input change', '.batch-qty-input', updateBatchQuantityValidation);
            $(document).on('input change', '#adjustment_qty', updateBatchQuantityValidation);
            
            $(document).on('click', '#add-batch-row-btn', addBatchRow);
            $(document).on('click', '.remove-batch-row', function() {
                $(this).closest('tr').remove();
                $('#batch-details-tbody tr').each(function(i) {
                    $(this).find('td:first').text(i + 1);
                });
                updateBatchQuantityValidation();
            });
            
            // Validate batch quantities before form submission
            $('form').on('submit', function(e) {
                var isBatch = $('#batch_tracking_enabled').val() == '1';
                var openingStock = parseFloat($('#adjustment_qty').val()) || 0;
                
                if (isBatch && openingStock > 0 && $('#batch-details-section').is(':visible')) {
                    var totalBatchQty = 0;
                    $('.batch-qty-input').each(function() {
                        totalBatchQty += parseFloat($(this).val()) || 0;
                    });
                    
                    if (totalBatchQty !== openingStock) {
                        e.preventDefault();
                        alert('ERROR: Batch quantities (Total: ' + totalBatchQty + ') must equal the opening stock (' + openingStock + '). Please adjust batch quantities.');
                        $('#batch-qty-validation').scrollIntoView({behavior: 'smooth', block: 'center'});
                        return false;
                    }
                }
            });
        });
        // ===== END BATCH DETAILS =====

      </script>
      <!-- Make sidebar menu hughlighter/selector -->
      <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
      
      <!-- DatePicker for batch details -->
      <link rel="stylesheet" href="<?=$this->data['theme_link'];?>plugins/datepicker/bootstrap-datepicker.min.css">
      <script src="<?=$this->data['theme_link'];?>plugins/datepicker/bootstrap-datepicker.min.js"></script>
      
      <style>
        /* Fix double background issue */
        #batch-details-section .box {
            background: #fff;
            border: 1px solid #d2d6de;
            border-radius: 3px;
        }
        
        #batch-details-section .box-header {
            background-color: #17a2b8;
            color: #fff;
            border-bottom: 1px solid #d2d6de;
        }
        
        /* Style date inputs to look like text boxes */
        .date-input {
            background-color: #fff !important;
            cursor: pointer;
        }
        
        .date-input:hover {
            background-color: #f5f5f5 !important;
        }
        
        /* Increase font sizes for better readability */
        .box-body .form-control,
        .box-body input[type="text"],
        .box-body input[type="number"],
        .box-body input[type="file"],
        .box-body select,
        .box-body textarea {
            font-size: 18px !important;
            padding: 10px 14px !important;
            line-height: 1.5 !important;
        }
        
        .box-body label {
            font-size: 18px !important;
            font-weight: 600 !important;
            margin-bottom: 10px !important;
        }
        
        .box-body small,
        .box-body .text-muted {
            font-size: 16px !important;
        }
        
        .box-body .form-group {
            margin-bottom: 25px !important;
        }
        
        .box-body .input-group-addon {
            font-size: 18px !important;
            padding: 10px 14px !important;
        }
        
        /* Fix Select2 dropdown text cutoff - Target all Select2 containers */
        .select2-container .select2-selection--single {
            font-size: 18px !important;
            height: auto !important;
            min-height: 48px !important;
            padding: 0 !important;
        }
        
        .select2-container .select2-selection--single .select2-selection__rendered {
            line-height: 1.6 !important;
            font-size: 18px !important;
            padding: 10px 30px 10px 12px !important;
            white-space: normal !important;
            word-wrap: break-word !important;
            overflow: visible !important;
            text-overflow: clip !important;
            display: block !important;
            width: 100% !important;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 100% !important;
            top: 0 !important;
            right: 8px !important;
            width: 24px !important;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow b {
            border-color: #888 transparent transparent transparent !important;
            border-width: 6px 5px 0 5px !important;
            margin-top: -3px !important;
        }
        
        .select2-container--default .select2-results__option {
            font-size: 18px !important;
            padding: 12px 15px !important;
            line-height: 1.6 !important;
            white-space: normal !important;
            word-wrap: break-word !important;
            overflow: visible !important;
        }
        
        .select2-dropdown {
            font-size: 18px !important;
        }
        
        .select2-container--default .select2-results > .select2-results__options {
            max-height: 400px !important;
        }
        
        .select2-container {
            width: 100% !important;
        }
        
        /* Ensure Select2 container doesn't cut off text */
        .select2-container--default .select2-selection--single {
            overflow: visible !important;
        }
        
        .select2-container .select2-selection {
            overflow: visible !important;
        }
        
        /* Fix regular HTML select dropdowns (not Select2) - for tracking_type, expiry_enabled, batch_tracking_enabled, discount_type, warehouse_id */
        select.form-control:not(.select2-hidden-accessible) {
            font-size: 18px !important;
            padding: 10px 35px 10px 12px !important;
            height: auto !important;
            min-height: 48px !important;
            line-height: 1.6 !important;
            -webkit-appearance: none !important;
            -moz-appearance: none !important;
            appearance: none !important;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e") !important;
            background-repeat: no-repeat !important;
            background-position: right 8px center !important;
            background-size: 20px !important;
        }
        
        /* Specific fixes for affected dropdowns */
        #tracking_type,
        #expiry_enabled,
        #batch_tracking_enabled,
        #discount_type,
        #warehouse_id {
            font-size: 18px !important;
            padding: 10px 35px 10px 12px !important;
            height: auto !important;
            min-height: 48px !important;
            line-height: 1.6 !important;
        }
        
        #tracking_type option,
        #expiry_enabled option,
        #batch_tracking_enabled option,
        #discount_type option,
        #warehouse_id option {
            font-size: 18px !important;
            padding: 12px 8px !important;
            white-space: normal !important;
            word-wrap: break-word !important;
            height: auto !important;
        }
        
        .box-body .btn {
            font-size: 18px !important;
            padding: 12px 24px !important;
        }
        
        .box-body .alert {
            font-size: 16px !important;
            padding: 12px 16px !important;
        }
        
        .box-body .table {
            font-size: 17px !important;
        }
        
        .box-body .table th,
        .box-body .table td {
            font-size: 17px !important;
            padding: 12px !important;
        }
        
        .box-body h3,
        .box-body h4 {
            font-size: 24px !important;
        }
        
        .box-body .panel-title {
            font-size: 20px !important;
        }
        
        .box-body .box-title {
            font-size: 22px !important;
        }
        
        .box-body .content-header h1 {
            font-size: 28px !important;
        }
        
        .box-body .content-header small {
            font-size: 18px !important;
        }
        
        .box-body .breadcrumb {
            font-size: 16px !important;
        }
        
        .box-body .text-danger,
        .box-body .text-success,
        .box-body .text-info {
            font-size: 16px !important;
        }
        
        /* Increase sidebar font sizes - Global styles */
        body .sidebar-menu > li > a {
            font-size: 18px !important;
            padding: 15px 5px 15px 15px !important;
        }
        
        body .sidebar-menu > li.header {
            font-size: 16px !important;
            padding: 12px 25px 12px 15px !important;
        }
        
        body .sidebar-menu .treeview-menu > li > a {
            font-size: 16px !important;
            padding: 8px 5px 8px 35px !important;
        }
        
        body .user-panel > .info,
        body .user-panel > .info > a {
            font-size: 18px !important;
        }
        
        body .sidebar a {
            font-size: 18px !important;
        }
        
        body .main-sidebar .sidebar-menu > li > a > .fa,
        body .main-sidebar .sidebar-menu > li > a > .glyphicon,
        body .main-sidebar .sidebar-menu > li > a > .ion {
            font-size: 18px !important;
            width: 24px !important;
        }
      </style>
     
   </body>
</html>

