<?php
session_start();

// Verifica se os dados foram enviados pelo formulário
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Obtém os dados do formulário
   $usuario_digitado = $_POST["usuario"];
   $senha_digitada = $_POST["senha"];

   $db_check1 = new SQLite3('.eggziepanels.db');
   
  $db_check1->exec('CREATE TABLE IF NOT EXISTS USERS(id INT PRIMARY KEY,NAME TEXT,USERNAME TEXT,PASSWORD TEXT,LOGO TEXT)');
  $rows = $db_check1->query('SELECT COUNT(*) as count FROM USERS');
  $row = $rows->fetchArray();
  
  $numRows = $row['count'];
  if ($numRows == 0) {
    $db_check1->exec('INSERT INTO USERS(id,NAME,USERNAME,PASSWORD,LOGO) VALUES(\'1\',\'Administrador\',\''.$usuario_digitado.'\',\''.$senha_digitada.'\',\'img/logo.png\')');
  }

  $res_login = $db_check1->query('SELECT * '."\n\t\t\t\t".'  FROM USERS '."\n\t\t\t\t".'  WHERE id=\'1\'');
  $row_login = $res_login->fetchArray();
  
  //echo "<p>cccc: ".$row_login['NAME']."<p>";
  
  if (isset($_POST['usuario'])) {
    $sql_check = 'SELECT * from USERS where USERNAME="'.$usuario_digitado.'"';
    $ret_check = $db_check1->query($sql_check);

    while ($row_check = $ret_check->fetchArray()) {
        $id_check = $row_check['id'];
        $NAME = $row_check['NAME'];
        $USERNAME = $row_check['USERNAME'];
        $PASSWORD = $row_check['PASSWORD'];
    }
  }

    //echo "<p>eee: ".$USERNAME."<p>";  

    if (empty($id_check)) {
      header('Location: login.php');
    }
    else if ($PASSWORD == $_POST['senha']) {
      $_SESSION['usuarioadminpainel'] = $usuario_digitado;
      $_SESSION['logged_in'] = true;
      
     header('Location: index.php');
    }

}
?>
