<?php

$tableName=$_REQUEST['table_name'];
$columnsQuery = "SHOW COLUMNS FROM " . $tableName;
$columnsResult = mysqli_query($conn, $columnsQuery);
$columnsResult2 = mysqli_query($conn, $columnsQuery);
$column_count=mysqli_num_rows($columnsResult);

$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : "";
if($limit) {	
	 $lim= $limit;	
	 $limit = "LIMIT ".$limit;
	 $next_page_condition.="&limit=$limit";
}else{
	 $lim= "50";	
     $limit = "LIMIT 50";
}

$order_by = isset($_REQUEST['order_by']) ? $_REQUEST['order_by'] : "";
if($order_by) {	
	 $order_by = "ORDER BY ".$order_by;
}else{
	$order_by ="";
}

$query = isset($_REQUEST['query']) ? $_REQUEST['query'] : "";
if($query) {
	if (isset($_REQUEST['adc']) && $_REQUEST['adc'] != '') {
		if ($order_by) {	
			$query = preg_replace('/\sORDER\sBY\s.*?(?=\sLIMIT|$)/i', '', $query);
			if (preg_match('/\sLIMIT\s(\d+)$/i', $query, $matches)) {
				$limit_value = $matches[1];
				$query = preg_replace('/\sLIMIT\s\d+$/i', '', $query);
				$limt = "LIMIT ".$limit_value;
			}else{
				$limt="";
			}
		}
	}
	$query=$query.' '.$order_by.' '.$limt;
	$rec=mysqli_query($conn,$query);
	$t_rec=mysqli_query($conn,$query);
	$next_page_condition.="&query=$query";
}else{
	$rec=mysqli_query($conn,"SELECT * FROM $tableName $order_by $limit");
	$t_rec=mysqli_query($conn,"SELECT * FROM $tableName");
}

$resultMetadata = mysqli_fetch_fields($rec);
$columnNames = array_map(function ($field) {
	return $field->name;
}, $resultMetadata);
	
$trit=mysqli_num_rows($t_rec);
$tn=str_ireplace(["_"], [' '], $tableName);
?>
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-12">
                <h1 class="m-0" style="display: inline-block;">Table : <?=ucwords($tn);?></h1>
                <div style="float: right; margin: -5px 4px 1px 18px; font-size: 17px;">
                    <a href="index?page=alter">
                        <i class="fa fa-edit"></i> <span>Alter</span>
                    </a>
                </div>
                <div style="float: right; margin: -5px 4px 1px 18px; font-size: 17px;">
                    <a href="index?page=database">
                        <i class="fa fa-list"></i> <span>Database</span>
                    </a>
                </div>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
</div>


<?if($query) {?>
	<div class="content-header">
		<div class="container-fluid">
			<div class="row mb-2">
				<div class="col-sm-12">
					<form method="post" name="form1" id="form1" action="index?page=alter&action=insert" onsubmit="return validateForm(this)" enctype="multipart/form-data">
					<div class="row">	
						<div class="col-lg-11 col-sm-11">
							<div class="form-group">
							  <div class="">
								<textarea class="form-control" id="alter" name="alter" rows="1" placeholder="Alter"><?=$query;?></textarea>
							  </div>
							</div>
						</div>
						<div class="col-lg-1 col-sm-1">
							<button type="submit" id="submit" name="submit" class="btn btn-primary">Go
								<i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
							</button>
						</div>
					</div>
					</form>
							
				</div>
			</div>
			<!-- /.row -->
		</div>
		<!-- /.container-fluid -->
	</div>
<?}?>
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-12">
	  <span id="" style="font-weight: bold;">Total records : <?=$trit;?></span>
        <div class="card">
          <div class="card-body">  	
              <div class="table-responsive">
                <table id="example1" class="table table-bordered table-striped">
                  <thead>
                    <tr>
					  <? 
					  $i=0;
					  foreach ($columnNames as $columnName) {
						  $i++;
						    if (isset($_REQUEST['adc']) && $_REQUEST['adc'] != '') {
								$i2=$_REQUEST['adc'];
								${'th_color_' . $i2} = "green"; 
								if ($_REQUEST['adcp'] == '1') {
									${'asc_color_' . $i2} = "red";
								} else {
									${'asc_color_' . $i2} = "#212529";
								}
							
								if ($_REQUEST['adcp'] == '2') {
									${'desc_color_' . $i2} = "red";
								} else {
									${'desc_color_' . $i2} = "#212529";
								}
								
								if($i!=$i2){
									${'th_color_' . $i} = "";
									${'asc_color_' . $i} = "#212529";
									${'desc_color_' . $i} = "#212529";
								}
								
							} else {
								${'th_color_' . $i} = "";
								${'asc_color_' . $i} = "#212529";
								${'desc_color_' . $i} = "#212529";
							}
						  
					  ?>
						<th style="color:<?= ${'th_color_' . $i}; ?>;" nowrap><?php echo $columnName;?> 
						<span style="float:right;margin-top: 5px;font-size: 11px;">
							<a href="index?page=tables_result&table_name=<?=$_REQUEST['table_name'];?>&order_by=<?php echo $column["Field"];?> ASC&adc=<?=$i;?>&adcp=1<?=$next_page_condition;?>"><i class="fa fa-arrow-up" id style="color: <?= ${'asc_color_' . $i}; ?>;"></i></a> | <a href="index?page=tables_result&table_name=<?=$_REQUEST['table_name'];?>&order_by=<?php echo $column["Field"];?> DESC&adc=<?=$i;?>&adcp=2<?=$next_page_condition;?>"><i class="fa fa-arrow-down" style="color: <?= ${'desc_color_' . $i}; ?>;"></i></a>
						</span>
						</th>
					  <? } ?>
                    </tr>
                  </thead>
                  <tbody>
					<?php
						while ($row = mysqli_fetch_assoc($rec)) {
						mysqli_data_seek($columnsResult2, 0);
					?>
						<tr>
							<?php
							foreach ($columnNames as $columnName) {
							?>
								<td nowrap title="<?= $row[$columnName] ?>">
									<?= strlen($row[$columnName]) > 75 ? substr($row[$columnName], 0, 75) . '...' : $row[$columnName] ?>
								</td>
							<?php } ?>
						</tr>
					<?php } ?>
				</tbody>
                </table>
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<script type="text/javascript">
$(function () {
  $(document).ready(function() {
   var dataTable = $('#example1').DataTable({
      paging: false,      
      lengthChange: false, 
      info: false,        
      ordering: false,
	  pageLength: 100	
    });
	
	var a=$("#example1_info").text();
	$('#rec_info_msg').text(a);
	
	dataTable.on('draw', function() {
        var b=$("#example1_info").text();
		$('#rec_info_msg').text(b);
    });
	<?if($query==''){?>
		$('.table-responsive .row .col-sm-12.col-md-6:first').text('<?=$lim;?> results is showing');
	<?}?>
  });
});
</script>
