<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js" integrity="sha256-gfQwA6PlkZsLqWu4bU4hXPrbTqzixm0B5MdvBLI+Oas=" crossorigin="anonymous"></script>

<div class="grid-form1">
<h3 id="forms-example" class="">[[*longtitle]]</h3>

<span class="error">* required fields.</span>

[[!clientDetailsFORM]]

<form method="post" action="#" id="PlantcsvForm" class="needs-validation" novalidate > <!-- ~[*id*]~] [[~28~]] -->

    [[!Personalize?
        &yesChunk=`analysisLogged_Clientdetails`
        &noChunk=`analysis_Clientdetails`
    ]]
    
    <hr>

    [[$plantAnalysisForm]]
	
 <button form="PlantcsvForm" type="submit" name="PlantcsvForm" class="btn btn-success">Submit</button>
</form>

[[!plantformSubmit]]

[[!newClientDetails]]

<hr>

<div class="card">
    <div class="card-body">
        <h5 class="card-title">Excel/CSV Upload</h5>
        <p class="card-text">Download a csv of this form for easy filling or upload a filled form to pre-populate.</p>
        <div class="input-group mt-3">
            <div class="custom-file">
                <input type="file" class="custom-file-input" id="upload">
                <label class="custom-file-label border-success" for="upload">Choose file</label>
            </div>
            <div class="input-group-append">
                <button class="btn btn-success" type="button" id="download">Download</button>
            </div>
        </div>
    </div>
</div>

</div>


<!-- ************************ Download Form as CSV ************************ -->
<script>
    document.getElementById("upload").addEventListener("change", upload, false);
    document.getElementById("download").addEventListener("click", download, false);
    
    function upload(e) {
        var data = null;
        var file = e.target.files[0];
        var reader = new FileReader();
        reader.readAsText(file);
        reader.onload = function (event) {
            var csvData = event.target.result;
            var parsedCSV = d3.csv.parseRows(csvData);
            parsedCSV.forEach(function (d, i) {
                if (i == 0) return true; // skip the header
                document.getElementById(d[0]).value = d[1];
            });
        }
    }
    
    function download(e) {
        data = [ ["id","value"]];
        var f = d3.selectAll("#csvForm input, select")[0];
        f.forEach(function(d,i){
          	data.push([d.id, d.value]);
        });
        console.log(data);
        var csvContent = "data:text/csv;charset=utf-8,";
        data.forEach(function (d, i) {
            dataString = d.join(",");
            csvContent += i < data.length ? dataString + "\n" : dataString;
        });
        var url = window.location.pathname;
        var filename = url.substring(url.lastIndexOf('/')+1);
        var fname = filename.split(".")[0];
        var today = new Date();
        var date = today.getDate()+''+(today.getMonth()+1)+''+today.getFullYear();
        var csvname = date+''+fname+"-plant.csv";
    
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", csvname);
        link.click();
    }
</script>
<script type="text/javascript">
    // JavaScript for disabling form submission if there are invalid fields
    (function() {
      'use strict';
      window.addEventListener('load', function() {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
              event.preventDefault();
              event.stopPropagation();
            }
            form.classList.add('was-validated');
          }, false);
        });
      }, false);
    })();
    
</script>