<?php

ini_set('display_errors', 0);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('../a/.eggziedb.db');

include '../includes/header2.php';
if(isset($_GET['update'])) {
    $sub_revenda_id = $_GET['update'];
    $res1 = $db->query("SELECT * FROM sub_revenda WHERE id = '$sub_revenda_id' AND registrado_por = '$seller_name'");
    while ($row1 = $res1->fetchArray()) {
                                  
        $sub_revenda_id = $row1['id'];
        $sub_revenda_nome = $row1['nome'];
        $sub_revenda_usuario = $row1['usuario'];
        $user = $sub_revenda_usuario;
        $sub_revenda_senha = $row1['senha'];
        $sub_revenda_registro = $row1['registro'];
        $sub_revenda_macs = $row1['macs'];
        $sub_revenda_extra = $row1['extra'];
        
    }
} else {
    echo "<script>alert('Selecione o sub revenda a ser editado!');</script>";
    echo "<script>window.location.href='sub_revenda.php';</script>";
}

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' AND usuario <> '$sub_revenda_usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];
    
    $result = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$usuario' AND usuario <> '$sub_revenda_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='sub_revenda.php';</script>";
    } else {
        
          $result = $db->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
         // Iterate over the fetched results
         while ($row = $result->fetchArray()) {
             // Output the value of the column
             $macs_rev = $row['macs'];
             break;
         }
         
         $result = $db->query("SELECT macs FROM sub_revenda WHERE id = '$sub_revenda_id'");
         // Iterate over the fetched results
         while ($row = $result->fetchArray()) {
             // Output the value of the column
             $macs_sub = $row['macs'];
             break;
         }
    	
    	$registro = date('Y/m/d');
    	$nome = $_POST['nome'];
    	$Descricao = $_POST['Descricao'];
    	$usuario = $_POST['username'];
    	$senha = $_POST['password'];
    	$new_macs = $_POST['macs'];
    	
    	if($new_macs < $macs_sub) {
    	         echo "<script>alert('O numero de MACs deve ser maior ou igual ao numero de MAcs atuais!');window.location.href='sub_revenda.php';</script>";
    	} else {
    	        
    	        $dif_macs = $new_macs - $macs_sub;
    	        $newmac = $macs_rev - $dif_macs;
    	    	if($dif_macs > $macs_rev) {
    	            echo "<script>alert('MACs insuficientes para cobrir o novo valor!');window.location.href='sub_revenda.php';</script>";
    	        } else {
        	
                	$db->exec("UPDATE sub_revenda SET nome = '$nome', usuario = '$usuario', senha = '$senha', macs = '$new_macs', extra = '$Descricao' WHERE id = '$sub_revenda_id' AND registrado_por = '$seller_name'");
                	  $db->exec("UPDATE revenda SET macs = '$newmac' WHERE usuario = '$seller_name'");
                	  	// renomear arquivos e outros
                    rename("../a/rtx/Setting_$user.json", "../a/rtx/Setting_$usuario.json");
                    rename("../a/rtx/logo_filenames_$user.json", "../a/rtx/logo_filenames_$usuario.json");
                    rename("../a/rtx/image_filenames_$user.json", "../a/rtx/image_filenames_$usuario.json");
                    rename("../a/note_$user.json", "../a/note_$usuario.json");
                    rename("../api/theme_$user.json", "../api/theme_$usuario.json");
                    
                    $db2 = new SQLite3("../api/.adb.db");
                    $db2->exec("UPDATE ads SET owner = '$usuario' WHERE owner = '$user'");
                    $db3 = new SQLite3("../api/intro.db");
                    $db3->exec("UPDATE intro SET owner = '$usuario' WHERE owner = '$user'");
                	$db->close();
                	echo "<script>window.location.href='sub_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-primary2"><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="<?php echo $sub_revenda_nome;?>" 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="999" class="form-control text-primary" name="macs" placeholder="Numero de MACs" id="macs" value="<?php echo $sub_revenda_macs;?>" 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" value="<?php echo $sub_revenda_usuario;?>" 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" value="<?php echo $sub_revenda_senha;?>" required/>
                </div>
            </div>
            
              <div class="form-group">
                    <label class="control-label" for="Descricao">
                        <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="<?php echo $sub_revenda_extra;?>" required/>
                    </div>
                </div>
            
            <b style="color: red;"> O numero da diferença de MACs será descontado do seu saldo de MACs!</b><br><br>
          
            <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/footer2.php';
?>
</html>
