<?php 
  require_once("./session_job.php");
  date_default_timezone_set('America/Bahia');

  if ($_SESSION['id_user'] != '11' && $_SESSION['id_user'] != '6' && $_SESSION['id_user'] != '1') {
    header('Location: index.php');
  }

  require_once("./config/conexao.php");
  $conn = conn();

  require_once("./checar_loja.php");
  $loja_id = $_SESSION['loja'];

  function connWeb(){
     $db = mysqli_connect("192.185.176.211", "unidosim_newjay", "Chamod@777", "unidosim_db_system") or die("Erro ao selecionar banco");
     //   $db = mysqli_connect("localhost", "root", "", "unidos_web") or die("Erro ao selecionar banco");
     mysqli_set_charset($db,"utf8");
     return $db;
  }
  $connWeb = connWeb();


  if (!empty($_POST['tabela'])) {

    $db         = $_POST['db'];
    $qtd_linhas = $_POST['qtd_linhas'];

    $query_sql  = "SELECT * FROM tabelas_backup WHERE id=".$_POST['tabela'];
    $query_info = mysqli_fetch_array(mysqli_query($conn, $query_sql));

    if ($query_info) {

      $tabela     = $query_info['tabela'];
      $tabela_bkp = $query_info['tabela_bkp'];


      $query_sql = "SELECT * FROM $tabela ORDER BY id ASC LIMIT $qtd_linhas";

      if ($db == 'web') {
        
        $new_query = mysqli_query($connWeb, $query_sql);

      } else {

        $new_query = mysqli_query($conn, $query_sql);
      }

      if ($new_query) {
        while($row = mysqli_fetch_assoc($new_query)){

          $places = '(';
          $values = '(';
          $count_row = count($row);
          $count = 1;
          foreach ($row as $key => $value) {
            if ($count < $count_row) {
              
              $places .= "$key, ";
              $values .= "'$value', ";
              
            } else {

              $places .= "$key)";
              $values .= "'$value')";
            }
            
            $count++;
          }

          $query_sql = "INSERT INTO $tabela_bkp $places VALUES $values";

          if ($db == 'web') {
            
            $query_insert = mysqli_query($connWeb, $query_sql);

          } else {

            $query_insert = mysqli_query($conn, $query_sql);
          }

          if ($query_insert) {
            $id_row = $row['id'];

            $query_sql = "DELETE FROM $tabela WHERE id = $id_row";

            if ($db == 'web') {
              
              $query_delete = mysqli_query($connWeb, $query_sql);

            } else {

              $query_delete = mysqli_query($conn, $query_sql);
            }

            if (!$query_delete) {

              header('Location: fazer_backup.php?msg=2');
            }

          } else {

            header('Location: fazer_backup.php?msg=2');
          }

        }

        if ($query_delete) {
          header('Location: fazer_backup.php?msg=1');
        }

      } else {

        header('Location: fazer_backup.php?msg=2');
      }

    } else {

      header('Location: fazer_backup.php?msg=2');
    }
    
  }

  $quantos_resultados=0;
  $isset_get = false;
  if (!empty($_GET['tabela'])) {
    $isset_get = true;
    
    $query_sql    = "SELECT * FROM tabelas_backup WHERE id=".$_GET['tabela'];
    $query_tabela = mysqli_fetch_assoc(mysqli_query($conn, $query_sql));

    $query_sql = "SELECT * FROM ".$query_tabela['tabela'];

    if ($_GET['db'] == 'web') {
      
      $query_qtd = mysqli_query($connWeb, $query_sql);

    } else {

      $query_qtd = mysqli_query($conn, $query_sql);
    }

    $quantos_resultados = mysqli_num_rows($query_qtd);
  }
?>
<!DOCTYPE html>
<html lang="pt-br">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>BACKUP</title>

  <link rel="stylesheet" href="./utils/css/bootstrap.min.css" />
  <link rel="stylesheet" href="./utils/css/bootstrap-select.min.css" />
  <link rel="stylesheet" href="./utils/css/styles.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"
    integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous" />

  <style type="text/css">
  .disabled {
    cursor: no-drop !important;
  }

  .content_form_bkp{
    padding: 15px;
    display: flex;
    justify-content: center;
    gap: 20px;
  }
  </style>
</head>

<body>
  <nav class="navbar">
    <div class="container caixa_logo">
      <a class="" href="javascript:void(0);">
        <img src="./utils/img/logo.png" alt="" width="150" />
      </a>
      <div>
        <?php if ($_SESSION['id_user'] == '1'){?>
        <span><a href="index.php"><img src="./utils/img/icons/home.svg" width="19"></a></span> &nbsp;
        <span><a href="users.php"><img src="./utils/img/icons/user.svg" width="17"></a></span> &nbsp;
        <?php }?>
        <span><?= $_SESSION['nome_user'];?></span> &nbsp;
        <span><a href="exit.php"><img src="./utils/img/icons/exit.svg" width="17"></a></span>
      </div>
    </div>
  </nav>
  <?php

    if (!empty($_GET['msg'])) {

      ?>
        <div id="msg-div" style="position: fixed; top: 20%; left: 15px;z-index: 1000;">
          <?php

            if ($_GET['msg'] == '1') {
              
              ?>
                <div style="padding: 10px; background-color: #0f0; border-radius: 10px;">
                  <span>Ação Realizada com sucesso!</span>
                </div>
              <?php

            } else {
              ?>
                <div style="padding: 10px; background-color: #f00; color: #fff; border-radius: 10px;">
                  <span>Algo deu errado!</span>
                </div>
              <?php
            }

          ?>
          <script type="text/javascript">
            const msg_div = document.getElementById('msg-div');
            setTimeout(()=>{
              msg_div.remove();
            },3000);
          </script>
        </div>
      <?php

    }

  ?>

  <div class="container">

    <div class="content_form_bkp">
      <div class="content">
        <form id="form_bkp_tabelas" method="get" action="">
          <h4 class="text-center">Fazer Backup de Tabela</h4>
          <p class="text-center"><small>A tabela selecionada possui <strong><?= $quantos_resultados ?> resultados</strong></small></p>
          <hr>

          <label for="db">Banco de Dados:</label>

          <select name="db" id="db" required class="form-control" onchange="submitForm('form_bkp_tabelas')">
            <option selected disabled>Selecione</option>
            <option value="conn" <?php if (!empty($_GET['db']) && $_GET['db'] == 'conn') {echo "selected";}?>>unidos</option>
            <option value="web" <?php if (!empty($_GET['db']) && $_GET['db'] == 'web') {echo "selected";}?>>unidosim_db_system</option>
          </select>
          

          <label for="tabela">Tabela principal:</label>

          <select name="tabela" id="tabela" required class="form-control" onchange="submitForm('form_bkp_tabelas')">
            <option selected disabled>Selecione</option>

            <?php

              if (!empty($_GET['db'])) {

                $query_sql = "SELECT * FROM tabelas_backup WHERE db ='".$_GET['db']."'";

                $query = mysqli_query($conn, $query_sql);
                
                while($options = mysqli_fetch_array($query)){

                  ?>
                    <option id="<?= $options['id'] ?>" data-tabela_bkp="<?= $options['tabela_bkp'] ?>" value="<?= $options['id'] ?>" <?php if (!empty($_GET['tabela'])){ if($options['id'] == $_GET['tabela']) {echo "selected";}} ?>><?= $options['tabela'] ?></option>
                  <?php
                }
              }

            ?>
          </select>
                    

          <label for="tabela_bkp">Tabela de backup:</label>

          <?php

            if ($isset_get) {

              $query_sql  = "SELECT * FROM tabelas_backup WHERE id =".$_GET['tabela'];
              $query_info = mysqli_fetch_array(mysqli_query($conn, $query_sql));

              if ($query_info['db'] == $_GET['db']) {

                ?>
                  <input type="text" id="tabela_bkp" readonly class="form-control" value="<?= $query_info['tabela_bkp'] ?>">
                <?php
              }
            }

          ?>
          
          <hr>
        </form>
      </div>

    <?php

      if ($isset_get) {
        
        if ($query_info['db'] == $_GET['db']) {

          ?>
              <div class="content">
                <form method="post" action="">

                  <?php

                    $db_get = $_GET['db'];
                    $tabela_get = $_GET['tabela'];

                    $query_sql  = "SELECT * FROM tabelas_backup WHERE id = $tabela_get";
                    $query_info = mysqli_fetch_array(mysqli_query($conn, $query_sql));

                    $tabela_bkp_get = $query_info['tabela_bkp'];

                  ?>
                  
                  <input type="hidden" name="db" value="<?= $db_get ?>">
                  <input type="hidden" name="tabela" value="<?= $tabela_get ?>">

                  <h4 class="text-center">Detalhes do Backup</h4>
                  <p class="text-center"><small>Esse campo indica a quantidade de linhas a serem removidas da tabela principal e inseridas na tabela de backup. As linhas selecionadas são as mais antigas</small></p>
                  
                  <label>Quantidade de linhas da tabela:</label>                 
                  <input type="number" min="1" name="qtd_linhas" class="form-control" value="50" required>


                  <hr>
                  <button style="width:100%;" type="submit" class="btn btn-success" id="btn_backup_tabelas">Fazer Backup</button>
                </form>
              </div>
            </div>
          <?php
        }
      }

    ?>

  </div>


  <!--Footer-->
  <footer>
    <div class="container">
      <p>&copy; UNIDOS IMPORTADOS</p>
      <p>
        DESENVOLVIDO PELA
        <a href="https://agenciadp.com.br/" target="_blank">AGÊNCIA DP WEB</a>
      </p>
    </div>
  </footer>
  <!--/. Footer-->

  

  <script src="./utils/js/jquery-1.12.4.min.js"></script>
  <script src="./utils/js/popper.min.js"></script>
  <script src="./utils/js/bootstrap.min.js"></script>
  <script src="./utils/js/bootstrap-select.min.js"></script>
  <script src="./utils/js/notify.min.js"></script>
  <script src="./utils/js/scripts.js"></script>
  

  <script type="text/javascript">

    function submitForm(form) {
      const form_element = document.getElementById(form);

      form_element.submit();
    }
  </script>
</body>

</html>