<?php 
session_start();
function getLastPathSegment($url) {
	$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
	$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
	$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash

	if (substr($path, -1) !== '/') {
		array_pop($pathTokens);
	}
	return end($pathTokens); // get the last segment
}

$name="Form";
if(isset($_GET['name'])){
	$name=$_GET['name'];
	$_SESSION['form_id']=$name;
}else if(isset($_GET['url'])){
	$name=$_GET['url'];
	
}else{
$name=getLastPathSegment($_SERVER['REQUEST_URI']);}
?><meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
  <meta charset="utf-8">
  <link rel="icon" type="image/x-icon" href="https://crm.menetalk.com/favicon.ico?v=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title> Lamenes form</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="custom/app/syntax.css" rel="stylesheet">
  <link href="custom/app/main.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  
  
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" rel="stylesheet">
   <link href="https://meeting-css-url.s3.eu-west-2.amazonaws.com/crm/form/<?=$name?>/main.css" rel="stylesheet">
   
  <script src="custom/dist/formio.full.js"></script>
  <link href="custom/dist/formio.full.min.css" rel="stylesheet">
  <script src="	https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"></script>
  
  
  <script type="text/javascript">Formio.icons = 'fontawesome';</script>

<div class="container-fluid">
<div class="v2" class="row" style="margin-top:30px">
  <div id="full_form_view" class="col-sm-12 col-md-12">
  
    <div id="formio" class="card card-body bg-light">
    
</div>
<div id="form_submit_progress" class="form-submit-progress" style="display:none" aria-live="polite">
  <div class="form-submit-progress__inner">
    <p class="form-submit-progress__label">Submitting your form...</p>
    <div class="progress">
      <div id="form_submit_progress_bar" class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" style="width:0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
    </div>
  </div>
</div>
<p id="full_form_view_success" style="margine:20px;background: green;color:#fff;padding:30px;text-align:center;display:none" class="success">Thank you, Our Team will contact you soon</p>
    <p id="full_form_view_fail" style="margine:20px;background: red;color:#fff;padding:30px;text-align:center;display:none" >Thank you, Our Team will contact you soon</p>

  </div>
  <div class="clearfix"></div>
</div>
</div>

<style>
.selection.dropdown{
min-height:35px!important}
#full_form_view{
position:relative}
.form-submit-progress{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
background:rgba(255,255,255,.88);
display:flex;
align-items:center;
justify-content:center;
z-index:20;
padding:20px}
.form-submit-progress__inner{
width:100%;
max-width:420px}
.form-submit-progress__label{
margin-bottom:10px;
font-weight:600;
text-align:center}
.form-submit-progress .progress{
height:18px}
</style>
<script>

var formElement = document.getElementById('formio');
var formSuccess= document.getElementById('full_form_view_success')
var formFail= document.getElementById('full_form_view_fail')
var progressWrap = document.getElementById('form_submit_progress');
var progressBar = document.getElementById('form_submit_progress_bar');
var progressTimer = null;

function setProgress(percent) {
  progressBar.style.width = percent + '%';
  progressBar.setAttribute('aria-valuenow', percent);
}

function startProgress() {
  clearInterval(progressTimer);
  progressWrap.style.display = 'flex';
  setProgress(12);
  var current = 12;
  progressTimer = setInterval(function() {
    if (current < 85) {
      current += Math.max(1, (85 - current) * 0.08);
      setProgress(Math.round(current));
    }
  }, 200);
}

function finishProgress() {
  clearInterval(progressTimer);
  setProgress(100);
}

function hideProgress() {
  clearInterval(progressTimer);
  progressWrap.style.display = 'none';
  setProgress(0);
}

var onForm = function(form) {
  var isSubmitting = false;

  function setSubmitDisabled(disabled) {
    var buttons = formElement.querySelectorAll('button[type="submit"]');
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].disabled = disabled;
      buttons[i].style.pointerEvents = disabled ? 'none' : '';
    }
  }

  form.on('submitButton', function() {
    if (isSubmitting) {
      return false;
    }
    setSubmitDisabled(true);
  });

  form.on('error', function() {
    if (!isSubmitting) {
      setSubmitDisabled(false);
      hideProgress();
    }
  });

  form.on('submit', function() {
    if (isSubmitting) {
      return;
    }
    isSubmitting = true;
    setSubmitDisabled(true);
    startProgress();

    console.log(form.submission.data)
    var data=form.submission.data
    console.log("www",typeof data)
    data.mene_crm_id="<?=$name ?>"
    fetch('/form/api.php', 
        {
            method: 'POST',
            headers: {
               'Content-Type': 'application/json',                 
               'Accept': '*/*' 
            },            
            body: JSON.stringify(data)
        }
        )
    .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // Parse the JSON response
  })
  .then(data => {
    console.log('Received data:', data);
    finishProgress();
    setTimeout(function() {
      showSuccess(data)
    }, 350);
  })
  .catch(function() {
    finishProgress();
    setTimeout(function() {
      showSuccess({status_code: 0});
    }, 350);
  })
  });
};
function showSuccess(response){
	
	console.log("response",response)
	hideProgress();
	if(response.status_code==200){
		if(response.redirect_url){
			window.top.location.href  =response.redirect_url
			}
		formSuccess.style.display="block"
			formElement.style.display="none"}
	else{
		formFail.style.display="block"
			formElement.style.display="none"
		}
}
function getJsonData(data){
  data=data.replace(/'(?=(?:[^"]|"[^"]*")*$)/g, '"')
            console.log("fffffffff3.21",typeof data,data)
            data=data.replace(/False/gi, '"False"')
            console.log("fffffffff3.22",typeof data,data)
            data=data.replace(/True/gi, '"True"')
            data=data.replace(/None/gi, '""')
            console.log("fffffffff3.25",typeof data,data)
data=JSON.parse(data, (k, v) => v === "True" ? true : v === "False" ? false : v);
return data

}
url="https://crm-general-api.menetalk.com/api/v1/get/form/secure?id=<?=$name?>"
fetch(url)
  .then((response) => response.json())
  .then((data) => Formio.createForm(formElement,getJsonData(data) ).then(onForm));

  
</script>