<?php
declare(strict_types=1);

session_start();
date_default_timezone_set('America/Sao_Paulo');

if (isset($_SESSION["panel_user"])) {
    header("Location: dashboard.php");
    exit;
}

function getRealIP(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    return $_SERVER['REMOTE_ADDR'] ?? "0.0.0.0";
}

function csrf_token(){
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function csrf_check($token){
    return isset($_SESSION['csrf_token']) && is_string($token) && hash_equals($_SESSION['csrf_token'], $token);
}


function safeText($s){
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function checkPasswordCompat(string $senhaInformada, string $senhaBanco): bool
{
    $senhaBanco = (string)$senhaBanco;

    if ($senhaBanco === "") return false;

    $info = password_get_info($senhaBanco);

    if (!empty($info["algo"]) && (int)$info["algo"] !== 0) {
        return password_verify($senhaInformada, $senhaBanco);
    }

    if (strlen($senhaBanco) === 32 && ctype_xdigit($senhaBanco)) {
        return hash_equals(strtolower($senhaBanco), md5($senhaInformada));
    }

    return hash_equals($senhaBanco, $senhaInformada);
}

function sqliteExecRetry(PDO $db, string $sql, array $params = [], int $tries = 6, int $sleepMs = 150): bool
{
    for ($i = 0; $i < $tries; $i++) {
        try {
            $st = $db->prepare($sql);
            return $st->execute($params);
        } catch (PDOException $e) {
            $msg = strtolower($e->getMessage());
            if (str_contains($msg, "database is locked") || str_contains($msg, "locked")) {
                usleep($sleepMs * 1000);
                continue;
            }
            throw $e;
        }
    }
    return false;
}

$db = new PDO("sqlite:" . dirname(__DIR__) . "/api/db.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_TIMEOUT, 5);

$db->exec("PRAGMA busy_timeout = 8000");
$db->exec("PRAGMA journal_mode = WAL");
$db->exec("PRAGMA synchronous = NORMAL");

$panelIdentityPath = dirname(__DIR__) . "/api/panel_identity.json";
$panelName = "THEFULL TV";

if (is_file($panelIdentityPath)) {
    $panelIdentityRaw = @file_get_contents($panelIdentityPath);
    $panelIdentity = json_decode((string)$panelIdentityRaw, true);
    if (is_array($panelIdentity) && isset($panelIdentity["name"])) {
        $candidateName = trim((string)$panelIdentity["name"]);
        if ($candidateName !== "") {
            $panelName = $candidateName;
        }
    }
}

$panelLogoFile = dirname(__DIR__) . "/api/img/logo.png";
$panelLogoVersion = is_file($panelLogoFile) ? (string)filemtime($panelLogoFile) : (string)time();

$error = "";
$success = "";
$recoverMode = isset($_GET["recuperar"]) || isset($_POST["recover_access"]);


if (isset($_POST["recover_access"])) {
    $csrf = (string)($_POST["csrf_token"] ?? "");
    $newUser = trim((string)($_POST["new_username"] ?? ""));
    $newPass = trim((string)($_POST["new_password"] ?? ""));
    $newPass2 = trim((string)($_POST["new_password_confirm"] ?? ""));

    if (!csrf_check($csrf)) {
        $error = "Falha de segurança (CSRF). Recarregue a página.";
    } elseif ($newUser === "" || $newPass === "" || $newPass2 === "") {
        $error = "Preencha o novo usuário e a nova senha.";
    } elseif (strlen($newUser) < 3) {
        $error = "O novo usuário precisa ter pelo menos 3 caracteres.";
    } elseif (strlen($newPass) < 4) {
        $error = "A nova senha precisa ter pelo menos 4 caracteres.";
    } elseif ($newPass !== $newPass2) {
        $error = "As senhas não conferem.";
    } else {
        try {
            $newHash = password_hash($newPass, PASSWORD_DEFAULT);

            $stmtRecover = $db->query("SELECT id FROM panel_users ORDER BY id ASC LIMIT 1");
            $adminRecover = $stmtRecover ? $stmtRecover->fetch() : false;

            if ($adminRecover && isset($adminRecover["id"])) {
                sqliteExecRetry(
                    $db,
                    "UPDATE panel_users SET username=?, password=? WHERE id=?",
                    [$newUser, $newHash, (int)$adminRecover["id"]],
                    6,
                    160
                );
            } else {
                sqliteExecRetry(
                    $db,
                    "INSERT INTO panel_users(username,password) VALUES(?,?)",
                    [$newUser, $newHash],
                    6,
                    160
                );
            }

            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            $success = "Acesso recuperado com sucesso. Entre com o novo usuário e a nova senha.";
            $recoverMode = false;
        } catch (Throwable $e) {
            $error = "Não foi possível recuperar o acesso. Verifique o banco de dados.";
            $recoverMode = true;
        }
    }
}

if (isset($_POST["login"])) {
    $u = trim((string)($_POST["username"] ?? ""));
    $p = trim((string)($_POST["password"] ?? ""));
    $csrf = (string)($_POST["csrf_token"] ?? "");

    if (!csrf_check($csrf)) {
            $error = "Falha de segurança (CSRF). Recarregue a página.";
        } else {
            if ($u === "" || $p === "") {
                $error = "Preencha usuário e senha";
            } else {

                $user = null;
                $tipo = "";

                $stmt = $db->prepare("SELECT id, username, password FROM panel_users WHERE username=? LIMIT 1");
                $stmt->execute([$u]);
                $panelUser = $stmt->fetch();

                if ($panelUser) {
                    $senhaBanco = (string)($panelUser["password"] ?? "");
                    if (checkPasswordCompat($p, $senhaBanco)) {
                        $user = $panelUser;
                        $tipo = "admin";

                        if (password_get_info($senhaBanco)["algo"] === 0) {
                            try {
                                $newHash = password_hash($p, PASSWORD_DEFAULT);
                                $db->beginTransaction();
                                $db->exec("BEGIN IMMEDIATE");
                                sqliteExecRetry($db, "UPDATE panel_users SET password=? WHERE id=?", [$newHash, (int)$panelUser["id"]], 6, 160);
                                $db->commit();
                            } catch (Throwable $e) {
                                if ($db->inTransaction()) $db->rollBack();
                            }
                        }
                    }
                }

                if (!$user) {
                    $stmt2 = $db->prepare("SELECT id, username, password, status FROM revendedores WHERE username=? AND (status IS NULL OR status='' OR status='ativo') LIMIT 1");
                    $stmt2->execute([$u]);
                    $revUser = $stmt2->fetch();

                    if ($revUser) {
                        $senhaBanco = (string)($revUser["password"] ?? "");
                        if (checkPasswordCompat($p, $senhaBanco)) {
                            $user = $revUser;
                            $tipo = "revendedor";

                            if (password_get_info($senhaBanco)["algo"] === 0) {
                                try {
                                    $newHash = password_hash($p, PASSWORD_DEFAULT);
                                    $db->beginTransaction();
                                    $db->exec("BEGIN IMMEDIATE");
                                    sqliteExecRetry($db, "UPDATE revendedores SET password=? WHERE id=?", [$newHash, (int)$revUser["id"]], 6, 160);
                                    $db->commit();
                                } catch (Throwable $e) {
                                    if ($db->inTransaction()) $db->rollBack();
                                }
                            }
                        }
                    }
                }

                $ip = getRealIP();

                $country = "Unknown";
                $state   = "Unknown";
                $isp     = "Unknown";

                $ctx = stream_context_create([
                    "http" => [
                        "timeout" => 2,
                        "ignore_errors" => true,
                        "header" => "User-Agent: THEFULLTV-PANEL\r\n"
                    ],
                    "ssl" => [
                        "verify_peer" => true,
                        "verify_peer_name" => true
                    ]
                ]);

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

                if ($user) {
                    session_regenerate_id(true);

                    $_SESSION["panel_user"] = $user["username"];
                    $_SESSION["tipo_user"]  = $tipo;

                    if ($tipo === "admin") {
                        $_SESSION["panel_id"] = $user["id"];
                    } else {
                        $_SESSION["revendedor_id"] = $user["id"];
                    }

                    if ($tipo === "revendedor") {
                        header("Location: revenda_clientes.php");
                        exit;
                    }

                    header("Location: dashboard.php");
                    exit;

                } else {
                    $error = "Usuário ou senha inválidos";
                    try {
                        sqliteExecRetry($db, "INSERT INTO panel_logs(date,access,ip,country,state,isp) VALUES(?,?,?,?,?,?)", [date("d/m/Y H:i:s"), "Login inválido", $ip, $country, $state, $isp], 6, 150);
                    } catch (Throwable $e) {}
                }
            }
        }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title><?= safeText($panelName) ?></title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#050607;
  --panel: rgba(148,163,184,.10);
  --panel2: rgba(203,213,225,.14);
  --stroke: rgba(203,213,225,.20);
  --stroke2: rgba(226,232,240,.32);
  --shadow: 0 24px 80px rgba(0,0,0,.62);
  --shadow2: 0 18px 60px rgba(15,23,42,.52);

  --white:#e5e7eb;
  --white2:#cbd5e1;

  --text:#f8fafc;
  --muted: rgba(226,232,240,.78);
  --muted2: rgba(203,213,225,.58);
  --radius: 20px;
  --ease: cubic-bezier(.2,.9,.2,1);
  --speed: .22s;
}

*{ box-sizing:border-box; }
html,body{
  margin:0;
  padding:0;
  width:100%;
  height:100%;
  min-height:100%;
  overflow-x:hidden;
  font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,Helvetica,sans-serif;
  background: var(--bg);
  color: var(--text);
}

body{
  min-height:100vh;
  min-height:100dvh;
  display:flex;
  align-items:center;
  justify-content:center;
  padding: 18px;
  overflow:auto;

  background:
    radial-gradient(1200px 760px at 78% 28%, rgba(148,163,184,.18), transparent 60%),
    radial-gradient(900px 620px at 20% 18%, rgba(100,116,139,.16), transparent 62%),
    radial-gradient(900px 520px at 88% 82%, rgba(226,232,240,.08), transparent 58%),
    linear-gradient(180deg, rgba(3,7,18,.74), rgba(0,0,0,.96));
}

.bgPoster{
  position:fixed;
  inset:0;
  z-index:0;
  pointer-events:none;
  background-image:
    url("api/img/fundo_login.jpg"),
    radial-gradient(1200px 760px at 78% 28%, rgba(148,163,184,.18), transparent 60%),
    radial-gradient(900px 620px at 20% 18%, rgba(100,116,139,.16), transparent 62%),
    radial-gradient(900px 520px at 88% 82%, rgba(226,232,240,.08), transparent 58%),
    linear-gradient(180deg, rgba(3,7,18,.74), rgba(0,0,0,.96));
  background-size: cover;
  background-position:center;
  background-repeat:no-repeat;
  filter: grayscale(.22) saturate(.82) contrast(1.08);
  opacity:.24;
}

.vignette{
  position:fixed;
  inset:0;
  z-index:1;
  pointer-events:none;
  background:
    radial-gradient(circle at 60% 30%, transparent 0%, rgba(15,23,42,.28) 40%, rgba(0,0,0,.84) 86%, rgba(0,0,0,.96) 100%);
  opacity:.95;
}

.noise{
  position:fixed;
  inset:0;
  z-index:2;
  pointer-events:none;
  background-image: radial-gradient(rgba(203,213,225,.08) 1px, transparent 1px);
  background-size: 3px 3px;
  opacity:.06;
  mix-blend-mode: overlay;
}

.login-box{
  width:100%;
  max-width: 360px;
  padding: 22px;
  border-radius: var(--radius);
  background:
    radial-gradient(circle at 18% 18%, rgba(226,232,240,.13), transparent 55%),
    linear-gradient(180deg, rgba(148,163,184,.18), rgba(15,23,42,.46));
  border: 1px solid rgba(203,213,225,.24);
  box-shadow: var(--shadow);
  position:relative;
  z-index:3;
  backdrop-filter: blur(18px);
}

.logo{
  display:flex;
  justify-content:center;
  align-items:center;
  gap: 12px;
  width:100%;
  margin-bottom: 6px;
}

.logoBox{
  width: 54px;
  height: 54px;
  border-radius: 18px;
  display:flex;
  align-items:center;
  justify-content:center;
  background:
    radial-gradient(circle at 30% 18%, rgba(248,250,252,.34), transparent 60%),
    linear-gradient(135deg, rgba(226,232,240,.92), rgba(71,85,105,.24));
  border: 1px solid rgba(226,232,240,.28);
  box-shadow: 0 20px 50px rgba(148,163,184,.16);
  overflow:hidden;
}

.logoBox img{
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.title{
  text-align:center;
  margin: 8px 0 8px 0;
  font-size: 19px;
  font-weight: 900;
  letter-spacing:.3px;
}

.subtitle{
  text-align:center;
  margin: 0 0 14px 0;
  font-size: 12px;
  color: rgba(226,232,240,.76);
}

.badge{
  margin: 0 auto 12px auto;
  width: fit-content;
  padding: 6px 11px;
  border-radius: 999px;
  border: 1px solid rgba(203,213,225,.22);
  background: rgba(15,23,42,.48);
  font-size: 12px;
  font-weight: 800;
  letter-spacing:.2px;
  color: rgba(248,250,252,.92);
  display:flex;
  align-items:center;
  gap: 10px;
}

.dot{
  width: 10px;
  height: 10px;
  border-radius: 999px;
  background: linear-gradient(135deg, #f8fafc, #94a3b8);
  box-shadow: 0 0 0 7px rgba(148,163,184,.18), 0 0 22px rgba(203,213,225,.35);
}

.form{
  margin-top: 6px;
}

input{
  width:100%;
  padding: 12px 13px;
  border-radius: 14px;
  border: 1px solid rgba(203,213,225,.18);
  margin-bottom: 10px;
  background: rgba(15,23,42,.62);
  color:white;
  font-size: 15px;
  outline:none;
  transition: box-shadow var(--speed) var(--ease), border-color var(--speed) var(--ease), transform var(--speed) var(--ease);
}

input::placeholder{
  color: rgba(203,213,225,.58);
}

input:focus{
  border-color: rgba(226,232,240,.78);
  box-shadow: 0 0 0 4px rgba(148,163,184,.24), 0 16px 40px rgba(0,0,0,.48);
  transform: translateY(-1px);
}

button{
  width:100%;
  padding: 12px;
  border:none;
  border-radius: 14px;
  background: linear-gradient(90deg, #f8fafc, #94a3b8 55%, #64748b);
  border: 1px solid rgba(226,232,240,.34);
  color:#050607;
  font-size: 16px;
  font-weight: 900;
  cursor:pointer;
  outline:none;
  transition: transform var(--speed) var(--ease),
              box-shadow var(--speed) var(--ease),
              border-color var(--speed) var(--ease),
              opacity var(--speed) var(--ease);
}

button:hover{ opacity:.95; }
button:active{ transform: scale(.992); }
button:focus{
  box-shadow: 0 0 0 4px rgba(148,163,184,.26), 0 20px 55px rgba(0,0,0,.58);
  border-color: rgba(226,232,240,.78);
}

.error{
  background: rgba(71,85,105,.28);
  border: 1px solid rgba(203,213,225,.36);
  padding: 10px 12px;
  border-radius: 14px;
  text-align:center;
  margin-bottom: 14px;
  font-weight: 800;
  color: #fff;
}


.success{
  background: rgba(100,116,139,.30);
  border: 1px solid rgba(226,232,240,.48);
  padding: 10px 12px;
  border-radius: 14px;
  text-align:center;
  margin-bottom: 14px;
  font-weight: 800;
  color: #fff;
}

.form-title{
  text-align:center;
  margin: 0 0 12px 0;
  font-size: 15px;
  font-weight: 900;
  color: rgba(248,250,252,.94);
}

.small-note{
  text-align:center;
  margin: 0 0 14px 0;
  font-size: 12px;
  line-height: 1.45;
  color: rgba(203,213,225,.70);
}

.recovery-area{
  margin-top: 12px;
  display:flex;
  flex-direction:column;
  gap: 10px;
}

.recovery-link{
  width:100%;
  display:flex;
  align-items:center;
  justify-content:center;
  text-decoration:none;
  padding: 11px 13px;
  border-radius: 14px;
  background: rgba(0,0,0,.30);
  border: 1px solid rgba(255,255,255,.14);
  color: rgba(248,250,252,.92);
  font-size: 14px;
  font-weight: 900;
  transition: transform var(--speed) var(--ease),
              box-shadow var(--speed) var(--ease),
              border-color var(--speed) var(--ease),
              background var(--speed) var(--ease);
}

.recovery-link:hover{
  background: rgba(100,116,139,.24);
  border-color: rgba(226,232,240,.34);
}

.recovery-link:active{
  transform: scale(.992);
}

.recovery-link:focus{
  outline:none;
  box-shadow: 0 0 0 4px rgba(148,163,184,.24), 0 18px 42px rgba(0,0,0,.48);
  border-color: rgba(226,232,240,.55);
}

.recovery-submit{
  margin-top: 2px;
}

.footer{
  text-align:center;
  margin-top: 14px;
  font-size: 12px;
  opacity:.72;
}

@media (max-width: 520px){
  body{
    padding: 14px;
    align-items:center;
  }
  .login-box{
    max-width: 340px;
    padding: 18px;
    border-radius: 18px;
    margin: 0 auto;
  }
  .logoBox{
    width: 50px;
    height: 50px;
    border-radius: 17px;
  }
  .title{ font-size: 18px; }
  .subtitle{ font-size: 12px; margin-bottom: 14px; }
  input, button, .recovery-link{
    min-height: 44px;
    font-size: 14px;
  }
}

@media (max-width: 360px){
  body{ padding: 10px; }
  .login-box{ max-width: 315px; padding: 15px; }
  .title{ font-size: 18px; }
  .badge{ font-size: 11px; }
}
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.save-btn{
    border-radius:14px;
    min-height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.info-box{
    background:rgba(0,0,0,.03);
    border:1px solid rgba(0,0,0,.08);
    border-radius:14px;
    padding:12px 14px;
    font-weight:700;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn{
        width:100%;
    }
}
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.textarea-radius{
    border-radius:14px !important;
}
.save-btn{
    border-radius:14px;
    height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.table-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
}
.table thead th{
    font-weight:900;
    white-space:nowrap;
}
.table td{
    vertical-align:middle;
}
.action-btn{
    border-radius:12px;
    font-weight:800;
    margin:2px 0;
}
.img-link{
    font-weight:900;
    text-decoration:none;
}
.status-on{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(25,135,84,.12);
    color:#198754;
    font-weight:900;
}
.status-off{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(220,53,69,.12);
    color:#dc3545;
    font-weight:900;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn{
        width:100%;
    }
}

/* SCROLLBAR CINZA - PC E MOBILE */
html{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

body{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

*::-webkit-scrollbar{
  width: 10px;
  height: 10px;
}

*::-webkit-scrollbar-track{
  background: #1f1f1f;
  border-radius: 999px;
}

*::-webkit-scrollbar-thumb{
  background: linear-gradient(180deg, #b8b8b8, #7c7c7c);
  border-radius: 999px;
  border: 2px solid #1f1f1f;
}

*::-webkit-scrollbar-thumb:hover{
  background: linear-gradient(180deg, #d0d0d0, #909090);
}

.table-responsive{
  scrollbar-width: thin;
  scrollbar-color: #8f8f8f #1f1f1f;
}

@media (max-width: 768px){
  *::-webkit-scrollbar{
    width: 7px;
    height: 7px;
  }
}
</style>

</head>

<body>
<div class="bgPoster"></div>
<div class="noise"></div>
<div class="vignette"></div>

<div class="login-box">
  <div class="logo">
    <div class="logoBox">
      <img src="api/img/logo.png?v=<?= safeText($panelLogoVersion) ?>" alt="<?= safeText($panelName) ?>">
    </div>
  </div>

  <div class="title">Painel <?= safeText($panelName) ?></div>
  <div class="subtitle">Acesso premium • protegido • rápido</div>

  <div class="badge"><span class="dot"></span> Login seguro</div>

  <?php if($error!=""){ ?>
  <div class="error"><?= safeText($error) ?></div>
  <?php } ?>

  <?php if($success!=""){ ?>
  <div class="success"><?= safeText($success) ?></div>
  <?php } ?>

  <?php if($recoverMode){ ?>
  <form method="post" class="form" autocomplete="off">
    <input type="hidden" name="csrf_token" value="<?= safeText(csrf_token()) ?>">
    <div class="form-title">Recuperar acesso</div>
    <div class="small-note">Crie um novo usuário e uma nova senha para acessar o painel.</div>
    <input type="text" name="new_username" placeholder="Novo usuário" required autofocus autocomplete="username">
    <input type="password" name="new_password" placeholder="Nova senha" required autocomplete="new-password">
    <input type="password" name="new_password_confirm" placeholder="Confirmar nova senha" required autocomplete="new-password">
    <button class="recovery-submit" name="recover_access" value="1">Salvar novo acesso</button>
    <div class="recovery-area">
      <a class="recovery-link" href="<?= safeText(basename($_SERVER['PHP_SELF'] ?? 'login.php')) ?>">Voltar para o login</a>
    </div>
  </form>
  <?php } else { ?>
  <form method="post" class="form" autocomplete="off">
    <input type="hidden" name="csrf_token" value="<?= safeText(csrf_token()) ?>">
    <input type="text" name="username" placeholder="Usuário" required autofocus autocomplete="username">
    <input type="password" name="password" placeholder="Senha" required autocomplete="current-password">
    <button name="login" value="1">Entrar</button>
    <div class="recovery-area">
      <a class="recovery-link" href="?recuperar=1">Recuperar acesso</a>
    </div>
  </form>
  <?php } ?>

  <div class="footer">
    © <?= date("Y") ?> <?= safeText($panelName) ?>
  </div>
</div>

</body>
</html>
