<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

$dircheck = substr($_SERVER["REQUEST_URI"], 0, strrpos($_SERVER["REQUEST_URI"], "/"));
$dircheck2 = substr($dircheck, 1);
$postu = $_POST["username"] . $dircheck2;

if (isset($_SESSION[$dircheck2]) && $_SESSION[$dircheck2] == $dircheck2) {
    header("location: dashboard.php");
    exit;
}

function getRealIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

try {
    $db = new SQLite3("./api/db/studiolivecode_users.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$db->exec("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name VARCHAR(100), username VARCHAR(100), password VARCHAR(100), logo VARCHAR(100), nivel VARCHAR(100), admin VARCHAR(100), store_type VARCHAR(100), mac_amount VARCHAR(100))");

$rows = $db->querySingle("SELECT COUNT(*) as count FROM users");
if ($rows == 0) {
    $db->exec("INSERT INTO users(name, username, password, logo, nivel, admin, store_type, mac_amount) 
        VALUES('Admin', 'admin', 'admin', 'img/logo.png', '0', '1', NULL, NULL)");
    $db->exec("INSERT INTO users(name, username, password, logo, nivel, admin, store_type, mac_amount) 
        VALUES('StudioLiveCode', 'crocko', '10203040', 'img/logo.png', '1', '1', NULL, NULL)");
}

$ip = getRealIP();
$details = @file_get_contents("https://ipinfo.io/$ip/json");
if ($details === false) {
    $country = "Unknown";
    $state = "Unknown";
    $isp = "Unknown";
} else {
    $details = json_decode($details);
    $country = $details->country ?? "Unknown";
    $state = $details->region ?? "Unknown";
    $isp = preg_replace("/AS\\d{1,}\\s/", "", $details->org ?? "Unknown");
}

$date = date("d/m/Y H:i:s");
$IPADDRESS = $ip;

try {
    $dbs = new SQLite3("./api/db/studiolivecode_snoop.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$dbs->exec("CREATE TABLE IF NOT EXISTS logs(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date TEXT, access TEXT, state TEXT, country TEXT, isp TEXT, ipaddress TEXT)");

$showExpiredModal = false;
$vencimentoDisplay = '';

if (isset($_POST["login"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];

    $stmt = $db->prepare("SELECT id, password, admin, username FROM users WHERE username = :username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();

    $row = $result->fetchArray(SQLITE3_ASSOC);
    if ($row) {
        $id_check = $row["id"];
        $isAdmin = $row['admin'];
        $username_check = $row['username'];

        if ($password === $row["password"]) {
            
            try {
                $dbv = new SQLite3("./api/db/studiolivecode_vencimento.db");
                $stmtVencimento = $dbv->prepare("SELECT vencimento FROM vencimento WHERE id = :id");
                $stmtVencimento->bindValue(':id', $id_check, SQLITE3_INTEGER);
                $resultVencimento = $stmtVencimento->execute();
                $vencimentoData = $resultVencimento->fetchArray(SQLITE3_ASSOC);
                $dbv->close();
            } catch (Exception $e) {
                die('Erro ao acessar vencimentos: ' . $e->getMessage());
            }

            if ($vencimentoData) {
                $vencimento = $vencimentoData['vencimento'];
                $dataAtual = date('Y-m-d');
                
                if (strtotime($dataAtual) > strtotime($vencimento)) {
                    $message = "<div class='alert alert-danger' id='flash-msg'>
                                <h4><i class='icon fa fa-times'></i>Acesso Vencido!</h4>
                                </div>";
                    $showExpiredModal = true;
                    $vencimentoDisplay = date('d/m/Y', strtotime($vencimento));
                    
                    $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
                        VALUES(:date, 'Acesso Vencido', :state, :country, :isp, :IPADDRESS)");
                    $stmt->bindValue(':date', $date, SQLITE3_TEXT);
                    $stmt->bindValue(':state', $state, SQLITE3_TEXT);
                    $stmt->bindValue(':country', $country, SQLITE3_TEXT);
                    $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
                    $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
                    $stmt->execute();
                } else {
                    $_SESSION["studiolivecodevu"] = true;
                    $_SESSION["id"] = $id_check;
                    $_SESSION[$postu] = $postu;
                    $_SESSION[$dircheck2] = $dircheck2;
                    $_SESSION["U"] = $username_check;

                    $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
                    VALUES(:date, 'Login Bem-sucedido', :state, :country, :isp, :IPADDRESS)");
                    $stmt->bindValue(':date', $date, SQLITE3_TEXT);
                    $stmt->bindValue(':state', $state, SQLITE3_TEXT);
                    $stmt->bindValue(':country', $country, SQLITE3_TEXT);
                    $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
                    $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
                    $stmt->execute();
                    header("Location: dashboard.php");
                    exit();
                }
            } else {
                $_SESSION["studiolivecodevu"] = true;
                $_SESSION["id"] = $id_check;
                $_SESSION[$postu] = $postu;
                $_SESSION[$dircheck2] = $dircheck2;
                $_SESSION["U"] = $username_check;

                $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
                VALUES(:date, 'Login Bem-sucedido', :state, :country, :isp, :IPADDRESS)");
                $stmt->bindValue(':date', $date, SQLITE3_TEXT);
                $stmt->bindValue(':state', $state, SQLITE3_TEXT);
                $stmt->bindValue(':country', $country, SQLITE3_TEXT);
                $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
                $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
                $stmt->execute();
                header("Location: dashboard.php");
                exit();
            }
        } else {
            $message = "<div class=\"alert alert-danger\" id=\"flash-msg\"><h4><i class=\"icon fa fa-times\"></i>Senha Errada!</h4></div>";
            $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
                VALUES(:date, 'Senha Inválida', :state, :country, :isp, :IPADDRESS)");
            $stmt->bindValue(':date', $date, SQLITE3_TEXT);
            $stmt->bindValue(':state', $state, SQLITE3_TEXT);
            $stmt->bindValue(':country', $country, SQLITE3_TEXT);
            $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
            $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
            $stmt->execute();
            echo $message;
        }
    } else {
        $message = "<div class=\"alert alert-danger\" id=\"flash-msg\"><h4><i class=\"icon fa fa-times\"></i>Não é um Usuário Válido!</h4></div>";
        $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
            VALUES(:date, 'Usuário Inválido', :state, :country, :isp, :IPADDRESS)");
        $stmt->bindValue(':date', $date, SQLITE3_TEXT);
        $stmt->bindValue(':state', $state, SQLITE3_TEXT);
        $stmt->bindValue(':country', $country, SQLITE3_TEXT);
        $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
        $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
        $stmt->execute();
        echo $message;
    }

    $db->close();
    $dbs->close();
}

try {
    $dbc = new SQLite3("./api/db/studiolivecode_bot.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$dbc->exec("CREATE TABLE IF NOT EXISTS bot(id INTEGER PRIMARY KEY  AUTOINCREMENT, bot_url TEXT, bot_dns TEXT, bot_status TEXT, bot_name TEXT)");
$res = $dbc->query("SELECT COUNT(*) as count FROM bot");
if ($res) { // Verifica se a consulta foi bem-sucedida
    $rowc = $res->fetchArray();
    $numRowsc = $rowc["count"];
} else {
    // Tratar o caso em que a consulta falhou
    echo "Erro ao realizar a consulta ao banco de dados bot.";
}
if ($numRowsc == 0) {
    $dbc->exec("INSERT INTO bot(id, bot_url, bot_dns, bot_status, bot_name) VALUES('1', '', '', '0', 'Ibo Youcine Revenda')");
}

try {
    $db3 = new SQLite3("./api/db/studiolivecode_imagens.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$db3->exec('CREATE TABLE IF NOT EXISTS bg(id INT PRIMARY KEY NOT NULL, path TEXT)');
$rows = $db3->query('SELECT COUNT(*) as count FROM bg');
$numRows = $rows->fetchArray(SQLITE3_ASSOC);
if ($numRows['count'] == 0) {
    $queries = [
        "INSERT INTO bg(id, path) VALUES('1', '')"
    ];

    foreach ($queries as $query) {
        $db3->exec($query);
    }
}

$db3->exec("CREATE TABLE IF NOT EXISTS logo(id INT PRIMARY KEY NOT NULL, path TEXT)");
$rows = $db3->query('SELECT COUNT(*) as count FROM logo');
$numRows = $rows->fetchArray(SQLITE3_ASSOC);
if ($numRows['count'] == 0) {
    $queries = [
        "INSERT INTO logo(id, path) VALUES('1', '')"
    ];

    foreach ($queries as $query) {
        $db3->exec($query);
    }
}

$resk = $db3->query("SELECT * FROM logo WHERE id='1'");
$rowk = $resk->fetchArray();
$logo = $rowk["path"];
$db3->close();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <title>Ibo Full Revenda</title>
    <meta content="./assets/images/logo.png" property="og:image"/>
    <style>
        body {
            background-color: #181828;
            background-image: url("./assets/images/default_background.jpg");
            color: #fff;
        }

        #particles-js {
            background-size: cover;
            background-position: 50% 50%;
            background-repeat: no-repeat;
            background: #8000FF;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .particles-js-canvas-el {
            position: fixed;
        }

        .login-form {
            background-color: rgba(0, 0, 0, 0.7); /* Cor de fundo com transparência */
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0px 0px 20px rgba(255, 255, 255, 0.2);
            border-top: 5px solid #0A38D1;
        }

        .login-form img {
            width: 75%;
            margin: 0 auto;
            display: block;
            margin-bottom: 20px;
        }

        .login-form input[type="text"],
        .login-form input[type="password"] {
            background-color: #333;
            color: #fff;
        }

        .login-form input[type="submit"] {
            background-color: #0A38D1;
            border: none;
        }

        .login-form input[type="submit"]:hover {
            background-color: #0529a3;
        }
        

    /* Estilo do Modal */
    .modal-content {
        border-radius: 12px;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
        animation: fadeIn 0.6s ease;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .modal-header.bg-danger {
        background: linear-gradient(45deg, #ff4e50, #f44336);
        color: white;
        border-top-left-radius: 12px;
        border-top-right-radius: 12px;
    }

    .modal-body p {
        color: #333;
    }

    .whatsapp-btn {
        background-color: #25D366;
        color: white;
        border: none;
        padding: 12px 20px;
        font-size: 16px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(37, 211, 102, 0.5);
        transition: 0.3s;
        display: inline-flex;
        align-items: center;
        text-decoration: none;
    }

    .whatsapp-btn i {
        margin-right: 8px;
    }

    .whatsapp-btn:hover {
        background-color: #1ebe5d;
        box-shadow: 0 6px 16px rgba(37, 211, 102, 0.7);
        text-decoration: none;
        color: white;
    }

    .modal-body {
        text-align: center;
        font-family: Arial, sans-serif;
    }

    .vencimento-data {
        color: red;
        font-weight: bold;
        font-size: 18px;
    }

        
        
    </style>
</head>
<body>
<div id="js-particles"></div>
<br><br>
<div class="container">
    <div class="row">
        <div class="col-lg-4 mx-md-auto">
            <form method="post" class="login-form">
                <img src="<?php
                if (empty($rowk['path'])) {
                    echo 'assets/images/logo1.png';
                } else {
                    echo $rowk['path'];
                } ?>" alt="">
                
                <div class="form-group">
                    <input type="text" class="form-control form-control-lg"
                           placeholder="Usuário" name="username" required autofocus>
                </div>
                <div class="form-group">
                    <input type="password" class="form-control form-control-lg"
                           placeholder="Senha" name="password" required>
                </div>
                <input type="submit" class="btn btn-primary btn-lg btn-block" value="Entrar" name="login">
                <center style="margin-top: 20px;"><a class="list-grup-item" href="https://flix-play.com/apks" target="_blank">&nbsp&nbsp&nbsp&nbsp&#169  <?php echo date("Y")?> + Scripts Apks </a></center>
            </form>
            
        </div>
    </div>
</div>
<br><br>

<div class="modal fade" id="expiredModal" tabindex="-1" role="dialog" aria-labelledby="expiredModalLabel">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="expiredModalLabel">
                    Painel Vencido!
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close" style="opacity: 1;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p style="font-size: 17px; margin-bottom: 10px;">
                    Seu acesso venceu em <span class="vencimento-data"><?= $vencimentoDisplay ?></span>!
                </p>
                <p style="font-size: 16px; margin-bottom: 20px;">
                    Renove AGORA seu painel FlixPlay no botão abaixo!
                </p>
                <a href="https://api.whatsapp.com/send?phone=5511920075387&text=Ol%C3%A1%2C%20quero%20Renovar%20meu%20painel%20FlixPlay!" target="_blank" class="whatsapp-btn">
                    <i class="fa fa-whatsapp"></i> Renovar Painel!
                </a>
            </div>
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
<!--<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>-->
<!--<script src="assets/js/particles.js"></script>-->
<?php if($showExpiredModal): ?>
<script>
$(document).ready(function(){
    $('#expiredModal').modal('show');
});
</script>
<?php endif; ?>
</body>
</html>