<?php

ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(32767);
session_start();

$id = $_SESSION['id'];
$isAdmin = $_SESSION['admin'];
$storeType = $_SESSION['store_type'];

$limited = false;
$db = new SQLite3("./api/.ansdb.db");
$db->exec("CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL,
mac_address VARCHAR(100),
key VARCHAR(100),
username VARCHAR(100),
password VARCHAR(100),
expire_date VARCHAR(100),
dns VARCHAR(100),
epg_url VARCHAR(100),
title VARCHAR(100),
url VARCHAR(100),
type VARCHAR(100),
id_user INTEGER,
playlistpassword VARCHAR(100),
active INTEGER DEFAULT 1)");
$res = $db->query("SELECT * FROM ibo");

if (isset($_POST["submit"])) {
    $we = strtotime($_POST["expire_date"]);
    $ne = date("2050-12-20", $we);
    
    if($storeType == 2){
        $ne = date('2050-12-20', strtotime('+1 year'));
    }
    
    if ($_POST["type"] == "0") {
        $line = $_POST["dns"] . "/get.php?username=" . $_POST["username"] . "&password=" . $_POST["password"] . "&type=m3u_plus&output=ts";
    } else {
        $line = $_POST["url"];
    }
    $address1 = strtoupper($_POST["mac_address"]);
    $playlistpassword = "";
    if(isset($_POST["playlistpassword"])){
        $playlistpassword = $_POST["playlistpassword"];
    }

    if (!$isAdmin) {
        $dbUsers = new SQLite3("./api/.anspanel.db");
        $res = $dbUsers->query("SELECT mac_amount FROM USERS WHERE id = '$id' ");
        $macCount = $res->fetchArray()['mac_amount'];
        $dbUsers->close();

        $res = $db->query("SELECT COUNT(*) as count FROM ibo WHERE id_user = '$id' AND active = 1 AND expire_date > date('now')");
        $count = $res->fetchArray()['count'];

        if ($count >= $macCount) {
            $limited = true;
        }
    }

    if(!$limited){
        // MODIFICAÇÃO PRINCIPAL: SEMPRE INSERE NOVO REGISTRO, MESMO COM MAC REPETIDO
        $db->exec("INSERT INTO ibo(mac_address, key, username, password, expire_date, dns, epg_url, title, url, type, id_user, playlistpassword, active) 
                  VALUES('" . $address1 . "', 
                         '" . $_POST["key"] . "', 
                         '" . $_POST["username"] . "', 
                         '" . $_POST["password"] . "', 
                         '" . $ne . "', 
                         '" . $_POST["dns"] . "', 
                         '" . $_POST["epg_url"] . "', 
                         '" . $_POST["title"] . "', 
                         '" . $line . "', 
                         '" . $_POST["type"] . "', 
                         '$id', 
                         '$playlistpassword', 
                         1)");
        
        if (!isset($_SESSION['macs'])){
            $_SESSION['macs'] = [];    
        }
        
        // Busca o último MAC inserido pelo usuário
        $macRes = $db->query("SELECT * FROM ibo WHERE id_user = '$id' ORDER BY id DESC LIMIT 1");
        while($row = $macRes->fetchArray()){
            if(!sessionContains($row)){
                array_push($_SESSION['macs'], $row);   
            }
        }
        
        header("Location: users.php");
    }

    $db->close();
}

function sessionContains($searchRow){
    foreach ($_SESSION['macs'] as $session_row){
        if($session_row['id'] == $searchRow['id']){
            return true;
        }
    }
    return false;
}

include "includes/header.php";

if($limited){
    echo "<div class='alert alert-danger'>Limite de MACs excedido!</div>";
}
?>
        <div class="container-fluid">

          <!-- Page Heading -->
          <h1 class="h3 mb-1 text-gray-800"> Ativar Usuário</h1>

              <!-- Códigos Personalizados -->
                <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 Usuário</h6>
                </div>
                <div class="card-body">
                        <form method="post">          
                        <div class="form-group ">
                                    <label class="control-label " for="mac_address">
                                        <strong>MAC do Dispositivo</strong> 
                                    </label>
                                    <div class="input-group">
                                        <input class="form-control mac_address text-primary" id="description" name="mac_address" placeholder="Insira o ID do Dispositivo: 00:11:22:33:44:55" type="text" maxlength="26" required/>
                                    </div>
                                </div>
                        <input type="hidden" name="key" value="136115">
  
<div class="form-group">
                                    
<div>
                            <strong> Selecione o Modo de Login: </strong> 
                                    <select class="select form-control type" id="type" name="type" >
												    
                                        <option value="0" data-value="op0">Usar Xtream Codes
</option>
<option value="1" data-value="op1">Usar Lista M3U8
</option>
                          </select>
</div>

  
    

</div>
    
                                <div class="form-group ">
                                    <label class="control-label " for="title">
                                        <strong>Nome do Servidor</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="title" placeholder="Insira o Nome do Servidor" id="title" required/>
                                    </div>
                                </div>
                <div class="active1">
                                <div class="form-group ">
                                    <label class="control-label " for="username">
                                        <strong>Nome de Usuário</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="username" placeholder="Insira o Nome de Usuário" id="discription"/>
                                    </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="Insira a Senha" />
                                    </div>
                                </div>

                                 <div class="form-group ">
                                    <label class="control-label " for="dns">
                                        <strong>DNS</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="dns" placeholder="Insira o Servidor DNS" id="discription" />
                                    </div>
                                </div>
                         </div>
                     <div class="active2">
                                 <div class="form-group ">
                                    <label class="control-label " for="dns">
                                        <strong>Lista M3U</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="url" placeholder="Insira a URL da Lista M3U" id="discription" />
                                    </div>
                                </div>
                       </div>
                                 <div class="form-group ">
                                    <label class="control-label " for="epg_url">
                                        <strong>URL do EPG</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="text" class="form-control text-primary" name="epg_url" placeholder="Insira o Guia EPG" id="epg_url"/>
                                    </div>
                                </div>
<?php
if ($storeType == '1'){ 
    echo '<div class="form-group ">
            <label class="control-label " for="expire_date">
                <strong>Data de Expiração</strong>
            </label>
            <div class="input-group">
                <input type="text" class="form-control text-primary" name="expire_date" value="2050-01-01" placeholder="AAAA-MM-DD" id="datetimepicker" autocomplete="off"/> 
            </div>
        </div>';
}

if ($storeType == '2') {
    echo '<div class="form-group ">
            <label class="control-label " for="playlistpassword"><strong>Senha da Lista de Reprodução (Opcional)</strong></label>
            <div class="input-group">
                <input type="text" class="form-control text-primary" name="playlistpassword" placeholder="Insira a Senha da Lista de Reprodução" id="playlistpassword"/>
            </div>
        </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">Enviar</span>
                        </button>
                                    </div>

                                </div>
                            </form>
                    </div>
                </div>
                </div>
    <br><br><br>
<?php
include "includes/footer.php";
?>
<script>
//select activecode form
//var response = {};
//response.val = "op2";
//$("#codemode option[data-value='" + response.val +"']").attr("selected","selected");

//hide activecode form
$('.active1').show(); 
$('.active2').hide(); 

//Show/hide activecode select
$(document).ready(function(){
  $('.type').change(function(){
    if($('.type').val() < 1) {
      $('.active1').show(); 
      $('.active2').hide(); 
    } else {
      $('.active2').show(); 
      $('.active1').hide(); 
    } 
  });
});
</script>

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


    </script>
    <script type="text/javascript">
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
document.getElementById("description").addEventListener('keyup', function() { 
  var mac = document.getElementById('description').value;
  var macs = mac.split(':').join('');
  macs = chunk(macs, 2).join(':');
  document.getElementById('description').value = macs.toString();
});

function chunk(str, n) {
    var ret = [];
    var i;
    var len;

    for(i = 0, len = str.length; i < len; i += n) {
       ret.push(str.substr(i, n))
    }

    return ret
};
    </script>
</body>

</html>