<?php
    if(!isset($id)){
        $id = NULL;
    }

    if(isset($_GET['version']) && !empty($_GET['version']) ){
        $versionId =  (int)$_GET['version'];  
    }else{
        $versionId = null;
    }

    $originalTable = $table;
    $originalId = $id;
    $relatedTables = array ();
    if(!empty($id)){
        $relatedTables = $table->getRelatedTables();
    }
    array_unshift($relatedTables, array ( 'originalTable' => true ,  'tableName' => $table->getRawTableName() , 'displayName' => printTableName($table->getRawTableName()) ) );
?>
<iframe id="upload_target" name="upload_target" src="blank_iframe.html" style="width:0;height:0;border:0px solid #fff;"></iframe>

<ul class="tabs" id="navlist">
    <?php  foreach($relatedTables as $relatedTable) :  ?>
        <li>
            <a href="#tab_<?php echo $relatedTable['tableName']; ?>" class="<?php echo $relatedTable['tableName'] == $tableName ? 'active' : ''; ?>"><?php echo $relatedTable['displayName']; ?></a>
        </li>
        <?php endforeach; ?>
</ul>

<?php
    foreach($relatedTables as $relatedTable) :
        $isOriginalTable = false;
        $tableName = $relatedTable['tableName'];
        if($originalTable->getRawTableName() == $relatedTable['tableName']){
            $isOriginalTable = true;
            $id = $originalId;
        } else {
            $id = null;   
        }


        $table = new Table($relatedTable['tableName']);

    ?>

    <form action="<?php echo pageLink('actions/upload.php'); ?>" method="post" id="generateForm" class="form generateForm generateForm_<?php echo $tableName; ?>" enctype="multipart/form-data" target="upload_target"  onsubmit="startUpload();">


        <div class="tabbed-page <?php echo $isOriginalTable ? 'active' : 'in-active'; ?>" data-table="<?php echo $relatedTable['tableName']; ?>" id="tab_<?php echo $relatedTable['tableName']; ?>"  >


            <h1 class="title"><?php echo printTableName($tableName) ; ?>
                <?php if($table->isCrudEnabled()) : ?><a href="<?php echo pageLink('generate.php?table='.$tableName); ?>" >[ + ]</a><?php endif; ?>
            </h1>



            <div class="create active">
                <h3><?php echo empty($id) ? 'Create a new entry' : 'Update Entry'; ?> <span id="result" style='color:#6e6;font-weight: bold;'></span></h3><br /><br />




                <?php
                    include("common/shortcodes.php"); 

                    //Loop through the current table's fields and output the corresponding form
                    foreach($table->returnFieldsNamesTypes() as $fieldName => $fieldTypeLength){
                        if($fieldName == 'id' || $fieldName == 'pos'){
                            continue;
                        }

                        echo'<div class="field"><label class="input-control text"><div class="label '. ($table->isRequired($fieldName) ? 'required' : '' ) .'">';

                        $tooltip = $table->getTooltip($fieldName);

                        echo printTableName($fieldName);
                        echo'</div>';
                        if(!isset($formOptions)){
                            $formOptions = array ();
                        }

                        if(isset($relatedTable['foreignKey']) && $relatedTable['foreignKey'] == $fieldName ){


                            $formOptions['forceValue'] = $originalId;
                        } else {
                            $formOptions = array ();
                        }



                        echo $table->getFormElement($fieldName,$id,$versionId,$formOptions); //Displays the corresponding form element to the following field
                        if(!empty($tooltip))
                            echo '<span title="'.$tooltip.'" class="tooltipMessage"></span>';

                        echo '</label></div>';
                        echo '<br />';

                    }
                ?>
                <br style="clear: both;" />
                <div style="float: left; margin-top: 20px;">
                    <?php if ($table->isPhotoGallery() && empty($id)) : ?>
                        <input class="submit round drop_shadow triggerFineUploader" type="button" value="Save" style="float:left"/>
                        <?php else : ?>
                        <input class="submit round drop_shadow save-generate-form" id="save" type="submit" value="Save" style="float:left"  data-table-name="<?php echo $tableName; ?>"  />
                        <?php endif; ?>

                    <input type="hidden" name="token" value="<?php echo CSRF::generateToken(); ?>" />
                    <input class="submit round drop_shadow"  type="reset" value="Reset" style="float:left;margin-left:4px;">
                </div>
                <input type="hidden" name="data[<?php echo $tableName; ?>][id]" value="<?php echo $id; ?>" />
                <input type="hidden" name="table" value="<?php echo $tableName; ?>" />
                <div class="clear"></div><br />
                <?php if(!in_array($tableName,$oneRowTables)) :  ?>
                    <a href="<?php echo pageLink('list.php?table='.$tableName); ?>" style="clear:both;" class="listAllRecordsLink">List all records</a>
                    <?php endif; ?>


                | <a href="<?php echo $table->returnFormatedLink($id); ?>">View on website</a>

            </div>


            <?php if(isset($relatedTable['foreignKey'])) : ?>

                <hr>

                <div class="list in-active" style="background-color:#f1f1f1; padding:10px;" >
                    <h3>List</h3>

                    <?php



                        $allFields = $table->getTableFields();
                        $childTableInformation = $table->getChildTableInformation();
                        $allRows = $table->safeFind(array(
                                'conditions' => array (
                                    $relatedTable['foreignKey'] => $originalId
                                )
                            ));

                        $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
                        $perPage = $totalRows = 1000;
                        $maxPages = ceil($totalRows/$perPage);//maximum number of pages that could be returned
                        $pagination = new Pagination($page,$perPage,$totalRows);

                        if(!empty($allRows)){
                            include(ADMIN_PATH.DS."common/listTable.php");
                        }else{
                            echo "No records found. ";
                        }



                    ?>

                </div>
                <?php endif; ?>


        </div>

    </form>
    <?php endforeach; ?>



<?php if(!empty($id) && ($table->countContentHistoryById($id) > 0 )) : 
        $versions = $table->getContentHistoryByRowId($id);
    ?>
    <br />
    <!-- Content version history drop down-->
    <div class="content-version">
        <?php echo $table->countContentHistoryById($id) . ' older versions you can revert back to. '; ?>

        <div class="field input-control text">
            <select name="versionId" id="changeDateSelect" data-current-table="<?php echo $tableName; ?>" data-current-id="<?php echo $id; ?>" onchange="document.location = this.value">
                <option value="<?php echo pageLink("generate.php?table={$tableName}&id={$id}"); ?>">No version selected</option>
                <?php $i=0; foreach($versions as $version) : $i++;
                        if($i == 1){
                            continue; 
                        }
                    ?>
                    <option value="<?php echo pageLink("generate.php?version={$version['id']}&table={$tableName}&id={$id}"); ?>" <?php echo $versionId == $version['id'] ? ' selected="selected" ' : ''; ?>><?php echo date("d F, Y @ h:i:s",strtotime($version['created'])); ?> -- by <?php echo User::getUsername($version['edited_by']); ?></option>
                    <?php endforeach; ?>
            </select>
        </div>
    </div>
    <?php endif; ?>

<style type="text/css">
    .tabbed-page.in-active{
        display:none;
    }

    ul#navlist
    {
        margin-left: 0;
        padding-left: 0;
        white-space: nowrap;

        margin-bottom:20px;

        border-bottom:thick solid #036;

    }

    #navlist li
    {
        display: inline;
        list-style-type: none;

    }

    #navlist a { 


        padding: 5px 20px 0px 20px;
        font-size:20px !important;
    }

    #navlist li a.active {
        background-color: #369;
        outline:0;
    }

    #navlist a:link, #navlist a:visited
    {
        color: #fff;
        background-color: #036;
        text-decoration: none;

    }

    #navlist a:hover
    {
        color: #fff;
        background-color: #369;
        text-decoration: none;
    }

</style>

<script type="text/javascript">

    function updateGenerateForm(){
        $(".tabbed-page").each( function(){
                $(this).closest(".generateForm").removeAttr("id"); 
                $(this).find(".save-generate-form").removeAttr("id"); 
        });
        $(".tabbed-page.active").closest(".generateForm").attr("id","generateForm");
        $(".tabbed-page.active").find(".save-generate-form").attr("id","save");
    }

    $(document).ready(function(){

            updateGenerateForm();


            $(".tabs li a").click(function(e){
                    $(".tabs li a").removeClass("active");
                    $(this).addClass("active");

                    e.preventDefault();
                    $(".tabbed-page").removeClass("active").addClass("in-active");
                    $($(this).attr("href")).addClass("active").removeClass("in-active");

                    updateGenerateForm();
            });
    });
    </script>