<?php
 include('include/headscript.php'); ?>
<?php 
// pickup the get variable
if (isset($_GET["certtype"])) {
	$certtype=$_GET["certtype"]; }
if (isset($_GET["tempcode"])) {
	$tempcode=$_GET["tempcode"]; }
if (isset($_GET["previousrepnumber"])) {
	$previousrepnumber=$_GET["previousrepnumber"]; }
else {
	$previousrepnumber=""; }
if (isset($_GET["idtrf"])) {
	$idtrf=$_GET["idtrf"]; }
if (isset($_GET["issuebycimac"])) {
	$issuebycimac=$_GET["issuebycimac"]; }
else {
	$issuebycimac=""; }
if (isset($_GET["samplestore"])) {
	$samplestore=$_GET["samplestore"]; }
else {
	$samplestore=""; }
if (isset($_GET["notificatedorganismname"])) {
	$notificatedorganismname=$_GET["notificatedorganismname"]; }
else {
	$notificatedorganismname=""; }

?>
<?php
			
			include 'ddown/dropdown.php';
			
			$obj = new Dropdown();
			
			$rows = $obj->fetchCountry();
			
			?>
<?php
//calculate next trf number available
$lasttrfnumber = new WA_MySQLi_RS("lasttrfnumber",$cmctrfdb,1);
$lasttrfnumber->setQuery("SELECT * FROM `trf-details` ORDER BY `trf-details`.trfnumber DESC LIMIT 1");
$lasttrfnumber->execute();?>
<?php
$lastnumber=$lasttrfnumber->getColumnVal("trfnumber");
$nextnumber=$lastnumber+1;
?>

<?php
if (!isset($_GET["idtrf"])) {
//check if the tempcode already exist
$tempcodesearch = new WA_MySQLi_RS("tempcodesearch",$cmctrfdb,1);
$tempcodesearch->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.tempcode='$tempcode'");
$tempcodesearch->execute();
}
?>
<?php
// insert the new TRF into the table
if (!isset($_GET["idtrf"])) {
if (empty($tempcodesearch->getColumnVal("idtrfdetails"))) {

  $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
  $InsertQuery->Action = "insert";
  $InsertQuery->Table = "`trf-details`";
  $InsertQuery->bindColumn("trfnumber", "i", "$nextnumber", "WA_DEFAULT");
  $InsertQuery->bindColumn("idcompany", "i", "$idcompany", "WA_DEFAULT");
  $InsertQuery->bindColumn("iduser", "i", "$iduserlogin", "WA_DEFAULT");
  $InsertQuery->bindColumn("idcertification", "i", "$certtype", "WA_DEFAULT");
  $InsertQuery->bindColumn("previousreportnumber", "s", "$previousrepnumber", "WA_DEFAULT");
  $InsertQuery->bindColumn("tempcode", "s", "$tempcode", "WA_DEFAULT");
  $InsertQuery->bindColumn("notificatedorganismname", "s", "$notificatedorganismname", "WA_DEFAULT");
  $InsertQuery->saveInSession("");
  $InsertQuery->execute();
  $InsertGoTo = "";

  $InsertQuery->redirect($InsertGoTo);
	
	$tempcodesearch2 = new WA_MySQLi_RS("tempcodesearch",$cmctrfdb,1);
$tempcodesearch2->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.tempcode='$tempcode'");
$tempcodesearch2->execute();
	
	$idtrf=$tempcodesearch2->getColumnVal("idtrfdetails");
	
	  $code="1";
  $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
  $InsertQuery->Action = "insert";
  $InsertQuery->Table = "wheretrfstep";
  $InsertQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
  $InsertQuery->bindColumn("code", "i", "$code", "WA_DEFAULT");
  $InsertQuery->saveInSession("");
  $InsertQuery->execute();
  $InsertGoTo = "";

  $InsertQuery->redirect($InsertGoTo);
	
	  $code="2";
  $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
  $InsertQuery->Action = "insert";
  $InsertQuery->Table = "wheretrfstep";
  $InsertQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
  $InsertQuery->bindColumn("code", "i", "$code", "WA_DEFAULT");
  $InsertQuery->saveInSession("");
  $InsertQuery->execute();
  $InsertGoTo = "";

  $InsertQuery->redirect($InsertGoTo);
	
  $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
  $UpdateQuery->Action = "update";
  $UpdateQuery->Table = "contacts";
  $UpdateQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
  $UpdateQuery->addFilter("tempcode", "=", "s", "".($tempcode)  ."");
  $UpdateQuery->execute();
  $UpdateGoTo = "";
  if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo?rel2abs($UpdateGoTo,dirname(__FILE__)):"";
  $UpdateQuery->redirect($UpdateGoTo);

	
	//include('uploadfilecertificate.php');
	}}
?>
<?php
if (!isset($_GET["idtrf"])) {
	 
$trfnumberfinal = new WA_MySQLi_RS("trfnumberfinal",$cmctrfdb,1);
$trfnumberfinal->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.tempcode='$tempcode'");
$trfnumberfinal->execute();
	$idtrf=$trfnumberfinal->getColumnVal("idtrfdetails");
	$idcertn=$trfnumberfinal->getColumnVal("idcertification");
} else {
$trfnumberfinal = new WA_MySQLi_RS("trfnumberfinal",$cmctrfdb,1);
$trfnumberfinal->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.idtrfdetails='$idtrf'");
$trfnumberfinal->execute();
	$idcertn=$trfnumberfinal->getColumnVal("idcertification");
}
?>
<?php
$typearticleselect = new WA_MySQLi_RS("typearticleselect",$cmctrfdb,0);
$typearticleselect->setQuery("SELECT * FROM article_type ORDER BY article_type.name_articletype");
$typearticleselect->execute();?>
<?php
$charactarticle = new WA_MySQLi_RS("charactarticle",$cmctrfdb,0);
$charactarticle->setQuery("SELECT * FROM article_characteristic ORDER BY article_characteristic.name_articlecharacteristic");
$charactarticle->execute();?>
<?php $idcert=$trfnumberfinal->getColumnVal("idcertification") ?>
<?php
$certname = new WA_MySQLi_RS("certname",$cmctrfdb,1);
$certname->setQuery("SELECT * FROM certificationtype WHERE certificationtype.idcertificationtype='$idcert'");
$certname->execute();?>
<?php
$modelarticlelist = new WA_MySQLi_RS("modelarticlelist",$cmctrfdb,1);
$modelarticlelist->setQuery("SELECT * FROM modelarticle ORDER BY modelarticle.namemodelarticle");
$modelarticlelist->execute();
?>
<?php
	include('include/trfqueryscript.php');  ?>
<?php if ($idcertn=='5' && $samplestore=='N') {
    header("Location: samplestore.php?idtrf=$idtrf&issuebycimac=$issuebycimac");
    } elseif ($idcertn=='5' && $samplestore=='Y' && $issuebycimac=='N') {
	header("Location: adddocument.php?idtrf=$idtrf");
} elseif ($idcertn=='5' && $samplestore=='Y' && $issuebycimac=='Y') {
		header("Location: trfoption.php?idtrf=$idtrf");
} elseif ($idcertn=='6' && $issuebycimac=='N') {
	header("Location: adddocument.php?idtrf=$idtrf");
} elseif ($idcertn=='6' && $issuebycimac=='Y') {
		header("Location: trfoption.php?idtrf=$idtrf");
}
?>
<!DOCTYPE html>
<html lang="en">
	
<head>
        <meta charset="utf-8" />
        <title>TRF CIMAC </title>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta content="CIMAC TRF Portal" name="description" />
        <meta content="" name="author" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />

        <!-- App favicon -->
        <link rel="shortcut icon" href="../images/favicon.ico">
	
		<!--Form Wizard-->
        <link href="../plugins/jquery-steps/jquery.steps.css" rel="stylesheet" type="text/css">

        <!-- App css -->
        <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/jquery-ui.min.css" rel="stylesheet">
        <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/metisMenu.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />

<!-- submit form with button -->
<script>
function formSubmit() {
    document.forms["myForm"].submit();
}
</script>
<!-- upload image script -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script> 
        $(document).ready(function() { 
            $(".upload-image").click(function(){
                $(".form-horizontal").ajaxForm({target: '.preview'}).submit();
            });
        }); 
</script>
<script>
  $('#form').parsley();
</script>	
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	
</head>

    <body>
        
         <!-- Top Bar Start -->
         <?php include('include/topbar.php'); ?>
        <!-- Top Bar End -->

        
        <!-- Left Sidenav -->
        <?php include('include/leftsidenav.php'); ?>
    <!-- end left-sidenav-->

        <div class="page-wrapper">
            <!-- Page Content-->
            <div class="page-content">

                <div class="container-fluid">
                    <!-- Page-Title -->
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="page-title-box">
                                <div class="float-right">
                                    <ol class="breadcrumb">
                                        <li class="breadcrumb-item"><a href="javascript:void(0);">TRF</a></li>
                                        <li class="breadcrumb-item active">Starter</li>
                                    </ol>
                                </div>
                                <h4 class="page-title"><?php echo $titlewb; ?></h4>
                            </div><!--end page-title-box-->
                        </div><!--end col-->
                    </div>
					<div class="row">
                        <div class="col-sm-12">
							<div class="card">
                                <div class="card-body">
                                    <div class="media">
							
                                               
                                       <?php include('include/appform.php'); ?>
                                    </div><!--end media-->
                                                                          
                                </div><!--end card-body--> 
                            </div><!--end card-->
							
							<div class="progress mb-4">
                              <div class="progress-bar" role="progressbar" style="width: 30%;" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100">30%</div>
                          </div>
							
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="mt-0 header-title"><?php echo $samplecheck; ?></h4>
                                    <p class="text-muted mb-3"><?php echo $samplecheck_help; ?></p> 
									
									
									<div class="upload-div">
    <!-- File upload form -->
    <form id="uploadForm" enctype="multipart/form-data">
        <label><?php echo $chooseimage; ?></label>
        <input type="file" name="images[]" id="fileInput" >
		<input type="hidden" name="idtrf" id="idtrf" value="<?php echo($trfnumberfinal->getColumnVal("idtrfdetails")); ?>">
        <input type="submit" name="submit" value="<?php echo $uploadph; ?>"/>
    </form>
	
    <!-- Display upload status -->
    <div id="uploadStatus"></div>
	   
</div>
	
	<!-- Gallery view of uploaded images --> 
									<div class="gallery"></div>
									<br>

				<form class="needs-validation" action="standardstep.php" method="post" id="form" name="myForm" novalidate>	
									
									<div class="form-group row">
                                                <label for="validationTooltip01" class="col-sm-3 col-form-label text-right"><?php echo $typearticletitle; ?></label>
                                          <div class="col-sm-8">
                                                    <select class="form-control" name="articletype" id="articletype_change" required="">
                                                      <option value=""  <?php if (!(strcmp("", ($trfnumberfinal->getColumnVal("idarticletype"))))) {echo "selected=\"selected\"";} ?>><?php echo $pleaseselect; ?></option>
                                                      <?php
				if(!empty($rows))
				{
					foreach($rows as $row)
					{
					?>
                                                      <option value="<?php echo $row['idarticletype']; ?>" <?php if (!(strcmp($row['idarticletype'], ($trfnumberfinal->getColumnVal("idarticletype"))))) {echo "selected=\"selected\"";} ?>><?php echo $row['name_articletype']; ?></option>
                                                      <?php
					}
				}
			  ?>
                                            </select>
                                                </div>
                                </div>
										<div class="form-group row">
                                                        <label for="validationTooltip01" class="col-sm-3 col-form-label"><?php echo $descriptiontitle; ?></label>
                                                        <div class="col-sm-8">
                                                            <input type="text" class="form-control" id="validationTooltip01" name="description" placeholder="<?php echo $descriptiontitle; ?>" value="<?php if (isset($_GET["idtrf"])) { echo $sdescription; } ?>" required="">
															
                                                        </div>
										</div>
										
										
										
										<div class="form-group row">
                                                <label for="validationTooltip01" class="col-sm-3 col-form-label text-right"><?php echo $modeltitle; ?></label>
                                          <div class="col-sm-8">
                                                    <select class="form-control" name="model" id="model_change" required="">
                                                    <option value="" <?php if (!(strcmp("", ($trfnumberfinal->getColumnVal("model"))))) {echo "selected=\"selected\"";} ?>><?php echo $pleaseselect; ?></option>

                                                    <?php
                                                    $modelrows = $obj->fetchModel($trfnumberfinal->getColumnVal("idarticletype"));
				if(!empty($modelrows))
				{
					foreach($modelrows as $row)
					{
					?>      
                    <option value="<?php echo $row['idmodelarticle']; ?>" <?php if (!(strcmp($row['idmodelarticle'], ($trfnumberfinal->getColumnVal("model"))))) {echo "selected=\"selected\"";} ?>><?php echo $row['namemodelarticle']; ?></option>
           
                                                      <?php
					}
				}
			  ?>                               
                                            </select>
                                                </div>
                                </div>
										
										
										
										<div class="form-group row">
                                                        <label for="validationTooltip01" class="col-sm-3 col-form-label"><?php echo $rangemeasuretitle; ?></label>
                                                        <div class="col-sm-4">
                                                            <input type="number" min="10" max="50" class="form-control" id="validationTooltip01" name="rangemeasuremin" placeholder="<?php echo $rangemeasuremintitle; ?>" value="<?php if (isset($smeasuremin)) { echo $smeasuremin; } ?>" required="">
															
                                                        </div>
														<div class="col-sm-4">
                                                            <input type="number" min="10" max="50" class="form-control" id="validationTooltip01" name="rangemeasuremax" placeholder="<?php echo $rangemeasuremaxtitle; ?>" value="<?php if (isset($smeasuremax)) { echo $smeasuremax; } ?>" required="">
															
                                                        </div>
										</div>
										
										
								  
								  <div class="form-group row">
                                                <label for="validationTooltip01" class="col-sm-3 col-form-label text-right"><?php echo $articlecharacteristictitle; ?></label>
                                          <div class="col-sm-8">
                                            <select class="form-control" name="articlecharacteristic" id="charact_result">
                                              <option value="" <?php if (!(strcmp("", ($trfnumberfinal->getColumnVal("idarticle_characteristics"))))) {echo "selected=\"selected\"";} ?>><?php echo $pleaseselect; ?></option>
                                              <?php
                                                    $chrows = $obj->fetchCharact($trfnumberfinal->getColumnVal("idarticletype"));
				if(!empty($chrows))
				{
					foreach($chrows as $row)
					{
					?>      
                    <option value="<?php echo $row['idarticlecharacteristic']; ?>" <?php if (!(strcmp($row['idarticlecharacteristic'], ($trfnumberfinal->getColumnVal("idarticle_characteristics"))))) {echo "selected=\"selected\"";} ?>><?php echo $row['name_articlecharacteristic']; ?></option>
           
                                                      <?php
					}
				}
			  ?>              
                                            </select>
                                    </div>
                                </div>
																				<div class="form-group row">
                                                        <label for="registeredmark" class="col-sm-3 col-form-label"><?php echo $registeredmarktitle; ?></label>
                                                        <div class="col-sm-8">
                                                            <input type="text" class="form-control" id="registeredmark" name="registeredmark" placeholder="<?php echo $registeredmarktitle; ?>" value="<?php if (isset($_GET["idtrf"])) { echo $sregisteredmark; } ?>" required>
															
                                                        </div>
										</div>
										
								  <input type="hidden" name="idtrf" id="idtrf" value="<?php echo($trfnumberfinal->getColumnVal("idtrfdetails")); ?>">
								   <input type="hidden" name="formupdtrfdetails" id="formupdtrfdetails" value="Y">
								<br><br>
										<button class="btn btn-gradient-primary" type="submit">Submit form</button>
										<input type="button" onclick="formSubmit()" class="btn btn-gradient-success waves-effect waves-light" value="<?php echo $nextsteptitle; ?>">
										
										</div>
                                    </form>
                          </div><!--end card-body-->
                      </div><!--end card-->
                       
						<script>
// country dependent ajax
 $(document).on("change","#articletype_change", function(e){
	e.preventDefault();
		
	var articletype = $("#articletype_change").val();	
		
	$.ajax({
        type: "POST",
        url: "ddown/modelart.php",
		dataType: "json",
        data: "idarticletype="+articletype,
        success: function(response)
        {
			var modelBody = "";
			modelBody = "<option>-- select Model --</option>"
			for(var key in response)
			{
				modelBody += "<option value="+ response[key]['idmodelarticle'] +">"+ response[key]['namemodelarticle'] +"</option>";
				$("#model_change").html(modelBody);
			}		
        }
    });
 });

// state dependent ajax
 $(document).on("change","#articletype_change", function(e){
	e.preventDefault();
		
	var charact = $("#articletype_change").val();	
		
	$.ajax({
        type: "POST",
        url: "ddown/articlecharact.php",
		dataType: "json",
        data: "idarticletype="+charact,
        success: function(response)
		
		{
			var charactBody = "";
			charactBody = "<option>-- select Characteristic --</option>"
			for(var key in response)
			{
				charactBody += "<option value="+ response[key]['idarticlecharacteristic'] +">"+ response[key]['name_articlecharacteristic'] +"</option>";
				$("#charact_result").html(charactBody);
			}		
        }
		
        
    });
 });	
</script>	
							
                       
                  </div><!--end col-->
              </div>
                    <!-- end page title end breadcrumb -->
                    

          </div><!-- container -->
<!-- footer start -->
              <?php include('include/footer.php'); ?>
                </footer><!--end footer-->
    </div>
            <!-- end page content -->
        </div>
        <!-- end page-wrapper -->
						<script>
// country dependent ajax
 $(document).on("change","#articletype_change", function(e){
	e.preventDefault();
		
	var articletype = $("#articletype_change").val();	
		
	$.ajax({
        type: "POST",
        url: "ddown/modelart.php",
		dataType: "json",
        data: "idarticletype="+articletype,
        success: function(response)
        {
			var modelBody = "";
			modelBody = "<option>-- select Model --</option>"
			for(var key in response)
			{
				modelBody += "<option value="+ response[key]['idmodelarticle'] +">"+ response[key]['namemodelarticle'] +"</option>";
				$("#model_change").html(modelBody);
			}		
        }
    });
 });

// state dependent ajax
 $(document).on("change","#articletype_change", function(e){
	e.preventDefault();
		
	var charact = $("#articletype_change").val();	
		
	$.ajax({
        type: "POST",
        url: "ddown/articlecharact.php",
		dataType: "json",
        data: "idarticletype="+charact,
        success: function(response)
		
		{
			var charactBody = "";
			charactBody = "<option>-- select Characteristic --</option>"
			for(var key in response)
			{
				charactBody += "<option value="+ response[key]['idarticlecharacteristic'] +">"+ response[key]['name_articlecharacteristic'] +"</option>";
				$("#charact_result").html(charactBody);
			}		
        }
		
        
    });
 });	
</script>
        <script>
$(document).ready(function(){
    // File upload via Ajax
    $("#uploadForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('#uploadStatus').html('<img src="images/uploading.gif"/>');
            },
            error:function(){
                $('#uploadStatus').html('<span style="color:#EA4335;">Images upload failed, please try again.<span>');
            },
            success: function(data){
                $('#uploadForm')[0].reset();
                $('#uploadStatus').html('<span style="color:#28A74B;">Images uploaded successfully.<span>');
                $('.gallery').html(data);
            }
        });
    });
    
    // File type validation
    $("#fileInput").change(function(){
        var fileLength = this.files.length;
        var match= ["image/jpeg","image/png","image/jpg","image/gif"];
        var i;
        for(i = 0; i < fileLength; i++){ 
            var file = this.files[i];
            var imagefile = file.type;
            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
                alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
                $("#fileInput").val('');
                return false;
            }
        }
    });
});
</script>

        <!-- jQuery  -->
        <script src="assets/js/jquery.min.js"></script>
		<script src="assets/js/jquery-ui.min.js"></script>
        <script src="assets/js/bootstrap.bundle.min.js"></script>
        <script src="assets/js/metismenu.min.js"></script>
        <script src="assets/js/waves.js"></script>
        <script src="assets/js/feather.min.js"></script>
        <script src="assets/js/jquery.slimscroll.min.js"></script>
        <script src="assets/js/jquery-ui.min.js"></script>
	
	  

        <!-- Parsley js -->
        <script src="../plugins/parsleyjs/parsley.min.js"></script>
        <script src="assets/pages/jquery.validation.init.js"></script> 

        <!-- App js -->
		<script src="assets/js/jquery.core.js"></script>
        <script src="assets/js/app.js"></script>
        
    </body>

</html>