<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$form_action	= "insert";
$button_value 	= "Add";
$table_name 	= "quotation";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Add Quotation";
$from = $_REQUEST['from'];
$enquiry_id = $_REQUEST['enq_id'];
$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(quotation_number, 5) AS UNSIGNED)), 0) + 1 AS new_quot FROM quotation");
$rr_row = mysqli_fetch_assoc($rr_query);
$quotation_number = 'QAF-' . str_pad($rr_row['new_quot'], 3, '0', STR_PAD_LEFT);

################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string"));
	
	
    $quotation_number			= $_REQUEST['quotation_number'];
    $customer_id				= $_REQUEST['customer_id'];
	$enquiry_id					= $_REQUEST['enquiry_id'];
	$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'];
	$anuual_value				= $_REQUEST['anuual_value'];
	$from	  				    = $_REQUEST['from'];

	$created_by					= $_SESSION['user_id'];
	$created_on					= date("Y-m-d H:i:s");	
	$updated_by					= $_SESSION['user_id'];
	$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(quotation_number, 5) AS UNSIGNED)), 0) + 1 AS new_quot FROM quotation");
	$rr_row = mysqli_fetch_assoc($rr_query);
	$quotation_number = 'QAF-' . str_pad($rr_row['new_quot'], 3, '0', STR_PAD_LEFT);

	
	$sql = "customer_id = '".$customer_id."',quotation_number = '".$quotation_number."', enquiry_id = '".$enquiry_id."',part_number = '".$part_number."',part_description = '".$part_description."',model_number = '".$model_number."', drawing_issue = '".$drawing_issue."', volume = '".$volume."', type = '".$type."', anuual_value = '".$anuual_value."',created_on = '".$created_on."', created_by = '".$created_by."', updated_by = '".$updated_by."'";
	

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

	mysqli_query($conn,$sql);
	$qot_id = mysqli_insert_id($conn);
	
	$sql1= "UPDATE enquiry_management SET quotation_status = '1' WHERE id = '$enquiry_id'";
	mysqli_query($conn,$sql1); 
	
	if($from != "enquiry"){
	$eq_query = mysqli_query($conn, "SELECT IFNULL(MAX(CAST(SUBSTRING(enquiry_no, 5) AS UNSIGNED)), 0) + 1 AS new_enq FROM enquiry_management");
	$eq_row = mysqli_fetch_assoc($eq_query);
	$enquiry_no = 'ENQ-' . str_pad($eq_row['new_enq'], 3, '0', STR_PAD_LEFT);
	$sql_enq = "customer = '".$customer_id."',enquiry_no = '".$enquiry_no."',part_number = '".$part_number."',part_description = '".$part_description."',model_number = '".$model_number."', drawing_issue = '".$drawing_issue."', volume = '".$volume."', type = '".$type."',quotation_status = '1', created_on = '".$created_on."', created_by = '".$created_by."', updated_by = '".$updated_by."'";
	
	$sql_enq= "INSERT INTO enquiry_management SET ".$sql_enq;
	mysqli_query($conn,$sql_enq);
	$enquiry_id = mysqli_insert_id($conn);
	
	$sql2= "UPDATE $table_name SET enquiry_id = '$enquiry_id' WHERE id = '$qot_id'";
	mysqli_query($conn,$sql2);
	}
  
	
	$_SESSION['info_message'] = "Quotation added successfully";
	header("Location: $file_name");
    exit();
}
################################################# END INSERT #################################################

################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];
	$quot_id = utility::app_crypt($_REQUEST['qout_id'],'d');
		if($_REQUEST['id'] != $quot_id){
			die("Invaild URL");
		}
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Quotation";
	$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);
	
    $quotation_number			    = $row_edit['quotation_number'];
    $customer_id			    = $row_edit['customer_id'];
    $enquiry_id			    = $row_edit['enquiry_id'];
	$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'];
	$anuual_value				= $row_edit['anuual_value'];
	
}
################################################# END EDIT ################################################# 


################################################## START UPDATE ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string"));
	
	$id  						= $_REQUEST['id'];
    $customer_id				= $_REQUEST['customer_id'];
	$enquiry_id					= $_REQUEST['enquiry_id'];	
	$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'];
	$anuual_value				= $_REQUEST['anuual_value'];
	$quotation_number				= $_REQUEST['quotation_number'];

	$updated_by		 		    = $_SESSION['user_id'];
	
	$sql = "customer_id = '".$customer_id."',quotation_number = '".$quotation_number."', part_number = '".$part_number."',part_description = '".$part_description."',model_number = '".$model_number."', drawing_issue = '".$drawing_issue."', volume = '".$volume."', type = '".$type."', anuual_value = '".$anuual_value."',updated_by = '".$updated_by."'";
	$sql= "UPDATE $table_name SET ".$sql." WHERE id = '".$id."'";
    mysqli_query($conn,$sql);
	$qot_id = mysqli_insert_id($conn);
	
	$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'] = "Quotation updated successfully";
	if(isset($from) && $from == "view_quotation_details"){
		header("Location: index?page=view_enquiry_details&from=view_customer_id&enquiry_id=$enquiry_id&id=$id");
		exit();
	}
	
    header("Location: $file_name$query_string");
    exit();
}
################################################# END UPDATE ################################################# 

##################################### For Annual ################################################
 

?>
<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">
									<label class="control-label" for="Part Number">Quotation Number<em></em></label>
									<div class="">
										<input type="text" id="quotation_number" name="quotation_number" value="<?php echo $quotation_number;?>" class="form-control" placeholder="Quotation Number" readonly>
										<input type='hidden' name='from' id='from' value='$from' >
									</div>
							     </div>
								 <div class="form-group col-lg-4">
									<div class="">
									  <label class="control-label" for="Customer">Customer<em>*</em></label>
										<? $gsi->getCustomerList("customer_id",$customer_id,"100%",false,"form-control select2","required"); ?>
									</div>
								</div>
								<?php if($from != "enquiry"){
									$hide ="hide";
								}?>
								<div class="form-group col-lg-4  <? echo $hide?>">
									<div class="">
									  <label class="control-label" for="Customer">Enquiry<em></em></label>
										<? $gsi->getEnquiryList("enquiry_id",$enquiry_id,"100%",false,"form-control select2",""); ?>
									</div>
								</div>
							</div>
							
							<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" required>
								</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 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 class="form-group col-lg-4">
								  <label class="control-label" for="Volume">Annual Value<em></em></label>
								  <div class="">
									<input type="text" id="anuual_value" name="anuual_value" value="<?php echo $anuual_value;?>" class="form-control" placeholder="Annual Value" readonly>
								  </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() {
        $(document).ready(function() {
            var urlParams = new URLSearchParams(window.location.search);
            var cust_id = urlParams.get('cust_id');

            if (cust_id) {
                $("#customer_id").val(cust_id);
                setTimeout(function() {
                    $("#customer_id").trigger("change");
                }, 500); 
            }
            <?php if($from == "enquiry"){  ?>
            $("#customer_id").on("change", function() {
                var customer_id = $(this).val();
                var form_data = {
                    'customer_id': customer_id
                };
                ////////////////////// For fetching Enquiry dropdown /////////////////////////
                if (customer_id != "") {
                    $.ajax({
                        async: true,
                        type: "POST",
                        url: site_url + "/modules/quotation_management/index.php?page=ajax_actions&action=get_enq_drodown",
                        data: form_data,
                        success: function(result) {
                            var resultObj = jQuery.parseJSON(result);
                            if (resultObj.status == 1) {
                                $(".enq_show").show();
                                $("#enquiry_id").empty();
                                for (i = 0; i < resultObj.enq_id.length; i++) {
                                    $("#enquiry_id").append(new Option(resultObj.enq_id[i].enquiry_no, resultObj.enq_id[i].id, false, false));
                                }
                                $("#enquiry_id").trigger("change");
                            } else {
                                $(".lift_show").hide();
                                $("#lift_id_serach").empty();
                                $("#lift_id_serach").append(new Option("No Site This Client", "", true, true));
                            }
                        }
                    });
                } else {
                    $("#enquiry_id").empty();
                }
            });
			<?php }  ?>
            /////////////// Fetch customer details   //////////////
            $("#form1").on("change", "#enquiry_id", function() {
                var enq_id = $(this).val();
                if (enq_id != "") {
                    $('#zone_checking').show();
                    var form_data = { 'enq_id': enq_id };       
                    
                    ////////////////////// For fetching address /////////////////////////
                    $.ajax({
                        async: true,
                        type: "POST",
                        url: site_url + "/modules/quotation_management/index.php?page=ajax_actions&action=get_enquiry_details",
                        data: form_data,
                        success: function(result) {  
                            var resultObj = jQuery.parseJSON(result); 
                            if (resultObj.status == 1) {
                                $('#zone_checking').hide();
                                $("#part_number").val(resultObj.part_number);
                                $("#part_description").val(resultObj.part_description);
                                $("#model_number").val(resultObj.model_number);
                                $("#drawing_issue").val(resultObj.drawing_issue);
                                $("#volume").val(resultObj.volume);
                                $("#type").val(resultObj.type).trigger("change");
                            }
                        }
                    });
                    ////////////////////// End For fetching address /////////////////////////
                }
            });
        });
    });
</script>
