<?php

ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);
$db = new SQLite3('./a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS `revenda` (
    `id` INTEGER PRIMARY KEY,
    `nome` TEXT NOT NULL,
    `usuario` TEXT NOT NULL,
    `senha` TEXT NOT NULL,
    `registro` TIMESTAMP NOT NULL,
    `macs` INTEGER NOT NULL
);');

$res = $db->query('SELECT * FROM revenda');

include 'includes/header.php';

if(isset($_GET['index'])) {
    $index = $_GET['index'];

} else {

    $index = ""; // Default value

}


if (isset($_POST['submit'])) {
	
	$usuario = $_POST['username'];
	$result = $db->query("SELECT COUNT(*) as count FROM revenda WHERE usuario = '$usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];
    
    $result = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count2 = $row['count'];
    
    $count = $count + $count2;
      
    if($count || $usuario == "ADM") {
      echo "<script>alert('Já existe um sub revenda/revenda com esse usuario, por favor escolha outro!');window.location.href='revenda.php';</script>";
    } else {
        
    	$registro = date('Y/m/d');
    	$nome = $_POST['nome'];
    	$senha = $_POST['password'];
    	$macs = $_POST['macs'];
    	$descricao = $_POST['Descricao'];
    	
        $query = "SELECT MAX(max_value) AS maior_valor FROM (
                SELECT MAX(id_ref) AS max_value FROM revenda
                UNION
                SELECT MAX(id_ref) AS max_value FROM sub_revenda
              ) as combined";
        $result = $db->query($query);
        $row = $result->fetchArray(SQLITE3_ASSOC);
        $ref_id = $row['maior_valor'];
        $ref_id++;
        echo "O maior valor da coluna é: " . $row['maior_valor'];
    	
    	$db->exec("INSERT INTO revenda (nome, usuario, senha, registro, macs, extra, id_ref) VALUES('$nome', '$usuario', '$senha', '$registro', '$macs', '$descricao', '$ref_id')");
    	$db->close();
    	
    	// criar arquivos default:

    $caminho_arquivo = "a/rtx/";
    $resultado = file_put_contents($caminho_arquivo . "Setting_$usuario.json", file_get_contents($caminho_arquivo . "Setting.json"));
	$resultado = file_put_contents($caminho_arquivo . "logo_filenames_$usuario.json", file_get_contents($caminho_arquivo . "logo_filenames.json"));
	$resultado = file_put_contents($caminho_arquivo . "image_filenames_$usuario.json", file_get_contents($caminho_arquivo . "image_filenames.json"));
	$resultado = file_put_contents("a/note_$usuario.json", file_get_contents("a/note.json"));
	$resultado = file_put_contents("a/qrcode_$usuario.json", file_get_contents("a/qrcode.json"));
	$caminho_arquivo = "api/theme_$usuario.json";
	$resultado = file_put_contents($caminho_arquivo, file_get_contents("api/theme.json"));

        echo "<script>window.location.href='revenda.php'</script>";

    }
}


?>


<div class="container-fluid">
    <h1 class="h3 mb-1 text-gray-800">Painel de Revenda</h1>
        <div class="card border-left-primary shadow h-100 card shadow mb-4">
      
        
</div>
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-user"></i> Detalhes do Revenda:</h6>
        </div>
        <div class="card-body">
            <form method="post">
                <div class="form-group">
                    <label class="control-label" for="nome">
                        <strong>Nome</strong>
                    </label>
                    <div class="input-group">
                        <input class="form-control text-primary" id="nome" name="nome" placeholder="Digite o Nome" type="text" value="" required/>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label" for="title">
                        <strong>MACs</strong>
                    </label>
                    <div class="input-group">
                        <input type="number" min="1" max="99999" class="form-control text-primary" name="macs" placeholder="Numero de MACs" id="macs" value="" required/>
                    </div>
            </div>
           
            <div class="form-group">
                <label class="control-label" for="username">
                    <strong>Usuario</strong>
                </label>
                <div class="input-group">
                    <input type="text" class="form-control text-primary" name="username" placeholder="Enter Username" id="username"  required/>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label" for="password">
                    <strong>Senha</strong>
                </label>
                <div class="input-group">
                    <input type="text" class="form-control text-primary" name="password" placeholder="Enter Password" id="password"  required/>
                </div>
            </div>
             <div class="form-group">
                    <label class="control-label" for="nome">
                        <strong>Descricao</strong>
                    </label>
                    <div class="input-group">
                        <input class="form-control text-primary" id="Descricao" name="Descricao" placeholder="Digite a Descricao" type="text" value="" required/>
                    </div>
                </div>
          
            <div class="form-group">
                <div>
                    <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                        <span class="icon text-white-50"><i class="fas fa-check"></i></span><span class="text">Submit</span>
                    </button>
                </div>
            </div>
</form>
</div>
</div>
</div>
<br><br><br>

<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>


</body>
<?php 
include 'includes/footer.php';
?>
</html>