<?php
session_start();
require_once("./config/conexao.php");
$conn   = conn();
$conn_s = conn_s();

$success = true;

if($_SESSION['id_user'] == '1'){

  if(@$_POST['FAZER_BACKUP']){
    $tabela      = $_POST['tabela'];
    $tabela_bkp  = $_POST['tabela_bkp'];
    $limite  = $_POST['limite'];
    $usar_campos = $_POST['usar_campos'];
    $select_db   = $_POST['db'];

    if($select_db == "conn"){
      $use_con = $conn;
    } else {
      $use_con = $conn_s;
    }

    $where = '';
    if(!empty($_POST['in_id'])){
      $in_id = $_POST['in_id'];
      if(mb_strpos($in_id, ',') !== false){
        $where = " WHERE id IN ($in_id) ";
      } else {
        $where = " WHERE id = $in_id ";
      }
    }

    $tabela_q_sql = "SELECT * FROM `$tabela` $where ORDER BY `id` ASC LIMIT $limite";
    $tabela_query = mysqli_query($use_con, $tabela_q_sql);

    if($tabela_query){

      $tabela_bkp_q_sql = "SELECT * FROM `$tabela_bkp` ORDER BY `id` ASC LIMIT 1";
      $tabela_bkp_query = mysqli_query($use_con, $tabela_bkp_q_sql);
      
      if($tabela_bkp_query){
        $tabela_bkp_query = mysqli_fetch_assoc($tabela_bkp_query);

        $campos = '';
        $values = '';
        while($info = mysqli_fetch_assoc($tabela_query)){
          $id_data = $info['id'];
          $row_pos = 1;
          if($usar_campos == 2){
            $count   = count($tabela_bkp_query);
            foreach($tabela_bkp_query as $k => $v){
				      $v = $info[$k];
              if(empty($v) && $v !== '0'){
                $v = "NULL";
              } else {
                $v = "'$v'";
              }
              if($row_pos == 1){
                $campos = "(`$k`,";
                $values = "($v,";
              } else if($row_pos == $count){
                $campos .= "`$k`)";
                $values .= "$v)";
              } else {
                $campos .= " `$k`,";
                $values .= " $v,";
              }
              $row_pos++;
            }
          } else {
            $count   = count($info);
            foreach($info as $k => $v){
              if(empty($v) && $v !== '0'){
                $v = "NULL";
              } else {
                $v = "'$v'";
              }
              if($row_pos == 1){
                $campos = "(`$k`,";
                $values = "($v,";
              } else if($row_pos == $count){
                $campos .= "`$k`)";
                $values .= "$v)";
              } else {
                $campos .= " `$k`,";
                $values .= " $v,";
              }
              $row_pos++;
            }
          }

          $check_tabela_bkp_sql = "SELECT * FROM $tabela_bkp WHERE id = $id_data";
          $check_tabela_bkp     = mysqli_query($use_con, $check_tabela_bkp_sql);
          $check_tabela_bkp     = mysqli_num_rows($check_tabela_bkp);

          if($check_tabela_bkp == 0){

            $insert_sql = "INSERT INTO `$tabela_bkp`$campos VALUES $values";
            $insert     = mysqli_query($use_con, $insert_sql);
  
            if($insert){
              $delete_sql = "DELETE FROM `$tabela` WHERE id=$id_data";
              $delete     = mysqli_query($use_con, $delete_sql);
			  
              if(!$delete){
                $success = false;
				
                header("Location: /sistema/backup_tabelas.php?status=2&msg=Ocorreu algum erro ao tentar excluir os dados da tabela original");
                break;
              }
  
            } else {
              $success = false;
			  
              header("Location: /sistema/backup_tabelas.php?status=2&msg=Ocorreu algum erro ao adicionar os dados na tabela de backup: ($insert_sql)");
              break;
            }
          } else {
              $delete_sql = "DELETE FROM `$tabela` WHERE id=$id_data";
              $delete     = mysqli_query($use_con, $delete_sql);
        
              if(!$delete){

                header("Location: /sistema/backup_tabelas.php?status=2&msg=Ocorreu algum erro ao tentar excluir os dados da tabela original");
                break;
              }
          }
        }

        if($success){
          header("Location: /sistema/backup_tabelas.php?status=1&msg=tudo certo");
        }
      } else {
		
        header("Location: /sistema/backup_tabelas.php?status=2&msg=não foi possível encontrar a tabela_bkp");
      }
    } else {
	  
      header("Location: /sistema/backup_tabelas.php?status=2&msg=não foi possível encontrar a tabela");
    }
  }



?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>BACKUP tabelas</title>
</head>
<body>

  <?php
    if(isset($_GET['status'])){
      if($_GET['status'] == 1){
        ?>
          <div style="padding:10px;background-color:#0f0;"><?= $_GET['msg'] ?>.</div>
        <?php
      } else{
        ?>
          <div style="padding:10px;background-color:#f00;"><?= $_GET['msg'] ?>.</div>
        <?php
      }
    }
  ?>
  
<form action="" method="post">
  <input type="text" name="tabela" placeholder="tabela">
  
  <input type="text" name="tabela_bkp" placeholder="tabela_bkp">
  <input type="number" name="limite" placeholder="Limite">
  <input type="text" name="in_id" placeholder="id IN">
  
  <select name="usar_campos">
    <option value="1">Tabela</option>
    <option value="2">Tabela_bkp</option>
  </select>

  <select name="db">
    <option value="conn">unidos</option>
    <option value="conn_S">unidos_sistema</option>
  </select>
  
  <input type="submit" name="FAZER_BACKUP" value="ENVIAR">
</form>
</body>
</html>
<?php
}

?>