<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view_pro_attr";
$form_action	= "insert";
$button_value 	= "Save";
$table_name 	= "bays";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Add Item Attributes ";
$organisation_date = date("d-m-Y");
$from = $_REQUEST['from'];
$product_template_name 	= isset($_REQUEST['pro_temp_id']) ? $_REQUEST['pro_temp_id'] : "";
################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string","admin_id","new_fields"));    
    
	$created_on				= date("Y-m-d H:i:s");	    
	$created_by 			=$_SESSION['admin_user_id'];
    
	$newFields 				= $_REQUEST["new_fields"];
    $pro_template_id 		= $_REQUEST["pro_template_id"]; 
    
    foreach ($newFields as $field) {
        $fieldName = $field["name"];
        $fieldType = $field["type"];
        
         $sql = "INSERT INTO product_attributes(pro_template_id, attribute_name ,data_type, created_by,created_on) VALUES ('$pro_template_id','$fieldName','$fieldType','$created_by','$created_on')";
		 mysqli_query($conn, $sql);
    }
    
   
	header('Location: index?page=add_product&pro_temp_id=' .$pro_template_id);
    $_SESSION['info_message'] = "Item Attributes added sucessfully";
	exit;
	
}

################################################# END INSERT #################################################

################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];
	
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Item Attributes ";
	$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
   /*  $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);
	$row_edit = utility::validate_crypt_data($row_edit);
	
    $bay_name			= $row_edit['bay_name'];
     */
    
}
################################################# END EDIT ################################################# 


################################################## START UPDATE ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
    utility::addslashesOnAllInput(array("query_string","admin_id","new_fields"));
    
    $id             		= $_REQUEST['id'];
    $newFields      		= $_REQUEST["new_fields"];
    $pro_template_id        = $_REQUEST["pro_template_id"]; 
    $updated_by    			= $_SESSION['user_id'];
    $created_on				= date("Y-m-d H:i:s");	   
	
    foreach ($newFields as $field) {
        $fieldName = $field["name"];
        $fieldType = $field["type"];
        
        $sql = "INSERT INTO product_attributes(pro_template_id, attribute_name ,data_type, created_by,created_on,updated_by) VALUES ('$pro_template_id','$fieldName','$fieldType','$created_by','$created_on','$updated_by')";
		 mysqli_query($conn, $sql);
    }
		header('Location: index?page=view_pro_attr&pro_temp_id=' .$pro_template_id);
        $_SESSION['info_message'] = "Item Attributes added successfully";
}

################################################# END UPDATE ################################################# 
	$sql1= "SELECT * FROM product_template WHERE id = '".$_REQUEST['pro_temp_id']."'";
    $result = mysqli_query($conn,$sql1);
    $row_ = mysqli_fetch_array($result);
	$row_ = utility::validate_crypt_data($row_);
	
	$part_number 							= $row_['part_number'];
	$part_number_revision 					= $row_['part_number_revision'];
	$part_number_category 					= $row_['part_number_category'];
	$stock_part 							= $row_['stock_part'];
	$current_product_range					= $row_['current_product_range'];
	$is_taxable 							= $row_['is_taxable'];
	$sales_item_code 						= $row_['sales_item_code'];
	$sales_price 							= $row_['sales_price'];
	$product_group							= $row_['product_group'];
	$product_group_short_code 				= $row_['product_group_short_code'];
	$parent_product_groups 					= $row_['parent_product_groups'];
	$description_external 					= $row_['description_external'];
	$description_internal 					= $row_['description_internal'];
	$currency								= $row_['currency'];
	$part_checked 							= $row_['part_checked'];
	$part_checked_date 						= $row_['part_checked_date'];
	$part_requires_attention 				= $row_['part_requires_attention'];
	$part_attention_notes 					= $row_['part_attention_notes'];
	$components_costs 						= $row_['components_costs'];
	$costing_method 						= $row_['costing_method'];
	$labour_hours 							= $row_['labour_hours'];
	$labour_hours_total_parts 				= $row_['labour_hours_total_parts'];
	$total_cost 							= $row_['total_cost'];
	$bill_of_materials 						= $row_['bill_of_materials'];
	$where_used 							= $row_['where_used'];
	$qr_code 								= $row_['qr_code'];
	$barcode 								= $row_['barcode'];
	$image1									= $row_['image1'];
	$image2 								= $row_['image2'];
	$image3 								= $row_['image3']; 
	
?>
<style>
em {
    color: red;
    font-size: 20px;
    position: absolute;
}
</style>
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>
                    <?=$page_name;?>
                </h1>
            </div>
            <div class="col-sm-6">
                <?
			$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
			if(isset($from) && $from == "view_customer_details"){
				$query_string = str_ireplace("page=add", "page=view_customer_details", $query_string);
			}else {
				$query_string = str_ireplace("page=add_pro_attr", "page=view_pro_attr", $query_string);
			}
				
			?>
                <button type="button" id="back" name="back" value="back"
                    style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-success"
                    onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
            </div>
        </div>
    </div>
</section>
<section class="content">
    <div class="row">
        <div class="col-12">
           
            <!----------------------- End Message ------------------------------->
            <!-- general form elements -->
            <div class="card">
                <form class="" method="post" name="form1" id="form1"
                    action="index?page=add_pro_attr&action=<? echo $form_action; ?>" onsubmit="return validateForm(this)"
                    enctype="multipart/form-data">
                    <div class="card-body">
					 <div class="row">
						<div class="col-lg-12 col-sm-12">
							<div class="form-group">
								<label for="bay_name" class="col-sm-2 control-label">Item Template Name <em>*</em></label>
								<div class="">
									<? echo $gsi->getProductTempateList("pro_template_id",$product_template_name,"100%",false,"form-control select2","required"); ?>
								</div>
							</div>
						</div>
					  </div>
					   <div class="row">
							<div class="text-center col-lg-12 mb-2">
								<strong class="h5"> Fixed Fields</strong>
								<hr style="background-color:#fa4a14; height:1px;">
							</div>
                           <?if($row_['part_number']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_number" name="part_number" value="1" <?php echo ($part_number == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Number</label>
								</div>
							</div>
							<?}if($row_['part_number_revision']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_number_revision" name="part_number_revision" value="1" <?php echo ($part_number_revision == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Number Revision</label>
								</div>
							</div>
							<?}if($row_['part_number_category']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_number_category" name="part_number_category" value="1" <?php echo ($part_number_category == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Number Category</label>
								</div>
							</div>
							<?}if($row_['stock_part']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="stock_part" name="stock_part" value="1" <?php echo ($stock_part == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Stock Part</label>
								</div>
							</div>
							<?}if($row_['current_product_range']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="current_product_range" name="current_product_range" value="1" <?php echo ($current_product_range == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Current Item Range</label>
								</div>
							</div>
							<?}if($row_['is_taxable']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="is_taxable" name="is_taxable" value="1" <?php echo ($is_taxable == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Is Taxable</label>
								</div>
							</div>
							<?}if($row_['sales_item_code']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="sales_item_code" name="sales_item_code" value="1" <?php echo ($sales_item_code == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Sales Item Code</label>
								</div>
							</div>
							<?}if($row_['sales_price']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="sales_price" name="sales_price" value="1" <?php echo ($sales_price == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Sales Price</label>
								</div>
							</div>
							<?}if($row_['product_group']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="product_group" name="product_group" value="1" <?php echo ($product_group == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Item Group</label>
								</div>
							</div>
							<?}if($row_['product_group_short_code']==1){?>
							<div class="col-lg-3 col-sm-3 col-md-3">
								<div>
									<input type="checkbox" class="" id="product_group_short_code" name="product_group_short_code" value="1" <?php echo ($product_group_short_code == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Item Group Short Code</label>
								</div>
							</div>
							<?}if($row_['parent_product_groups']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="parent_product_groups" name="parent_product_groups" value="1" <?php echo ($parent_product_groups == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Parent Item Groups</label>
								</div>
							</div>
							<?}if($row_['description_external']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="description_external" name="description_external" value="1" <?php echo ($description_external == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Description External</label>
								</div>
							</div>
							<?}if($row_['description_internal']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="description_internal" name="description_internal" value="1" <?php echo ($description_internal == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Description Internal</label>
								</div>
							</div>
							<?}if($row_['currency']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="currency" name="currency" value="1" <?php echo ($currency == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Currency</label>
								</div>
							</div>
							<?}if($row_['part_checked']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_checked" name="part_checked" value="1" <?php echo ($part_checked == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Checked</label>
								</div>
							</div>
							<?}if($row_['part_checked_date']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_checked_date" name="part_checked_date" value="1" <?php echo ($part_checked_date == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Checked Date</label>
								</div>
							</div>
							<?}if($row_['part_requires_attention']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_requires_attention" name="part_requires_attention" value="1" <?php echo ($part_requires_attention == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Requires Attention</label>
								</div>
							</div>
							<?}if($row_['part_attention_notes']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="part_attention_notes" name="part_attention_notes" value="1" <?php echo ($part_attention_notes == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Part Attention Notes</label>
								</div>
							</div>
							<?}if($row_['components_costs']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="components_costs" name="components_costs" value="1" <?php echo ($components_costs == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Components Costs</label>
								</div>
							</div>
							<?}if($row_['costing_method']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="costing_method" name="costing_method" value="1" <?php echo ($costing_method == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Costing Method</label>
								</div>
							</div>
							<?}if($row_['labour_hours']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="labour_hours" name="labour_hours" value="1" <?php echo ($labour_hours == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Labour Hours</label>
								</div>
							</div>
							<?}if($row_['labour_hours_total_parts']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="labour_hours_total_parts" name="labour_hours_total_parts" value="1" <?php echo ($labour_hours_total_parts == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Labour Hours Total Parts</label>
								</div>
							</div>
							<?}if($row_['total_cost']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="total_cost" name="total_cost" value="1" <?php echo ($total_cost == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Total Cost</label>
								</div>
							</div>
							<?}if($row_['bill_of_materials']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="bill_of_materials" name="bill_of_materials" value="1" <?php echo ($bill_of_materials == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Bill of Materials</label>
								</div>
							</div>
							<?}if($row_['where_used']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="where_used" name="where_used" value="1" <?php echo ($where_used == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Where Used</label>
								</div>
							</div>
							<?}if($row_['qr_code']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="qr_code" name="qr_code" value="1" <?php echo ($qr_code == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">QR Code</label>
								</div>
							</div>
							<?}if($row_['barcode']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="barcode" name="barcode" value="1" <?php echo ($barcode == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Barcode</label>
								</div>
							</div>
							<?}if($row_['image1']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="image1" name="image1" value="1" <?php echo ($image1 == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Image1</label>
								</div>
							</div>
							<?}if($row_['image2']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="image2" name="image2" value="1" <?php echo ($image2 == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Image2</label>
								</div>
							</div>
							<?}if($row_['image3']==1){?>
							<div class="col-lg-3">
								<div>
									<input type="checkbox" class="" id="image3" name="image3" value="1" <?php echo ($image3 == 1) ? 'checked' : ''; ?> style="height: 17px; width: 17px;" disabled>
									<label class="control-label">Image3</label>
								</div>
							</div>
							<?}?>
						</div>
						<div class="text-center col-lg-12 mb-2 mt-2"><strong class="h5">Item Template Attributes</strong>
							<hr style="background-color:#fa4a14; height:0.6px;"></div>
					  <div id="formFields" class="row">
					    <?$query = "SELECT * FROM product_attributes WHERE pro_template_id ='".$_REQUEST['pro_temp_id']."' ORDER BY id";
					   
					    $sql=mysqli_query($conn,$query);
					    $result=mysqli_num_rows($sql);
							if($result>0){
							   while($row =mysqli_fetch_array($sql)){ 
							   $row=utility::validate_crypt_data($row);?>
								<div class="col-lg-6">
								 <label class="control-label"><?=ucwords($row['attribute_name']);?>:</label>
								 <input type="text" id=""  class="form-control" name="" placeholder="<?=ucwords($row['attribute_name']);?>" value="" readonly>
								</div>
							<?}}?>
						   
					  </div>
					  <div id="custom_fields">
						<div class="custom_field">
						 <!--<div class="row">
						   <div class="col-lg-6 col-sm-12">
							<label class="control-label" for="field_name_1">Field Name:</label>
							<input type="text"id="field_name_1" name="new_fields[0][name]"class="form-control" required placeholder="Field Name">
						   </div>
							<div class="col-lg-6 col-sm-12">
								<label for="field_type_1">Field Type:</label>
								<select id="field_type_1" class="form-control" name="new_fields[0][type]" required>
									
									<option value="VARCHAR(255)">VARCHAR</option>
									<option value="INT">INTEGER</option>
									<option value="TEXT">TEXT</option>
									 Add more options for other field types 
								</select>
							</div>
						</div>-->
						</div>
					   </div>
					   <div class="row mt-3">
						  <div class="col-lg-5 col-sm-12 col-md-5">
						  </div>
						  <div class="col-lg-6 col-sm-12 col-md-6">
						  </div>
						 <div class="col-lg-1 col-md-1 col-sm-1">
						   <button type="button" class="btn btn-success" onclick="addCustomField()">+ Field</button>
						 </div>
					  </div>
                    </div><!-- /.box-body -->
                    <div class="card-footer">
                        <input type="hidden" id="id" name="id" value="<?php echo $id;?>">
                        <input type="hidden" id="from" name="from" value="<?php echo $from;?>">
                        <input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string;?>">
                        <button type="submit" id="submit" name="submit" value="<?php echo $button_value;?>"
                            class="btn btn-primary"><?php echo $button_value;?>
                            <i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
                        </button>
						<?if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){?>
						<?}else{?>
							<button type="submit" id="submit1" name="submit" value="<?php echo $button_value;?>"
                            class="btn btn-success">Next
                            <i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div1"></i>
                        </button>
						<?}?>
                    </div>
                </form>
            </div><!-- /.box -->
        </div>
    </div>
</section>
<script>
   /* var jsonData = 
      <?=$fields_added;?>

    function createFormFields(jsonData) {
      var formFields = '';
      $.each(jsonData, function(key, value) {
        var inputType = (value.type === 'TEXT') ? 'text' : 'text';
        var labelName = value.name.charAt(0).toUpperCase() + value.name.slice(1);
        formFields += '<div class="col-lg-6"><label class="control-label">' + labelName + ':</label>';
        formFields += '<input type="' + inputType + '" id="' + value.name + '"  class="form-control" name="' + value.name + '" placeholder="' + labelName + '" value="' + value.name + '" readonly></div>';
      });
      return formFields;
    }

    var formFieldsHTML = createFormFields(jsonData);
    $('#formFields').html(formFieldsHTML);

    $('#jsonDataForm').submit(function(event) {
      event.preventDefault();
      var formData = {};
      $('#jsonDataForm input').each(function() {
        formData[$(this).attr('name')] = $(this).val();
      });
      console.log(formData);
    }); */
	$('#form1').submit(function(event) {
			$('#pro_template_id').prop('disabled', false);
			$("#submit").attr("disabled", true);
			$('#page_load_div').show();
			$('#form1').submit();
	});
	$('#pro_template_id').prop('disabled', true);

    let fieldCounter = 1;

    function addCustomField() {
        fieldCounter++;

        let customFieldsDiv = document.getElementById("custom_fields");

        let newFieldDiv = document.createElement("div");
        newFieldDiv.className = "custom_field row";

        newFieldDiv.innerHTML = `
            <div class="col-lg-6 col-sm-12">
                <label class="control-label" for="field_name_${fieldCounter}">Field Name:</label>
                <input type="text" id="field_name_${fieldCounter}" name="new_fields[${fieldCounter - 1}][name]" class="form-control" placeholder="Field Name" required>
            </div>
            <div class="col-lg-5 col-sm-12">
                <label class="control-label" for="field_type_${fieldCounter}">Field Type:</label>
                <select id="field_type_${fieldCounter}" name="new_fields[${fieldCounter - 1}][type]" class="form-control" required>
                    <option value="VARCHAR(255)">VARCHAR</option>
                    <option value="INTEGER">INTEGER</option>
                    <option value="TEXT">TEXT</option>
                    <option value="DATETIME">DATE</option>
                    <!-- Add more options for other field types -->
                </select>
            </div>
            <div class="col-lg-1">
			  <label class="text-light">XX</label>
                <button type="button" class="btn btn-danger " onclick="removeCustomField(this)">- Field</button>
            </div>
        `;

        customFieldsDiv.appendChild(newFieldDiv);
    }

    function removeCustomField(button) {
        let fieldToRemove = button.parentNode.parentNode;
        fieldToRemove.parentNode.removeChild(fieldToRemove);
    }
		
	
	
</script>