<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$form_action	= "insert";
$button_value 	= "Add";
$table_name 	= "enquiry_management";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Add Enquiry";
$from = $_REQUEST['from'];
$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(enquiry_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM enquiry_management");
$rr_row = mysqli_fetch_assoc($rr_query);
$enquiry_no = 'ENQ-' . str_pad($rr_row['new_enq'], 3, '0', STR_PAD_LEFT);
################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string"));
	
	
    $customer					= $_REQUEST['customer'];
	$other_customer_name		= $_REQUEST['other_customer_name'];
	$enquiry_no					= $_REQUEST['enquiry_no'];
	$other_customer_phone		= utility::app_crypt($_REQUEST['other_customer_phone'],'e');
	$other_customer_email		= utility::app_crypt($_REQUEST['other_customer_email'],'e');
	$part_number				= $_REQUEST['part_number'];	
	$part_description			= $_REQUEST['part_description'];	
	$model_number				= $_REQUEST['model_number'];	
	$drawing_issue				= $_REQUEST['drawing_issue'];
	$volume						= $_REQUEST['volume'];
	$type						= $_REQUEST['type'];
	$enquiry_notes				= $_REQUEST['enquiry_notes'];
	$created_by					= $_SESSION['user_id'];
	$created_on					= date("Y-m-d H:i:s");	
	$updated_by					= $_SESSION['user_id'];


    $customer 		= $_REQUEST['customer'];
		if($customer =='-1'){
			$sql = "customer_name = '".$other_customer_name."', contact_1_phone_no = '$other_customer_phone', contact_1_email_address = '".$other_customer_email."',created_by = '".$created_by."',updated_by = '".$updated_by."'";
			$sql= "INSERT INTO client_management SET ".$sql;
			mysqli_query($conn,$sql);
			$client_id = mysqli_insert_id($conn);
			$customer = utility::getTableFieldById("client_management","id","id",$client_id);
		}
	
	$sql = "customer = '".$customer."', other_customer_name = '".$other_customer_name."', enquiry_no = '".$enquiry_no."', other_customer_phone = '".$other_customer_phone."',other_customer_email = '".$other_customer_email."', part_number = '".$part_number."',part_description = '".$part_description."',model_number = '".$model_number."', drawing_issue = '".$drawing_issue."', volume = '".$volume."', type = '".$type."', enquiry_notes = '".$enquiry_notes."',created_on = '".$created_on."', created_by = '".$created_by."', updated_by = '".$updated_by."'";
	

	$sql= "INSERT INTO $table_name SET ".$sql;

	mysqli_query($conn,$sql);
	$enquiry_id = mysqli_insert_id($conn);
	
	
	$_SESSION['info_message'] = "Enquiry added successfully";
	header("Location: $file_name");
    exit();
}
################################################# END INSERT #################################################

################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];
	$enquiry_id = utility::app_crypt($_REQUEST['enquiry_id'],'d');
		if($_REQUEST['id'] != $enquiry_id){
			die("Invaild URL");
		}
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Enquiry";
	$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);
	
    $customer					= $row_edit['customer'];
	$other_customer_name		= $row_edit['other_customer_name'];
	$enquiry_no					= $row_edit['enquiry_no'];
	$other_customer_phone		= $row_edit['other_customer_phone'];
	$other_customer_email		= $row_edit['other_customer_email'];
	$part_number				= $row_edit['part_number'];	
	$part_description			= $row_edit['part_description'];	
	$model_number				= $row_edit['model_number'];
	$drawing_issue				= $row_edit['drawing_issue'];
	$volume						= $row_edit['volume'];
	$type						= $row_edit['type'];
	$enquiry_notes				= $row_edit['enquiry_notes'];
	
}
################################################# END EDIT ################################################# 


################################################## START UPDATE ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string"));
	
	$id  						= $_REQUEST['id'];
    $customer					= $_REQUEST['customer'];
	$other_customer_name		= $_REQUEST['other_customer_name'];
	$enquiry_no					= $_REQUEST['enquiry_no'];	
	$other_customer_phone		= utility::app_crypt($_REQUEST['other_customer_phone'],'e');
	$other_customer_email		= utility::app_crypt($_REQUEST['other_customer_email'],'e');
	$part_number				= $_REQUEST['part_number'];	
	$part_description			= $_REQUEST['part_description'];	
	$model_number				= $_REQUEST['model_number'];
	$drawing_issue				= $_REQUEST['drawing_issue'];
	$volume						= $_REQUEST['volume'];
	$type						= $_REQUEST['type'];
	$enquiry_notes				= $_REQUEST['enquiry_notes'];

	$updated_by		 		    = $_SESSION['user_id'];
	
	$sql = "customer = '".$customer."', other_customer_name = '".$other_customer_name."', enquiry_no = '".$enquiry_no."',  other_customer_phone = '".$other_customer_phone."',  other_customer_email = '".$other_customer_email."', part_number = '".$part_number."',part_description = '".$part_description."',model_number = '".$model_number."', drawing_issue = '".$drawing_issue."', volume = '".$volume."', type = '".$type."', enquiry_notes = '".$enquiry_notes."',updated_by = '".$updated_by."'";
	$sql= "UPDATE $table_name SET ".$sql." WHERE id = '".$id."'";
    mysqli_query($conn,$sql);
	
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
	
  	$query_string = str_ireplace("page=add", "page=view", $query_string);
	$query_string = "&".$query_string;
	
	$enquiry_id = urlencode(utility::app_crypt($id,'e'));
	
	$_SESSION['info_message'] = "Enquiry updated successfully";
	if(isset($from) && $from == "view_enquiry_details"){
		header("Location: index?page=view_enquiry_details&from=view_customer&enquiry_id=$enquiry_id&id=$id");
		exit();
	}
	
    header("Location: $file_name$query_string");
    exit();
}
################################################# END UPDATE ################################################# 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}

fieldset {
    border-top: 4px solid #dedede; 
    border-right: 1px solid #dedede;
    border-bottom: 1px solid #dedede; 
    border-left: 1px solid #dedede; 
    padding: 15px;
    margin-bottom: 10px;
}

legend {
    width: auto;
    color: #a423a4;
}
</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_enquiry_details"){
				$query_string = str_ireplace("page=add", "page=view_enquiry_details", $query_string);
			}else {
				$query_string = str_ireplace("page=add", "page=view", $query_string);
			}
				
			?>
			<button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-primary" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>
<section class="content">
	<div class="row">
		<div class="col-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? } ?>
			<!----------------------- End Message ------------------------------->
			<!-- general form elements -->
              <div class="card">
                <form class="" method="post" name="form1" id="form1" action="index?page=add&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="row">
								<div class="form-group col-lg-4">
									<div class="">
									  <label class="control-label" for="Customer">Customer<em>*</em></label>
										<? $gsi->getCustomerList("customer",$customer,"100%",false,"form-control select2","required"); ?>
									</div>
								</div>
								<div class="form-group col-lg-4">
								</div>
								<div class="form-group col-lg-4">
								  <div class="">
									<label class="control-label" for="Enquiry No">Enquiry No.<em>*</em></label>
									 <input type="text" id="enquiry_no" name="enquiry_no" value="<?php echo $enquiry_no;?>" class="form-control" placeholder="Enquiry No" required readonly>
								 </div>
								</div>
							</div>
							<? $display_div = ($customer == -1) ? "block" : "none"; ?>
					       <div class="" id="otherCustomerFields" style="display:<?=$display_div;?>;">
							<div class="row">
								<div class="form-group col-lg-4">
									<label class="control-label" for="Other Customer Name">Other Customer Name<em></em></label>
									<input type="text" id="other_customer_name" name="other_customer_name" value="<?php echo $other_customer_name;?>" class="form-control" placeholder="Other Customer Name">
								</div>
								<div class="form-group col-lg-4">
								    <label class="control-label" for="Other Customer Phone">Other Customer Phone<em></em></label>
									<input type="text" id="other_customer_phone" name="other_customer_phone" value="<?php echo $other_customer_phone;?>" class="form-control" pattern="[0-9 ]*" placeholder="Other Customer Phone">
									<span id="phone_validate" style="color:red; display:none;">Please enter a valid phone number (digits only).</span>
								</div>
								<div class="form-group col-lg-4">
									<label class="control-label" for="Other Customer Email">Other Customer Email<em></em></label>
									<input type="text" id="other_customer_email" name="other_customer_email" value="<?php echo $other_customer_email;?>" class="form-control" placeholder="Other Customer Email">
									<span class="invalid-feedback" id="customer_email_validate">Invalid email format. Must contain '@'</span>
								</div>
						    </div>
						    </div>
							<div class="">
							<div class="row">
							 <div class="form-group col-lg-4">
								<label class="control-label" for="Part Number">Part Number<em></em></label>
								<div class="">
									<input type="text" id="part_number" name="part_number" value="<?php echo $part_number;?>" class="form-control" placeholder="Part Number">
								</div>
							</div>
							<div class="form-group col-lg-4">
								<label class="control-label" for="Part Description">Part Description<em></em></label>
								<div class="">
									<input type="text" id="part_description" name="part_description" value="<?php echo $part_description;?>" class="form-control" placeholder="Part Description">
								</div>
							</div>
							<div class="form-group col-lg-4">
								<label class="control-label" for="Model Number">Model Number<em></em></label>
								<div class="">
									<input type="text" id="model_number" name="model_number" value="<?php echo $model_number;?>" class="form-control" placeholder="Model Number">
								</div>
							</div>
							</div>
							</div>
							<div class="">
							  <div class="row">
								<div class="form-group col-lg-4">
								  <label class="control-label" for="Drawing Issue">Drawing Issue<em></em></label>
								  <div class="">
									<input type="text" id="drawing_issue" name="drawing_issue" value="<?php echo $drawing_issue;?>" class="form-control" placeholder="Drawing Issue">
								  </div>
								</div>
								<div class="form-group col-lg-4">
								  <label class="control-label" for="Volume">Volume<em></em></label>
								  <div class="">
									<input type="text" id="volume" name="volume" value="<?php echo $volume;?>" class="form-control" placeholder="Volume">
								  </div>
								</div>
								<div class="form-group col-lg-4">
								  <label class="control-label" for="Type">Type<em></em></label>
								  <div class="">
									<? $gsi->getEnquiryTypeList("type",$type,"100%",false,"form-control select2",""); ?>
								  </div>
								</div>
							  </div>
							  </div>
							<div class="">
							<div class="row">
								<div class="form-group col-lg-12">
								  <label class="control-label" for="Enquiry Notes">Enquiry Notes<em></em></label>
								  <div class="">
									<textarea id="enquiry_notes" name="enquiry_notes" rows="3" cols="50" maxlength="500" class="form-control" placeholder="Enquiry Notes"  style="resize: vertical;"><?php echo $enquiry_notes;?></textarea>
								  </div>
								</div>
							</div>
							</div>
						 </div>
					  </div><!-- /.row -->
                  </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">Submit
						<i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
					</button>
                  </div>
                </form>
              </div><!-- /.box -->
		</div>
	</div>
</section>
<script type="text/javascript">

$(function(){
	$('#form1').submit(function(){
		//$(this).addClass('disabled');
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
	});	
	$('#other_customer_email').blur(function() {
        var email = $(this).val();
        var errorSpan = $('#customer_email_validate');
        if (email === '') {
			errorSpan.hide(); 
		} else if (email.includes('@')) {
			errorSpan.hide(); 
		} else {
			errorSpan.show(); 
		}
	});
	$('#customer').change(function(){
		var customer = $(this).val();
		if(customer == -1){ 
			$('#otherCustomerFields').show();
		}else{
			$('#otherCustomerFields').hide();
		}
	});	
	$('#other_customer_phone').blur(function() {
		var phone = $(this).val();
		var errorSpan = $('#phone_validate'); 
		var phoneRegex = /^[\d\s]+$/; 
		if (phone === '') {
			errorSpan.hide();
		} else if (phoneRegex.test(phone)) {
			errorSpan.hide(); 
		} else {
			errorSpan.show(); 
		}
	});

});
</script>