<div class="wrapper">
    <div class="container">
        <div class="row">
            <div class="col-sm-12"></div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="card-box">
                    <div class="row form">
                        <div class="form-group col-md-4">
                            <label class="form-label">Form Category</label>
                            <select class="form-control" id="category">
                                <?php foreach($formcategory as $category){ ?>
                                <option <?php if($category->id_concent_category == $categoryid){ echo "selected='selected'";} ?> value="<?php echo $category->id_concent_category; ?>"><?php echo $category->concent_category; ?></option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="form-group col-md-4">
                            <label class="form-label">Form Name</label>
                            <input class="form-control" id="formname" value="<?php if(null!=$formid){echo $formname;}else{echo '';} ?>">        
                            <input type="text" id="form_id" value="<?php if(null!=$formid){echo $formid;}else{echo '';} ?>">                                                
                        </div>
                        <div class="form-group col-md-4">
                            <label class="form-label">Form Status</label>
                            <select class="form-control" id="formstatus">
                                <option value="Active">Active</option>
                                <option value="InActive">InActive</option>
                            </select>                                                        
                        </div>
                        <div class="form-group col-md-2 pull-right">
                            <?php if($formid==null){?>
                            <button onclick="create_form();" class="btn btn-success btn-sm">Create From</button>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row" <?php if($formid==null){echo 'style="display:none;"'; } ?>>
            <div class="col-md-6">
                <div class="card-box">
                    <div class="form">
                        <div class="form-group">
                            <label>Section</label>
                            <input class="form-control" id="section">
                        </div>
                        <div class="form-group">
                            <label>Title</label>
                            <input class="form-control" id="title">
                        </div>
                        <div class="form-group">
                            <label>Option Name</label>
                            <input class="form-control" id="option">
                        </div>
                        <div class="form-group">
                            <label>Select Type</label>
                            <select class="form-control" id="optiontype">
                                <option value="checkbox">Checkbox</option>
                                <option value="radio">Radio Button</option>
                                <option value="textarea">Text Input</option>
                                <option value="para">Paragraph</option>
                                <option value="list">List</option>
                                <option value="imghalf">Image half</option>
                                <option value="img">Image</option>
                            </select>
                        </div>     
                        <div class="form-group" >
                            <button onclick="updatetable()" class="btn btn-primary  ">Add <i class="fa fa-icon fa-arrow-right"></i></button>
                        </div>                   
                    </div>                    
                </div>                
            </div>
            <div class="col-md-6">
                <div class="card-box">
                    <table id="tblstructure" class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Section</th>
                                <th>Title</th>
                                <th>Option</th>
                                <th>Type</th>                                
                                <th>Edit</th>                                
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($formdata==null){?>
                                
                            <?php } else {?>
                                <?php foreach($formdata as $fd){ ?>
                                <tr id="<?php echo $fd['seq'];?>">
                                    <td><?php echo $fd['seq'];?></td>
                                    <td><?php echo $fd['section'];?></td>
                                    <td><?php echo $fd['title'];?></td>
                                    <td><?php echo $fd['option'];?></td>
                                    <td><?php echo $fd['option_type'];?></td>
                                    <?php if($formdata!=null){?>
                                    <td>
                                        <button class="btn btn-info btn-sm" onclick="openedit(<?php echo $fd['seq'];?>);">Edit</button>
                                    </td>
                                <?php } ?>
                                </tr>
                                <?php } ?>
                            <?php } ?>
                        </tbody>
                    </table>
                    
                </div>
                <div>
                    <div class="pull-left">
                        <button class="btn btn-success" id="btn_makejson" onclick="makejson('view');">View Json</button>
                    </div>
                    <div class="pull-right">
                        <button class="btn btn-success" id="btn_makejson" onclick="makejson('save');">Create Form</button>
                    </div>
                </div>
            </div>
    </div>

    <div id="editmodal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="editmodal" aria-hidden="true" style="display: none;">
        <div class="modal-dialog modal-md"  >
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="custom-width-modalLabel">Editing Seq <span id="seqid"></span></h4>
                </div>
                <div class="modal-body">
                    <div class='row'>
                        <input type="hidden" id="modalformid">
                        <input type="hidden" id="modalseqid">
                       
                        <div class="form-group">
                            <label class="form-label">Section</label>
                            <input class="form-control" id="modalsection">
                        </div>
                    
                        <div class="form-group">
                            <label class="form-label">Title</label>
                            <input class="form-control" id="modaltitle">
                        </div>
                                            
                        <div class="form-group">
                            <label class="form-label">Option</label>
                            <input class="form-control" id="modaloption">
                        </div>
                                            
                        <div class="form-group">
                            <label class="form-label">Type</label>
                            <select class="form-control" id="modaloptiontype">
                                <option value="checkbox">Checkbox</option>
                                <option value="radio">Radio Button</option>
                                <option value="textarea">Text Input</option>
                                <option value="para">Paragraph</option>
                                <option value="list">List</option>
                                <option value="imghalf">Image half</option>
                                <option value="img">Image</option>
                            </select>
                        </div>
                       
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="row">
                        <button onclick="saveeditdata();" class="btn btn-success" >Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
                        

    <script>

        function create_form(){


                if($("#formname").val() == ""){
                    swal({
                        title: "Form Name is missing",
                        text: result[1],
                        type: "info",
                        confirmButtonText: 'OK!'
                    });
                    return false;
                } else {

                    $.ajax({
                        type: 'POST',
                        url: '<?php echo base_url();?>concent_controller/add_concent_form',
                        data: {
                            formname: $("#formname").val(), formcategory: $("#category").val(), formstatus: $("#formstatus").val()

                        },
                        success: function(data) {
                            //alert(data);
                            var response = data.split("|");
                           
                            if(response[0]=='success'){
                                window.location.assign('<?php echo base_url();?>createformjson/'+response[1]);                                
                            }else{  
                                alert(response[1]);
                            }
                        }
                    });
                }

        }


        function updatetable(){


            var rowCount = $('#tblstructure tr').length;
           
            var section='';
            var title='';
            var option='';
            var optiontype='';
            
            var lastsection=''; lasttitle='';
            $('#tblstructure tr').each(function(row, tr) {
                
                if($(tr).find('td:eq(1)').text()!=''){ lastsection = $(tr).find('td:eq(1)').text();}
                if($(tr).find('td:eq(2)').text()!=''){lasttitle = $(tr).find('td:eq(2)').text();}
            });

            if(lastsection != $("#section").val()){
                section = $("#section").val();
            }
            if(lasttitle!=$("#title").val() || lastsection != $("#section").val()){
                title = $("#title").val();
            }

            var html = "<tr id='"+rowCount+"'>";
            html+="<td row='"+rowCount+"'>"+rowCount+"</td>";
            html+="<td>"+section+"</td>";
            html+="<td>"+title+"</td>";
            html+="<td>"+$("#option").val()+"</td>";
            html+="<td>"+$("#optiontype").val()+"</td>";
            html+="</tr>";

            $("#tblstructure tbody").append(html);

            
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url();?>concent_controller/add_structure_row',
                data: {
                    seq: rowCount,
                    formid: $("#form_id").val(),  
                    section: section, 
                    title: title, 
                    option: $("#option").val(), 
                    optiontype: $("#optiontype").val()
                },
                success: function(data) {
                   // alert(data);
                    var response = data.split("|");
                    
                    if(response[0]=='success'){
                        window.location.assign('<?php echo base_url();?>createformjson/'+response[1]);                                
                    }else{  
                        alert(response[1]);
                    }
                }
            });


        }

        function makejson(val){

            var myjson = "{"; var lastsection=""; var lasttitle=""; var lastoption ="";
            $('#tblstructure tr').each(function(row, tr) {
                //Add Section
                if($(tr).find('td:eq(1)').text() != lastsection && $(tr).find('td:eq(1)').text()!=""){
                    if(lastsection != ""){  //first section
                        myjson += "}}, ";
                    }
                    myjson += '"'+ $(tr).find('td:eq(1)').text() + '":{';
                    lastsection=$(tr).find('td:eq(1)').text();
                    lastoption = "";
                    lasttitle="";
                } 

                //Add Title
                if($(tr).find('td:eq(2)').text() != lasttitle && $(tr).find('td:eq(2)').text()!=""){
                    if(lasttitle!=""){myjson += "},";}

                    myjson += '"'+ $(tr).find('td:eq(2)').text() + '":{';
                    lasttitle=$(tr).find('td:eq(2)').text() ;
                    lastoption="";
                }
                //Add option and option type
                if($(tr).find('td:eq(3)').text() != lastoption){
                    if(lastoption!=""){myjson += ",";}
                    myjson += '"'+ $(tr).find('td:eq(3)').text() + '":"' + $(tr).find('td:eq(4)').text() + '"';
                    lastoption = $(tr).find('td:eq(3)').text();
                }
            });
            myjson += "}}}";

            //console.log(myjson);
            a = testJSON(myjson);
            if(a==true){
                if(val=='view'){
                    alert(myjson);
                }else{
                    save_structure(myjson);
                }
            }else{
                console.log(myjson);
                alert('json not valid');
            }
        }

        function testJSON(text) {
            if (typeof text !== "string") {
                return false;
            }
            try {
                JSON.parse(text);
                return true;
            } catch (error) {
                return false;
            }
        }

        function save_structure(myjson){
            var Table= storeOTblValues();


            if($("#form_id").val() == ""){
                $.ajax({
                    type: 'POST',
                    url: '<?php echo base_url();?>concent_controller/save_structure_json',
                    data: {
                        table: Table, myjson: myjson, category: $("#category").val(), formname: $("#formname").val(), formstatus:  $("#formstatus").val()
                    },
                    success: function(data) {
                        var response = data.split("|");
                        
                        if(response[0]=='success'){
                            alert(response[1]);
                            
                        }else{
                            alert(response[1]);
                        }
                    }

                });
            } else {
                $.ajax({
                    type: 'POST',
                    url: '<?php echo base_url();?>concent_controller/update_structure_json',
                    data: {
                       formid: $("#form_id").val(),  table: Table, myjson: myjson, category: $("#category").val(), formname: $("#formname").val(), formstatus:  $("#formstatus").val()
                    },
                    success: function(data) {
                        var response = data.split("|");
                        
                        if(response[0]=='success'){
                            alert(response[1]);
                            
                        }else{
                            alert(response[1]);
                        }
                    }

                });


            }
        }

        function storeOTblValues(){
            var TableData = new Array();
            $('#tblstructure tr').each(function(row, tr) {
                TableData[row] = {
                    "seq": $(tr).find('td:eq(0)').text()                    
                    , "section": $(tr).find('td:eq(1)').text()
                    , "title": $(tr).find('td:eq(2)').text()
                    , "option": $(tr).find('td:eq(3)').text()
                    , "option_type": $(tr).find('td:eq(4)').text()
                    
                }
            });
            TableData.shift();  // first row will be empty - so remove
           
            return TableData;
        }

        function openedit(seq){

            

            var section = $('#tblstructure').find('tr:eq('+seq+')').find('td:eq(1)').text();
            var title = $('#tblstructure').find('tr:eq('+seq+')').find('td:eq(2)').text();
            var option = $('#tblstructure').find('tr:eq('+seq+')').find('td:eq(3)').text();
            var optiontype = $('#tblstructure').find('tr:eq('+seq+')').find('td:eq(4)').text();
           

            var formid = $('#form_id').val();
            $('#seqid').html(seq);            
            $('#modalformid').val(formid);
            $('#modalseqid').val(seq);

            $("#modalsection").val(section);
            $("#modaltitle").val(title);
            $("#modaloption").val(option);
            $("#modaloptiontype").val(optiontype);

            $("#editmodal").modal('show');


        }

        function saveeditdata(){

            $.ajax({
                type: 'POST',
                url: '<?php echo base_url();?>concent_controller/save_edit_data',
                data: {
                    form_id: $("#form_id").val(),
                    seq: $("#modalseqid").val(),
                    section: $("#modalsection").val(), 
                    title:  $("#modaltitle").val(), 
                    option:  $("#modaloption").val(), 
                    optiontype:  $("#modaloptiontype").val()
                },
                success: function(data) {
                    var response = data.split("|");
                    
                    if(response[0]=='success'){
                        window.location.assign('<?php echo base_url();?>createformjson/'+response[1]);
                        
                    }else{
                        alert(response[1]);
                    }
                }

            });


        }
    </script>