<div  class="panel panel-primary" id="main_supp">
  <div class="panel-heading"style="font-size:1.2em;">شاشة ادخال و تعديل الاصناف</div>
  <div class="panel-body"style="background-color:#00324d;color:#cce5ff;">
<form method="post" class="form-horizontal" style="float:center;" id="new_item" autocomplete="off">
    <div class="row" style="padding:4px;">
        <input type="hidden" class="form-control" id="item_id" name="item_id" />
        <div class="col-md-2"style="float:right;">
          <label for="item_name" class="control-label"style="float:left;">اسم الصنف</label>
        </div>
        <div class="col-md-5"style="float:right;">
          <input type="text" class="form-control" style="float:right;" id="item_name" name="item_name" placeholder="اسم الصنف"   style="position: absolute; z-index: 2; background: transparent;"/>
          <div id="b_val" style="display:none"></div>
        </div>
        <div class="col-md-2"style="float:right;">
          <label for="ask" class="control-label"style="float:left;">حد الطلب</label>
        </div>
        <div class="col-md-2"style="float:right;">
          <input type="number" style="float:right;" class="form-control" id="ask" name="ask" placeholder="حد الطلب"/>
        </div>
    </div>
  <div class="row" style="padding:4px;">
          <div class="col-md-1"style="float:right;">
          <label for="description" class="control-label"style="float:left;">الوصف</label>
          </div>
          <div class="col-md-5"style="float:right;">
          <input type="text" class="form-control" style="float:right;" id="description" name="description" placeholder="مواصفات الصنف"/>
          </div>
          <div class="col-md-2"style="float:right;">
          <label for="kind" class="control-label"style="float:left;">ماركة السيارة</label>
          </div>
          <div class="col-md-3"style="float:right;">
          <select  class="form-control" id="kind" name="kind">
         <option value= "جميع السيارات" >جميع السيارات</option>
         <?php
         include "../actions/dbPDO.php";
         $sql3 =$db->prepare("SELECT DISTINCT brand from cars") ;
         $sql3->execute();
           if($sql3->rowCount()>0)
          {
             while($row = $sql3->fetch()){
                   $id = $row["brand"];
         echo "<option value= $id >$id</option>";
               }} ?>
         </select>
          </div>
  </div>
  <div class="row" style="padding:4px;">
        <div class="col-md-2"style="float:right;">
        <label for="part_no" class="control-label"style="float:left;">رقم القطعة</label>
        </div>
        <div class="col-md-3"style="float:right;">
        <input type="text" class="form-control" style="float:right;" id="part_no" name="part_no" placeholder="بارت نمبر"/>
        </div>
        <div class="col-md-3"style="float:right;">
        <label for="next_km" class="control-label"style="float:left;"> العمر الإفتراضي </label>
        </div>
        <div class="col-md-3"style="float:right;">
        <input type="number" class="form-control" style="float:right;" id="next_km" name="next_km" placeholder="بالكيلومتر "/>
        </div>
  </div>
  <div class="row" style="padding:4px;" >
    <div class="col-xs-2 col-md-2"style="float:right;">
    <label for="key_words" class="control-label"style="float:left;">كلمات مفتاحية</label>
  </div>
  <div class="col-xs-10 col-md-10" style="float:right ;">
    <input type="text" class="form-control" style="float:right;" id="key_words" name="key_words" placeholder="كلمات بحثية"/>
    </div>
  </div>
  <p><br/></p>
  <div class="form-group">
    <div class="col-md-3"style="float:right;">
      <input style="float:right ;" type="button" id="add_button" name="add_button" class="btn btn-success" value="حفظ الصنف الجديد"/>
      <input style="float:right ;" type="hidden" id="update_item" name="update_item" class="btn btn-info" value="تحديث بيانات "/>
    </div>
    <div class="col-md-2"style="float:left;">
      <input  type="hidden" id="prices" name="prices" class="btn btn-success" value="أسعار الفواتير"/>
    </div>
    <div class="col-md-1"style="float:left;">
      <input  type="hidden" id="prices2" class="btn btn-info" value="صرف للسيارات"/>
    </div>
  </div>
</form>

</div>
</div>
<!-- panel body style -->
<div class="table-responsive">
     <table style="color:#FAFAFA ;" class="table table-bordered table-hover">
          <tr>
               <th class="text-center" width="5%">حركة</th>
               <th class="text-center" width="24%">الصنف</th>
               <th class="text-center" width="52%">موصفات الصنف</th>
               <th class="text-center" width="12%">نوع السيارة</th>
               <th class="text-center" width="7%">حد الطلب</th>
              </tr>
<?php

$output = array();
    $item_sr = $db->prepare("SELECT item_id , item_name FROM items");
    $item_sr->execute();
    $i=0;
    if($item_sr->rowCount()>0)
      {
         while($row = $item_sr->fetch())
         {
             $output[$i] = array(
                           "value" => $row["item_name"],
                           "data" => $row["item_id"]
                           );  $i++ ; }
        }
    else  {$output[0]= 'لا يوجد صنف بهذا الاسم';}
?>
<div><!-- avilable Branches -->
<?php
$output2 = '';
$myItem = $db->prepare('SELECT item_id, item_name , description , kind , ask
                          FROM items ORDER BY item_id DESC LIMIT 40');
$myItem->execute();
if($myItem->rowCount()>0)
{
  while($row = $myItem->fetch())
  {
    $id = $row["item_id"];
       $output2 .= '  <tr>
              <td><input type="button"  idd='.$id.'  name="item_update" class="btn btn-info btn-xs item_update" value="تعديل"/></td>
                 <td class="text-center">' . $row['item_name'] . '</td>
                 <td class="text-center">' . $row['description'] . '</td>
                 <td class="text-center">' . $row['kind'] . '</td>
                 <td class="text-center">' . $row['ask'] . '</td>
              </tr> ';}
}
else
{
  $output2 .= '<tr> <td colspan="5">لا يوجد سجلات ...</td></tr>';
}
echo $output2;
?>
</table>
  </div>
</div><!-- end of avilable items -->
<script>
$(document).ready(function(){
  // var arr=  JSON.parse();
  //
function safeJSONParse(jsonString) {
    if (typeof jsonString !== 'string') {
        return jsonString;
    }
    
    try {
        return JSON.parse(jsonString);
    } catch (error) {
        console.warn('Initial JSON parse failed, attempting to sanitize...');
        
        // Attempt to fix common issues
        const sanitized = jsonString
            .replace(/\\['"\\\/bfnrtu]/g, function(match) {
                const escapes = {
                    "\\'": "'",
                    '\\"': '"',
                    '\\\\': '\\',
                    '\\/': '/',
                    '\\b': '\b',
                    '\\f': '\f',
                    '\\n': '\n',
                    '\\r': '\r',
                    '\\t': '\t'
                };
                return escapes[match] || match;
            })
            .replace(/\\u([0-9a-fA-F]{4})/g, function(match, hex) {
                return String.fromCharCode(parseInt(hex, 16));
            });
        
        try {
            return JSON.parse(sanitized);
        } catch (secondError) {
            console.error('Failed to parse JSON even after sanitization:', secondError);
            throw new Error('Invalid JSON data');
        }
    }
}

// Usage
// document.addEventListener('DOMContentLoaded', function() {
//     try {
//         const yourData = safeJSONParse(yourJSONString);
//         // Process your data here
//     } catch (error) {
//         console.error('Failed to process JSON:', error);
//         // Handle the error appropriately for your application
//     }
// });
  //
var arr = safeJSONParse('<?php echo json_encode($output) ; ?>');
  $('#item_name').autocomplete({
	 lookup: arr,
   maxHeight : 200,
   onSelect: function(suggestion) {
      //  $('#b_val').html(suggestion.data);
       one_item(suggestion.data);
         },
   onInvalidateSelection: function() {
       $('#b_val').html('You selected: none');
   }
});
$("#add_button").click(function(event){
  event.preventDefault();
  $.ajax({
    url     : "wh/new45Item.php",
    method  : "POST",
    data    :$("form").serialize(),
    success : function(data){
    $("#signup_msg").html(data);
    $("#signup_msg").delay(1500).slideUp(function(){
       // $("#signup_msg").html('');
       $('#site').load("wh/newItem.php");
      });
  },
    error   :function(result){
      alert(result.statusText);
      }
  })
}); //end of signup_button ajax code

$(".item_update").click(function(event){
      event.preventDefault();
  var item_id = $(this).attr("idd");
    one_item(item_id);
});//update item

function one_item(item_id){
  $.ajax({
  url:"wh/item_single.php",
  method:"POST",
  data:{item_id:item_id},
  dataType:"json",
  success:function(data)
  {
    $('#item_id').val(data.item_id);
    $('#item_name').val(data.item_name);
    $('#description').val(data.description);
    $('#kind').val(data.kind);
    $('#ask').val(data.ask);
    $('#part_no').val(data.part_no);
    $('#next_km').val(data.next_km);
    $('#key_words').val(data.key_words);
    $('#add_button').attr("type","hidden");
    $('#update_item').attr("type","button");
    $('#prices').attr("type","button");
    $('#prices2').attr("type","button");
  }
});
}
$("#prices").click(function(event){
  event.preventDefault();
  var id = $("#item_id").val();
    window.open("wh/item_prices.php?id="+id, '_blank');
});
$("#prices2").click(function(event){
  event.preventDefault();
  var id = $("#item_id").val();
    window.open("wh/item2prices.php?id="+id, '_blank');
});

$("#update_item").click(function(event){
  event.preventDefault();
  $.ajax({
    url     : "wh/item_update.php",
    method  : "POST",
    data    :$("form").serialize(),
    success : function(data){
    $("#signup_msg").html(data);
    $("#signup_msg").delay(5000).slideUp(function(){  $("#signup_msg").html(''); });
    $('#site').load("wh/newItem.php");
  },
    error   :function(result){
      alert(result.statusText);
      }
  })
}); //end of update_branch ajax code ?act='update'
});

</script>
