<?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,\r\nmac_address VARCHAR(100),\r\nkey VARCHAR(100),\r\nusername VARCHAR(100),\r\npassword VARCHAR(100),\r\nexpire_date VARCHAR(100),\r\ndns VARCHAR(100),\r\nepg_url VARCHAR(100),\r\ntitle VARCHAR(100),\r\nurl VARCHAR(100),\r\ntype VARCHAR(100))");
$res = $db->query("SELECT * FROM ibo");

if (isset($_POST["submit"])) {

    $we = strtotime($_POST["expire_date"]);
    $ne = date("Y-m-d", $we);
    
    if($storeType == 2){
        $ne = date('Y-m-d', 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 ($storeType == 5) {
        $dbUsers = new SQLite3("./api/.anspanel.db");
        $numRows = $dbUsers->querySingle("SELECT COUNT(*) FROM USERS WHERE USERNAME = '". $_POST['login'] ."' OR NAME = '". $_POST['firstname'] ."' ");

        if ($numRows <= 0) {
                $logoPath = "logotipo_painel/logo.png";
                $query = "INSERT INTO users (NAME, USERNAME, PASSWORD, LOGO, store_type, mac_amount, ADMIN, expire_date, email, price_to_mp) 
          VALUES ('{$_POST['firstname']}', '{$_POST['login']}', '{$_POST['password']}', '$logoPath', '0', '{$_POST['qtd_macs']}', '1', '{$_POST['expire_date']}', '{$_POST['email']}', '{$_POST['price_to_mp']}')";


                $result = $dbUsers->exec($query);

            if (!$result) {
                echo "Erro ao executar o comando SQL: " . $dbUsers->lastErrorMsg();
                echo "<pre>";
                print_r($_POST);
                die;
            }

            header("Location: users.php");
        } else {
            $_SESSION['error_session'] = "Usuário já foi cadastrado";
            header("Location: users.php");
        }
        $dbUsers->close();

    }else {
//        if (!$isAdmin) {

            $dbUsers = new SQLite3("./api/.anspanel.db");
            $res = $dbUsers->query("SELECT u.mac_amount, (SELECT SUM(mac_amount) FROM USERS WHERE user_id=u.id) as amountSum FROM USERS u WHERE u.id = '$id' ");
            $fetch = $res->fetchArray();
            $macCount = $fetch['mac_amount'];
            
            if($macCount != "9999999999"){
    
                $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']+$fetch['amountSum'];
    
                if ($count >= $macCount) {
                    $limited = true;
                }
            }
//        }
        if (!$limited) {
            $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'] = [];
            }

            $macRes = $db->query("SELECT * FROM ibo WHERE mac_address = '$address1'");
            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($isAdmin == 1){
    if (strtotime(date("Y-m-d", strtotime($expire_date))) <= strtotime(date("Y-m-d"))) {
        echo "<div class='alert alert-danger'><strong>Função bloqueada!</strong> Regularize a sua assinatura para voltar a cadastrar novas revendas</div>";
        die;
    }
}
if($storeType == 1){
    if (strtotime(date("Y-m-d", strtotime($revenda_date_expire))) <= strtotime(date("Y-m-d"))) {
        echo "<div class='alert alert-danger'><strong>Função bloqueada!</strong> Entre em contato com seu revendedor</div>";
        die;
    }
}

if($limited){
    echo "<div class='alert alert-danger'>MACs limit exceeded!</div>";
} else {
    $dbUsers = new SQLite3("./api/.anspanel.db");
    $res = $dbUsers->query("SELECT u.mac_amount, (SELECT SUM(mac_amount) FROM USERS WHERE user_id=u.id) as amountSum  FROM USERS u WHERE u.id = '$id' ");
    $fetch = $res->fetchArray();
    $macCount = $fetch['mac_amount'];
    $dbUsers->close();
    
    if($macCount != "9999999999"){
        $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'];
        
        $availableMacs = $macCount - ($count + $fetch['amountSum']);
        
        
        if($storeType != 5) {
            echo "<div class='alert alert-success'>MAC disponíveis: $availableMacs</div>";
        }
    }else{
                $availableMacs = 9999999999;
                 
        if($storeType != 5) {
            echo "<div class='alert alert-success'>MAC disponíveis: Ilimitado</div>";
        }
    }
    
}

if($storeType == 5){
    $title = "Criação de Usuario Master";
}else{
    $title = "Activate User";
}


echo "        <div class=\"container-fluid\">\n\n          <!-- Page Heading -->\n          <h1 class=\"h3 mb-1 text-gray-800\"> $title </h1>\n\n              <!-- Custom Codes -->\n                <div class=\"card border-left-primary shadow h-100 card shadow mb-4\">\n                <div class=\"card-header py-3\">\n                <h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-user\"></i> User Details</h6>\n                </div>\n     
                   
                   <div class=\"card-body\">\n                        <form method=\"post\">          \n                    \n                                   \n           
                                            
                                   ";
    if($storeType != '5') {
        echo "      <div class=\"form-group \">   <label class=\"control-label \" for=\"mac_address\">\n                                        <strong>Device MAC</strong> \n                                    </label>
    <div class=\"input-group\">\n                                        <input class=\"form-control mac_address text-primary\" id=\"description\" name=\"mac_address\" placeholder=\"Enter Device ID: 00:11:22:33:44:55\" type=\"text\" maxlength=\"17\" required/>\n                                    </div>\n                                </div>\n                        <input type=\"hidden\" name=\"key\" value=\"136115\">\n	  \r\n\r\n";

    if(!$dnsFixoUser) {
        echo "<div class=\"form-group\">\n                                    \r\n<div>\n                            <strong> Select Login Mode: </strong> \r\n                                    <select class=\"select form-control type\" id=\"type\" name=\"type\" >\r\n\t\t\t\t\t\t\t\t\t    \r\n                                        <option value=\"0\" data-value=\"op0\">Use Xtream Codes\r\n</option>\r\n<option value=\"1\" data-value=\"op1\">Use M3U8 List\r\n</option>\r\n                          </select>\r\n</div>\n\n  \r\n\r\n        \r\n\r\n</div>\n    \r\n    ";
        $onlyRead = "";
    }else{
        $onlyRead = " readonly='true' ";
        echo '<input type="hidden" name="type" value="0" />';
    }

    echo "                            <div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"title\">\n                                        <strong>Server Name</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"title\" placeholder=\"Enter Server Name\" id=\"title\" required/>\n                                    </div>\n                                </div>\n                <div class=\"active1\">\n                                <div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"username\">\n                                        <strong>Username</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"username\" placeholder=\"Enter Username\" id=\"discription\"/>\n                                    </div>\n                                </div>\n                                <div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"password\">\n                                        <strong>Password</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"password\" placeholder=\"Enter Password\" />\n                                    </div>\n                                </div>\n

                                 <div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"dns\">\n                                        <strong>DNS</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" $onlyRead class=\"form-control text-primary\" name=\"dns\" placeholder=\"Enter DNS Server\"  id=\"discription\" value=\"$dnsFixoUser\" />\n                                    </div>\n                                </div>\n                         </div>\n                     <div class=\"active2\">\n                                 <div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"dns\">\n                                        <strong>M3U List</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"url\" placeholder=\"Enter M3U List URL\" id=\"discription\" />\n                                    </div>\n                                </div>\n                       </div>\n                                 <div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"epg_url\">\n                                        <strong>EPG URL</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"epg_url\" placeholder=\"Enter EPG Guide\" id=\"epg_url\"/>\n                                    </div>\n                                </div>";
    }else{
        echo '
            <div class="form-group">
               <label class="control-label" for="isIlimite"><strong>Conta Ilimitada?</strong></label>
                  <div class="input-group">
                    <select class="form-control" id="IsIlimite">
                        <option value="0">Não</option>
                        <option value="1">Sim</option>
                    </select>
                  </div>   
            </div>
            <div class="form-group" id="quantidadeMacs">
               <label class="control-label" for="limit_macs"><strong>Quantidade de Macs disponiveis</strong></label>
                  <div class="input-group">
                    <input class="form-control" type="number" name="qtd_macs" value="50">
                  </div>   
            </div>
            <div class="form-group">
               <label class="control-label" for="login"><strong>Login</strong></label>
                  <div class="input-group">
                    <input class="form-control" type="text" id="login" name="login" value="">
                  </div>   
            </div>
            <div class="form-group">
               <label class="control-label" for="email"><strong>Email</strong></label>
                  <div class="input-group">
                    <input class="form-control" type="text" id="email" name="email" value="">
                  </div>   
            </div>
            <div class="form-group">
               <label class="control-label" for="price_to_mp"><strong>Valor</strong></label>
                  <div class="input-group">
                    <input class="form-control" step="0.01" type="number" id="price_to_mp" name="price_to_mp" value="">
                  </div>   
            </div>
            <div class="form-group">
               <label class="control-label" for="password"><strong>Senha</strong></label>
                  <div class="input-group">
                    <input class="form-control" type="text" id="password" name="password">
                  </div>   
            </div>
            <div class="form-group">
               <label class="control-label" for="firstname"><strong>Nome do Master</strong></label>
                  <div class="input-group">
                    <input class="form-control" type="text" id="firstname" name="firstname">
                  </div>   
            </div>
        ';
    }
                                    echo "<div class=\"form-group \">\n                                    <label class=\"control-label \" for=\"expire_date\">\n                                        <strong>Expiration Date</strong>\n                                    </label>\n                                    <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"expire_date\" value='2050-01-01' placeholder=\"YYYY-MM-DD\" id=\"datetimepicker\" autocomplete=\"off\"/> \n                                    </div>\n\n                                </div>\n";
                                if ($storeType == '2') {
                                    echo "<div class=\"form-group \">
                                                <label class=\"control-label \" for=\"playlistpassword\"><strong>Playlist Password (Optional)</strong></label>
                                            <div class=\"input-group\">\n                                        <input type=\"text\" class=\"form-control text-primary\" name=\"playlistpassword\" placeholder=\"Enter Playlist Password\" id=\"playlistpassword\"/>
                                        </div>
                                    </div>";
                                }

                                echo "<button class=\"btn btn-success btn-icon-split\" name=\"submit\" type=\"submit\">\n                        <span class=\"icon text-white-50\"><i class=\"fas fa-check\"></i></span><span class=\"text\">Submit</span>\n                        </button>\n                                    </div>\n\n                                </div>\n                            </form>\n                    </div>\n                </div>\n                </div>\n    <br><br><br>\n";
include "includes/footer.php";
echo "\r\n<script>\r\n//select activecode form\r\n//var response = {};\r\n//response.val = \"op2\";\r\n//\$(\"#codemode option[data-value='\" + response.val +\"']\").attr(\"selected\",\"selected\");\r\n\r\n//hide activecode form\r\n\$('.active1').show(); \r\n\$('.active2').hide(); \r\n\r\n//Show/hide activecode select\r\n\$(document).ready(function(){\r\n  \$('.type').change(function(){\r\n    if(\$('.type').val() < 1) {\r\n      \$('.active1').show(); \r\n      \$('.active2').hide(); \r\n    } else {\r\n      \$('.active2').show(); \r\n      \$('.active1').hide(); \r\n    } \r\n  });\r\n});\r\n</script>\r\n\r\n\n    <script>\n\$('#confirm-delete').on('show.bs.modal', function(e) {\n    \$(this).find('.btn-ok').attr('href', \$(e.relatedTarget).data('href'));\n});\n\r\n\r\n    </script>\r\n    <script type=\"text/javascript\">\r\n// @require http://code.jquery.com/jquery-latest.js\r\n// ==/UserScript==\r\ndocument.getElementById(\"description\").addEventListener('keyup', function() { \r\n  var mac = document.getElementById('description').value;\r\n  var macs = mac.split(':').join('');\r\n  macs = chunk(macs, 2).join(':');\r\n  document.getElementById('description').value = macs.toString();\r\n});\r\n\r\nfunction chunk(str, n) {\r\n    var ret = [];\r\n    var i;\r\n    var len;\r\n\r\n    for(i = 0, len = str.length; i < len; i += n) {\r\n       ret.push(str.substr(i, n))\r\n    }\r\n\r\n    return ret\r\n};\r\n    </script>\n</body>\n\n</html>";

?>
<script>
    $('#IsIlimite').change(function(){
        let isLimit = $(this).val();
        if(isLimit == 1){
            $('input[name="qtd_macs"]').val("9999999999");
            $('#quantidadeMacs').hide();
        }else{
            $('input[name="qtd_macs"]').val("50");
            $('#quantidadeMacs').show();
        }
    });
</script>