<?php
session_start();

$vence = date('Y-m-d', strtotime("+1 YEAR"));
$limited = false;
$db = new SQLite3("./api/db/studiolivecode_clientes.db");
$db->exec("CREATE TABLE IF NOT EXISTS ibo(
    id INTEGER PRIMARY KEY NOT NULL,
    mac_address VARCHAR(17),
    username VARCHAR(100),
    password VARCHAR(100),
    expire_date VARCHAR(10),
    dns VARCHAR(100),
    epg_url VARCHAR(100),
    title VARCHAR(100),
    url VARCHAR(100),
    type INTEGER,
    id_user INTEGER,
    active INTEGER,
    key VARCHAR(100) -- Certifique-se de que a coluna key existe
)");

$id = $_SESSION['id'];
$dbUsers = new SQLite3("./api/db/studiolivecode_users.db");
$query = $dbUsers->query("SELECT admin FROM users WHERE id = $id");
$userData = $query->fetchArray(SQLITE3_ASSOC);
$isAdmin = $userData['admin'] == 1;

if (isset($_POST["submit"])) {
    $mac_address = strtoupper($_POST["mac_address"]);
    $device_key = $_POST["device_key"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $expire_date = $isAdmin ? $_POST["expire_date"] : $vence; // Apenas admin pode definir a data de expiração
    $dns = $_POST["dns"];
    $title = $_POST["title"];
    $type = (int)$_POST["type"];

    if (!$userData || !$isAdmin) {       
        $res = $dbUsers->query("SELECT mac_amount FROM users WHERE id = '$id' ");
        $macCount = $res->fetchArray()['mac_amount'];

        $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) {
        if ($_POST["type"] == "1") {
            $line = $_POST["dns"] . "/get.php?username=" . $_POST["username"] . "&password=" . $_POST["password"] . "&type=m3u_plus&output=ts";
        } else {
            $line = $_POST["url"];
        }

        $insertQuery = "INSERT INTO ibo (
            mac_address, key, username, password, expire_date, dns, epg_url, title, url, type, id_user, active
        ) VALUES (
            '$mac_address', '$device_key', '$username', '$password', '$expire_date', '$dns', '$epg_url', '$title', '$line', $type, '$id', 1
        )";

        $db->exec($insertQuery);

        if (!isset($_SESSION['macs'])) {
            $_SESSION['macs'] = [];
        }

        $macRes = $db->query("SELECT * FROM ibo WHERE mac_address = '$mac_address'");
        while($row = $macRes->fetchArray()){
            if(!sessionContains($row)){
                array_push($_SESSION['macs'], $row);   
            }
        }

        $query = $dbUsers->query("SELECT admin FROM users WHERE id = $id");
        $userData = $query->fetchArray(SQLITE3_ASSOC);

        if (!$userData || !$isAdmin) {
            header("Location: users.php?r=adicionado");
        } else {
            header("Location: all_users.php?r=adicionado");
        }
    }

    $db->close();
}

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

// Função para obter as DNS do banco de dados e criar o seletor
function getDnsOptions() {
    $dbDns = new SQLite3("./api/db/studiolivecode_dns.db");
    $results = $dbDns->query("SELECT url FROM dns");
    $options = "";
    while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
        $options .= "<option value='" . $row['url'] . "'>" . $row['url'] . "</option>";
    }
    $dbDns->close();
    return $options;
}
?>

<?php include './includes/header.php';?>
<?php
if ($limited) {
    ?>
    <div class="alert alert-danger">Limite de MACs excedido!</div>
    <?php
}
?>
<div class="card radius-10">
    <div class="card-body">
        <h4 class="card-title">Adicionar Usuário</h4>
            <form method="post">
                <div class="form-group mb-4">
                    <label class="control-label" for="mac_address">
                        <strong>MAC do Dispositivo</strong>
                    </label>
                    <div class="input-group">
                        <input class="form-control mac_address" id="description" name="mac_address" placeholder="Digite o MAC: 00:11:22:33:44:55" type="text" maxlength="17" required/>
                    </div>
                </div>
                <div class="form-group mb-4">
                    <label class="control-label" for="device_key">
                        <strong>Chave do Dispositivo</strong>
                    </label>
                    <div class="input-group">
                        <input class="form-control" id="device_key" name="device_key" placeholder="Digite a Chave do Dispositivo" type="text" required/>
                    </div>
                </div>
                <div class="form-group mb-4">
                    <label class="control-label " for="type">
                            <strong>Selecione o Modo de Login:</strong>
                    </label>
                        <select class="form-control type" id="type" name="type">
                            <option data-value="op0" value="0" selected>Usar Lista M3U8</option>
                            <option data-value="op1" value="1">Usar Xtream Codes</option>
                        </select>                   
                </div>
                <div class="form-group mb-4">
                    <label class="control-label" for="title">
                        <strong>Nome do Servidor</strong>
                    </label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="title" placeholder="Digite o nome do servidor" id="title" required/>
                    </div>
                </div>
                <div class="actived">
                    <div class="form-group mb-4">
                        <label class="control-label" for="dns">
                            <strong>Lista M3U</strong>
                        </label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="url" placeholder="Digite a lista M3U" id="discription"/>
                        </div>
                    </div>
                </div>
                <div class="activeu">
                    <div class="form-group mb-4">
                        <label class="control-label" for="username">
                            <strong>Usuário</strong>
                        </label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="username" placeholder="Digite o Usuário" id="discription"/>
                        </div>
                    </div>
                    <div class="form-group mb-4">
                        <label class="control-label" for="password">
                            <strong>Senha</strong>
                        </label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="password" placeholder="Digite a Senha"/>
                        </div>
                    </div>
                    <div class="form-group mb-4">
                        <label class="control-label" for="dns">
                            <strong>DNS do Servidor</strong></label>
                        <div class="input-group">
                            <select class="form-control" name="dns" id="discription">
                                <?php echo getDnsOptions(); ?>
                            </select>
                        </div>
                    </div>
                </div>
              <!-- <div class="form-group mb-4">
                    <label class="control-label" for="epg_url">
                        <strong>EPG Url</strong></label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="epg_url" placeholder="Digite o EPG do Servidor" id="epg_url"/>
                    </div>
                </div> -->

                <div class="form-group mb-4">
                    <label class="control-label" for="expire_date">
                        <strong>Vencimento do MAC</strong></label>
                    <div class="input-group">
                        <input type="date" class="form-control" name="expire_date" value="<?php echo date('Y-m-d', strtotime($vence));?>" placeholder="YYYY-MM-DD" id="datetimepicker" <?php if (!$isAdmin) echo 'readonly'; ?> autocomplete="off"/>
                    </div>
                </div>

                <button type="submit" name="submit" class="btn btn-primary mr-2"><i class='bx bx-check mr-1'></i>Adicionar</button>
            </form>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//hide activecode form
      $('.actived').show(); 
      $('.activeu').hide(); 

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

<script type="text/javascript">
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>
<?php include './includes/footer.php';?>
